The Result of The Assignment #1: C++ Language Control Statement
The Result of The Assignment #1: C++ Language Control Statement
Presenter:HaVietUyen Synh,Ph.D.
Overview
if Selection Statement
The if selection statement allows us to state that an action (sequence of statements) should happen only when some condition is true:
if (condition)
action; The condition used in an if (and other control structures) is a Boolean value - either true or false. In C++: the value 0 is false anything else is true
if ( grade >= 60 ) cout << "Passed";
Example
Writeaprogramthatfindstherootofthelinearequationgivenbyax +bwherea,baretheargumentstotheprogram. Inthecase,a!=0 x=b/a Intheothercase,a==0 Ifb==0 xisundetermined Ifb!=0 xisnosolution.
if ( studentGrade >= 90 ) // 90 and above gets "A" cout << "A"; else if ( studentGrade >= 80 ) // 80-89 gets "B" cout << "B"; else if ( studentGrade >= 70 ) // 70-79 gets "C" cout << "C"; else if ( studentGrade >= 60 ) // 60-69 gets "D" cout << "D"; else // less than 60 gets "F" cout << "F";
Example
Writeaprogramthatfindstherootsofthequadraticequationgiven bya*x^2+b*x+cwherea,bandcaretheargumentstothe program. Delta=b^2 4*a*c IfDelta>0, x1,2 =(b sqrt(Delta))/(2*a) IfDelta==0, x=b/(2*a) IfDelta!=0, xisnosolution
11
while (condition)
do something;
// Calculate 3n with 3n<=100 int product = 3; while ( product <= 100) product = 3 * product;
Counter-controlled repetition
//Fig.5.1:fig05_01.cpp //Countercontrolledrepetition. #include<iostream> usingstd::cout; usingstd::endl; intmain() { intcounter=1;//declareandinitializecontrolvariable while(counter<=10)//loopcontinuationcondition { cout<<counter<<""; counter++;//incrementcontrolvariableby1 }//endwhile cout<<endl;//outputanewline return0;//successfultermination }//endmain 12345678910
12345678910
Example
Writeaprogramthatcalculatesfactorialofn(n!),wherenisthe argumenttotheprogram
16
do
somestuff;
while ( condition );
The School of Computer Science and Engineering (SCSE)
break Statement
The break statement, when executed in a while, for, do...while or switch statement, causes immediate exit from that statement. Program execution continues with the next statement. Common uses of the break statement are to escape early from a loop or to skip the remainder of a switch statement
1 // Fig. 5.13: fig05_13.cpp 2 // break statement exiting a for statement. 3 #include <iostream> 4 using std::cout; 5 using std::endl; 6 7 int main() 8{ 9 int count; // control variable also used after loop terminates 10 11 for ( count = 1; count <= 10; count++ ) // loop 10 times 12 { 13 if ( count == 5 ) 14 break; // break loop only if x is 5 15 16 cout << count << " "; 17 } // end for 18 19 cout << "\nBroke out of loop at count = " << count << endl; 20 return 0; // indicate successful termination 21 } // end main
continue Statement
The continue statement, when executed in a while, for or do...while statement, skips the remaining statements in the body of that statement and proceeds with the next iteration of the loop. In while and do...while statements, the loopcontinuation test evaluates immediately after the continue statement executes. In the for statement, the increment expression executes, then the loopcontinuation test evaluates.
1 // Fig. 5.14: fig05_14.cpp 2 // continue statement terminating an iteration 3 #include <iostream> 4 5 6 7 8 9 10 11 12 13 14 15 16 17 cout << "\nUsed continue to skip printing 5 " << endl; 18 19 return 0; } // end main int main() { for ( int count = 1; count <= 10; count++ ) { if ( count == 5 ) // if count is 5, continue; // skip remaining code using std::cout; using std::endl;
10
Any Questions?
Contact
[email protected]
Exercise 1
WriteC++statementstoaccomplisheachofthefollowingtasks. Declarevariablessumandxtobeoftypeint. Setvariablexto1. Setvariablesumto0. Addvariablextovariablesumandassigntheresulttovariablesum. Print"Thesumis:"followedbythevalueofvariablesum. Calculateandprintthesumoftheintegersfrom1to10.Usethe whilestatementtoloopthroughthecalculationandincrement statements.Theloopshouldterminatewhenthevalueofxbecomes 11.
11
Exercise 2
WritesingleC++statementsthatdothefollowing: Inputintegervariablexwithcin and>>. Inputintegervariableywithcin and>>. Setintegervariablei to1. Setintegervariablepowerto1. Multiplyvariablepowerbyxandassigntheresulttopower. Determinewhetheri islessthanorequaltoy. Outputintegervariablepowerwithcout and<<. Calculatexraisedtothepowery.Theprogramshouldhaveawhile repetitionstatement.
Exercise 3
WriteaC++statementorasetofC++statementstoaccomplisheach ofthefollowing: Sumtheoddintegersbetween1and99usingaforstatement. Assumetheintegervariablessumandcounthavebeendeclared. Calculatethevalueof2.5raisedtothepower3usingfunctionpow. Whatprints? Printtheintegersfrom1to20usingawhileloopandthecounter variablex.Assumethatthevariablexhasbeendeclared,butnot initialized.Printonly5integersperline.[Hint:Usethecalculationx %5.Whenthevalueofthisis0,printanewlinecharacter; otherwise,printatabcharacter.] Repeat(d)usingaforstatement.
12
Exercise 4
Write single C++ statements that do the following: Input integer variable n with n>0. Calculate 2n Calculate n! Calculate
Calculate
Exercise 5
Write a C++ program to accomplish the following: Input integer variable n with n>0. How many digits are there in the variable n? Calculate the sum of all digits which there are in variable n.
13
Exercise 6
Write single C++ statements that do the following: Input integer variable n with n>0. Check whether n is a prime number. Calculate the first n prime numbers.
14