Presentation is loading. Please wait.

Presentation is loading. Please wait.

 2003 Prentice Hall, Inc. All rights reserved. 1 Sequential execution –Statements executed in order Transfer of control –Next statement executed not next.

Similar presentations


Presentation on theme: " 2003 Prentice Hall, Inc. All rights reserved. 1 Sequential execution –Statements executed in order Transfer of control –Next statement executed not next."— Presentation transcript:

1  2003 Prentice Hall, Inc. All rights reserved. 1 Sequential execution –Statements executed in order Transfer of control –Next statement executed not next one in sequence 3 control structures (Bohm and Jacopini) –Sequence structure Programs executed sequentially by default –Selection structures if, if/else, switch –Repetition structures while, do/while, for Chapter 2 - Control Structures

2  2003 Prentice Hall, Inc. All rights reserved. 2 Problem : Compute and print the summation of two numbers. #include void main() { int a, b, s; cout >a>>b; s = a + b; cout<<"s="<<s<<endl; } 2.1Sequential programs

3  2003 Prentice Hall, Inc. All rights reserved. 3 Problem : Compute the area of the circle. Where area = R 2 π #include void main() { const double Pi = 3.14; int r; cout >r; double a; a = Pi * r * r; cout<<"\n Circle's Area = "<<a<<endl; }

4  2003 Prentice Hall, Inc. All rights reserved. 4 C++ keywords –Cannot be used as identifiers or variable names

5  2003 Prentice Hall, Inc. All rights reserved. 5 2.2if Selection Structure Selection structure –Choose among alternative courses of action –If the condition is true Print statement executed, program continues to next statement –If the condition is false Print statement ignored, program continues –Indenting makes programs easier to read C++ ignores whitespace characters (tabs, spaces, etc.)

6  2003 Prentice Hall, Inc. All rights reserved. 6 2.2if Selection Structure Translation into C++ If student’s grade is greater than or equal to 60 Print “Passed” if ( grade >= 60 ) cout << "Passed"; if structure –Single-entry/single-exit

7  2003 Prentice Hall, Inc. All rights reserved. 7 2.3 if/else Selection Structure if –Performs action if condition true if/else –Different actions if conditions true or false C++ code if ( grade >= 60 ) cout << "Passed"; else cout << "Failed";

8  2003 Prentice Hall, Inc. All rights reserved. 8 2.3 if/else Selection Structure Ternary conditional operator ( ?: ) –Three arguments (condition, value if true, value if false ) Code could be written: cout = 60 ? “Passed” : “Failed” ); ConditionValue if trueValue if false

9  2003 Prentice Hall, Inc. All rights reserved. 9 Example if ( grade >= 90 ) // 90 and above cout = 80 ) // 80-89 cout = 70 ) // 70-79 cout = 60 ) // 60-69 cout << "D"; else // less than 60 cout << "F"; 2.3if/else Selection Structure Nested if/else structures

10  2003 Prentice Hall, Inc. All rights reserved. 10 2.3 if/else Selection Structure Compound statement –Set of statements within a pair of braces if ( grade >= 60 ) cout << "Passed.\n"; else { cout << "Failed.\n"; cout << "You must take this course again.\n"; } –Without braces, cout << "You must take this course again.\n"; always executed Block –Set of statements within braces

11  2003 Prentice Hall, Inc. All rights reserved. 11 Another example if ( x>y) {if ( x<z) cout<<“ Hello”;} else cout<<“Hi”;

12  2003 Prentice Hall, Inc. All rights reserved. 12 2.4while Repetition Structure Repetition structure –Action repeated while some condition remains true –while loop repeated until condition becomes false Example int product = 2; while ( product <= 1000 ) product = 2 * product;

13  2003 Prentice Hall, Inc. All rights reserved. 13 Counter-controlled repetition –Loop repeated until counter reaches certain value Definite repetition –Number of repetitions known Example A class of ten students took a quiz. The grades (integers in the range 0 to 100) for this quiz are available to you. Determine the class average on the quiz.

14  2003 Prentice Hall, Inc. All rights reserved. Outline 14 fig02_07.cpp (1 of 2) 1 // Fig. 2.7: fig02_07.cpp 2 // Class average program with counter-controlled repetition. 3 #include 4 5 using std::cout; 6 using std::cin; 7 using std::endl; 8 9 // function main begins program execution 10 int main() 11 { 12 int total; // sum of grades input by user 13 int gradeCounter; // number of grade to be entered next 14 int grade; // grade value 15 int average; // average of grades 16 17 // initialization phase 18 total = 0; // initialize total 19 gradeCounter = 1; // initialize loop counter 20

15  2003 Prentice Hall, Inc. All rights reserved. Outline 15 fig02_07.cpp (2 of 2) fig02_07.cpp output (1 of 1) 21 // processing phase 22 while ( gradeCounter <= 10 ) { // loop 10 times 23 cout << "Enter grade: "; // prompt for input 24 cin >> grade; // read grade from user 25 total = total + grade; // add grade to total 26 gradeCounter = gradeCounter + 1; // increment counter 27 } 28 29 // termination phase 30 average = total / 10; // integer division 31 32 // display result 33 cout << "Class average is " << average << endl; 34 35 return 0; // indicate program ended successfully 36 37 } // end function main Enter grade: 98 Enter grade: 76 Enter grade: 71 Enter grade: 87 Enter grade: 83 Enter grade: 90 Enter grade: 57 Enter grade: 79 Enter grade: 82 Enter grade: 94 Class average is 81 The counter gets incremented each time the loop executes. Eventually, the counter causes the loop to end.

16  2003 Prentice Hall, Inc. All rights reserved. 16 2.5Assignment Operators Assignment expression abbreviations –Addition assignment operator c = c + 3; abbreviated to c += 3; Statements of the form variable = variable operator expression; can be rewritten as variable operator= expression; Other assignment operators d -= 4 (d = d - 4) e *= 5 (e = e * 5) f /= 3 (f = f / 3) g %= 9 (g = g % 9)

17  2003 Prentice Hall, Inc. All rights reserved. 17 2.5Increment and Decrement Operators Increment operator ( ++ ) - can be used instead of c += 1 Decrement operator ( -- ) - can be used instead of c -= 1 –Preincrement When the operator is used before the variable ( ++c or –c ) Variable is changed, then the expression it is in is evaluated. –Posincrement When the operator is used after the variable ( c++ or c-- ) Expression the variable is in executes, then the variable is changed.

18  2003 Prentice Hall, Inc. All rights reserved. 18 2.5Increment and Decrement Operators Increment operator ( ++ ) –Increment variable by one –c++ Same as c += 1 Decrement operator ( -- ) similar –Decrement variable by one –c--

19  2003 Prentice Hall, Inc. All rights reserved. 19 2.5Increment and Decrement Operators Preincrement –Variable changed before used in expression Operator before variable ( ++c or --c ) Postincrement –Incremented changed after expression Operator after variable ( c++, c-- )

20  2003 Prentice Hall, Inc. All rights reserved. 20 2.5Increment and Decrement Operators If c = 5, then –cout << ++c; c is changed to 6, then printed out –cout << c++; Prints out 5 ( cout is executed before the increment. c then becomes 6

21  2003 Prentice Hall, Inc. All rights reserved. 21 2.5Increment and Decrement Operators When variable not in expression –Preincrementing and postincrementing have same effect ++c; cout << c; and c++; cout << c; are the same

22  2003 Prentice Hall, Inc. All rights reserved. Outline 22 fig02_14.cpp (1 of 2) 1 // Fig. 2.14: fig02_14.cpp 2 // Preincrementing and postincrementing. 3 #include 4 5 using std::cout; 6 using std::endl; 7 8 // function main begins program execution 9 int main() 10 { 11 int c; // declare variable 12 13 // demonstrate postincrement 14 c = 5; // assign 5 to c 15 cout << c << endl; // print 5 16 cout << c++ << endl; // print 5 then postincrement 17 cout << c << endl << endl; // print 6 18 19 // demonstrate preincrement 20 c = 5; // assign 5 to c 21 cout << c << endl; // print 5 22 cout << ++c << endl; // preincrement then print 6 23 cout << c << endl; // print 6

23  2003 Prentice Hall, Inc. All rights reserved. Outline 23 fig02_14.cpp (2 of 2) fig02_14.cpp output (1 of 1) 24 25 return 0; // indicate successful termination 26 27 } // end function main 556 566556 566

24  2003 Prentice Hall, Inc. All rights reserved. 24 2.6Essentials of Counter-Controlled Repetition Counter-controlled repetition requires –Name of control variable/loop counter –Initial value of control variable –Condition to test for final value –Increment/decrement to modify control variable when looping

25  2003 Prentice Hall, Inc. All rights reserved. Outline 25 fig02_16.cpp (1 of 1) 1 // Fig. 2.16: fig02_16.cpp 2 // Counter-controlled repetition. 3 #include 4 5 using std::cout; 6 using std::endl; 7 8 // function main begins program execution 9 int main() 10 { 11 int counter = 1; // initialization 12 13 while ( counter <= 10 ) { // repetition condition 14 cout << counter << endl; // display counter 15 ++counter; // increment 16 17 } // end while 18 19 return 0; // indicate successful termination 20 21 } // end function main

26  2003 Prentice Hall, Inc. All rights reserved. Outline 26 fig02_16.cpp output (1 of 1) 1 2 3 4 5 6 7 8 9 10

27  2003 Prentice Hall, Inc. All rights reserved. 27 Problem : Print the following numbers. 1357911 #include void main() { int i=1; while (i <= 11) { cout<<i<<'\t'; i+=2; } } Remark: Write ((i+=2) <= 11 ) condition instead of the above one. What changes you have to do to produce the same output.

28  2003 Prentice Hall, Inc. All rights reserved. 28 Problem : Read five numbers from the user and print the positive numbers only. #include void main() { int num, j=0; while ( j++ < 5 ) { cout<<"Enter the next num:"; cin>>num; if (num > 0) cout<<num<<endl; } }

29  2003 Prentice Hall, Inc. All rights reserved. 29 Problem : Compute and Print the value of M where M = 2 * 4 * 6 * … * n #include void main() { int N, M=1, i=2; cout<<"Enter the upper limit:"; cin>>N; while ( i <= N ) { M *= i; i += 2; } cout<<"\nM="<<M; }

30  2003 Prentice Hall, Inc. All rights reserved. 30 2.6Essentials of Counter-Controlled Repetition The declaration int counter = 1; –Names counter –Declares counter to be an integer –Reserves space for counter in memory –Sets counter to an initial value of 1

31  2003 Prentice Hall, Inc. All rights reserved. 31 2.7for Repetition Structure General format when using for loops for ( initialization; LoopContinuationTest; increment ) statement Example for( int counter = 1; counter <= 10; counter++ ) cout << counter << endl; –Prints integers from one to ten No semicolon after last statement

32  2003 Prentice Hall, Inc. All rights reserved. Outline 32 fig02_17.cpp (1 of 1) 1 // Fig. 2.17: fig02_17.cpp 2 // Counter-controlled repetition with the for structure. 3 #include 4 5 using std::cout; 6 using std::endl; 7 8 // function main begins program execution 9 int main() 10 { 11 // Initialization, repetition condition and incrementing 12 // are all included in the for structure header. 13 14 for ( int counter = 1; counter <= 10; counter++ ) 15 cout << counter << endl; 16 17 return 0; // indicate successful termination 18 19 } // end function main

33  2003 Prentice Hall, Inc. All rights reserved. Outline 33 fig02_17.cpp output (1 of 1) 1 2 3 4 5 6 7 8 9 10

34  2003 Prentice Hall, Inc. All rights reserved. 34 Problem : Print the following numbers. 1357911 #include void main( ) { for (int k=1; k<=11; k+=2) cout<<k<<“\t”; cout<<endl; }

35  2003 Prentice Hall, Inc. All rights reserved. 35 Problem : Print the following numbers. 20171411852 #include void main() { for (int m=20; m>=2; m-=3) cout<<m<<“\t”; cout<<endl; }

36  2003 Prentice Hall, Inc. All rights reserved. 36 Problem : Compute and print the summation of any 10 numbers entered by the user. #include void main() { int S=0, N; for (int i=10; i>=1; i--) { cout >N; S+=N;} cout<<"\nS="<<S<<endl; }

37  2003 Prentice Hall, Inc. All rights reserved. 37 Problem : Compute and Print the factorial of the number 5. (Fact = 5 * 4 * 3 * 2 * 1) #include void main( ) { int Fact=1; for (int j=5; j>=1; j--) Fact *= j; cout<<"5!= "<<Fact<<endl; }

38  2003 Prentice Hall, Inc. All rights reserved. 38 Note: for loops can usually be rewritten as while loops initialization; while ( loopContinuationTest){ statement increment; } Initialization and increment –For multiple variables, use comma-separated lists for (int i = 0, j = 0; j + i <= 10; j++, i++) cout << j + i << endl;

39  2003 Prentice Hall, Inc. All rights reserved. 39 2.8switch Multiple-Selection Structure switch –Test variable for multiple values –Series of case labels and optional default case switch ( variable ) { case value1: // taken if variable == value1 statements break; // necessary to exit switch case value2: case value3: // taken if variable == value2 or == value3 statements break; default: // taken if variable matches no other cases statements break; }

40  2003 Prentice Hall, Inc. All rights reserved. 40 2.8switch Multiple-Selection Structure

41  2003 Prentice Hall, Inc. All rights reserved. 41 Switch(grade) {case ‘A’: cout<<“The Grade is A”; break; case ‘B’: cout<<“The Grade is B”; break; case ‘C’: cout<<“The Grade is C”; break; case ‘D’: cout<<“The Grade is D”; break; case ‘F’: cout<<“The Grade is F”; break; Default: cout<< “The Grade is invalid”; } switch examples

42  2003 Prentice Hall, Inc. All rights reserved. 42 #include int main() { int a; cout<<“ Enter an Integer between 0 and 10: “; cin>>a; cout<<“\nThe number you entered is “<<a<<endl; switch(a) { case 0: case 1: cout<<“hello”; case 2: cout<<“there”; case 3: cout<<“I am”; case 4: cout<<“Mickey”<<endl; break; case 5: cout<<“How “; case 6: case 7: case 8: cout<<“are you “<<endl; break; case 9: break; case 10: cout<<“Have a nice day. “<<endl; break; default: cout<<“sorry, the number is out of range.”<<endl; } cout<< “ out of switch structure.”<<endl; return 0; }//main switch examples

43  2003 Prentice Hall, Inc. All rights reserved. 43 Switch(score/10) { case 0: case 1: case 2: case 3: case 4: case 5: grade = ‘F’; break; case 6: grade = ‘D’; break; case 7: grade = ‘C’; break; case 8: grade = ‘B’; break; case 9: case 10: grade = ‘A’; break; default: cout<<“Invalid test score.”<<endl; } switch examples

44  2003 Prentice Hall, Inc. All rights reserved. 44 Switch (age>=18) { case 1: cout<<“old enough to be drafted.”<<endl; cout<< “old enough to vote.”<<endl; break; case 0: cout<<“Not old enough to be drafted.”<<endl; cout<< “Not old enough to vote.”<<endl; } switch examples

45  2003 Prentice Hall, Inc. All rights reserved. 45 2.9do/while Repetition Structure Similar to while structure –Makes loop continuation test at end, not beginning –Loop body executes at least once Format do { statement } while ( condition );

46  2003 Prentice Hall, Inc. All rights reserved. Outline 46 fig02_24.cpp (1 of 1) fig02_24.cpp output (1 of 1) 1 // Fig. 2.24: fig02_24.cpp 2 // Using the do/while repetition structure. 3 #include 4 5 using std::cout; 6 using std::endl; 7 8 // function main begins program execution 9 int main() 10 { 11 int counter = 1; // initialize counter 12 13 do { 14 cout << counter << " "; // display counter 15 } while ( ++counter <= 10 ); // end do/while 16 17 cout << endl; 18 19 return 0; // indicate successful termination 20 21 } // end function main 1 2 3 4 5 6 7 8 9 10 Notice the preincrement in loop-continuation test.

47  2003 Prentice Hall, Inc. All rights reserved. 47 2.10break and continue Statements break statement –Immediate exit from while, for, do/while, switch –Program continues with first statement after structure Common uses –Escape early from a loop –Skip the remainder of switch

48  2003 Prentice Hall, Inc. All rights reserved. Outline 48 fig02_26.cpp (1 of 2) 1 // Fig. 2.26: fig02_26.cpp 2 // Using the break statement in a for structure. 3 #include 4 5 using std::cout; 6 using std::endl; 7 8 // function main begins program execution 9 int main() 10 { 11 12 int x; // x declared here so it can be used after the loop 13 14 // loop 10 times 15 for ( x = 1; x <= 10; x++ ) { 16 17 // if x is 5, terminate loop 18 if ( x == 5 ) 19 break; // break loop only if x is 5 20 21 cout << x << " "; // display value of x 22 23 } // end for 24 25 cout << "\nBroke out of loop when x became " << x << endl; Exits for structure when break executed.

49  2003 Prentice Hall, Inc. All rights reserved. Outline 49 fig02_26.cpp (2 of 2) fig02_26.cpp output (1 of 1) 26 27 return 0; // indicate successful termination 28 29 } // end function main 1 2 3 4 Broke out of loop when x became 5

50  2003 Prentice Hall, Inc. All rights reserved. 50 2.10break and continue Statements continue statement –Used in while, for, do/while –Skips remainder of loop body –Proceeds with next iteration of loop while and do/while structure –Loop-continuation test evaluated immediately after the continue statement for structure –Increment expression executed –Next, loop-continuation test evaluated

51  2003 Prentice Hall, Inc. All rights reserved. Outline 51 fig02_27.cpp (1 of 2) 1 // Fig. 2.27: fig02_27.cpp 2 // Using the continue statement in a for structure. 3 #include 4 5 using std::cout; 6 using std::endl; 7 8 // function main begins program execution 9 int main() 10 { 11 // loop 10 times 12 for ( int x = 1; x <= 10; x++ ) { 13 14 // if x is 5, continue with next iteration of loop 15 if ( x == 5 ) 16 continue; // skip remaining code in loop body 17 18 cout << x << " "; // display value of x 19 20 } // end for structure 21 22 cout << "\nUsed continue to skip printing the value 5" 23 << endl; 24 25 return 0; // indicate successful termination Skips to next iteration of the loop.

52  2003 Prentice Hall, Inc. All rights reserved. Outline 52 fig02_27.cpp (2 of 2) fig02_27.cpp output (1 of 1) 26 27 } // end function main 1 2 3 4 6 7 8 9 10 Used continue to skip printing the value 5

53  2003 Prentice Hall, Inc. All rights reserved. 53 2.11Logical Operators Used as conditions in loops, if statements && (logical AND ) –true if both conditions are true if ( gender == 1 && age >= 65 ) ++seniorFemales; || (logical OR ) –true if either of condition is true if ( semesterAverage >= 90 || finalExam >= 90 ) cout << "Student grade is A" << endl;

54  2003 Prentice Hall, Inc. All rights reserved. 54 2.11Logical Operators ! (logical NOT, logical negation) –Returns true when its condition is false, & vice versa if ( !( grade == sentinelValue ) ) cout << "The next grade is " << grade << endl; Alternative: if ( grade != sentinelValue ) cout << "The next grade is " << grade << endl;

55  2003 Prentice Hall, Inc. All rights reserved. 55 2.12Confusing Equality (==) and Assignment (=) Operators Common error –Does not typically cause syntax errors Aspects of problem –Expressions that have a value can be used for decision Zero = false, nonzero = true –Assignment statements produce a value (the value to be assigned)

56  2003 Prentice Hall, Inc. All rights reserved. 56 2.12Confusing Equality (==) and Assignment (=) Operators Example if ( payCode == 4 ) cout << "You get a bonus!" << endl; –If paycode is 4, bonus given If == was replaced with = if ( payCode = 4 ) cout << "You get a bonus!" << endl; –Paycode set to 4 (no matter what it was before) –Statement is true (since 4 is non-zero) –Bonus given in every case

57  2003 Prentice Hall, Inc. All rights reserved. 57 2.12Confusing Equality (==) and Assignment (=) Operators Lvalues –Expressions that can appear on left side of equation –Can be changed (I.e., variables) x = 4; Rvalues –Only appear on right side of equation –Constants, such as numbers (i.e. cannot write 4 = x; ) Lvalues can be used as rvalues, but not vice versa

58  2003 Prentice Hall, Inc. All rights reserved. 58 2.13 Operator Precedence PrecedenceDescriptionOperator Highestparentheses ( ) unary plus, unary minus, Not +, –, ! *, /, % Binary plus, binary minus +, -, >= Equal, not equal ==, != && || LowestAssignment =

59  2003 Prentice Hall, Inc. All rights reserved. 59 Find the value of the following expression: (1) 5 + 8 * 2 / 4 16 4 9 (This is the final result) 2.13 Operator Precedence

60  2003 Prentice Hall, Inc. All rights reserved. 60 Find value of the following expression ( 9 + 3 ) - 6 / 3 + 5 12 2 10` 15 (this is the final result) 2.13 Operator Precedence

61  2003 Prentice Hall, Inc. All rights reserved. 61 Find the value of the following Expression If x = True, y = False, z = False, find the value of the expression x && y || z x && y || z False False (the final result) 2.13 Operator Precedence

62  2003 Prentice Hall, Inc. All rights reserved. 62 X=true, Y=false, Z= true X || Y && Z true X=true, Y=false, Z= false X || Y && Z true 2.13 Operator Precedence

63  2003 Prentice Hall, Inc. All rights reserved. 63 If a = 3, b = 5, x = true, y = false, find the value of the expression: ( a < b ) AND y OR x ( a < b ) && y || x True False True (the final result) Find the value of the following Expression 2.13 Operator Precedence

64  2003 Prentice Hall, Inc. All rights reserved. 64 What is the output of the following code: #include void main() { int a=10, b=3; cout = b*2 || a>b+9 is \t" = b*2 || a>b+9)<<endl; } 2.13 Operator Precedence

65  2003 Prentice Hall, Inc. All rights reserved. 65 Print the following shape ***** cin>>n; for(int i=1;i<=n;i++) { for (int j=1;j<=n;j++) cout<<“*”; cout<<endl; } Nested for 2.14 Nested Loops

66  2003 Prentice Hall, Inc. All rights reserved. 66 Problem : Draw the following shape * ** *** **** ***** #include void main( ) { for (int raw=1; raw<=5; raw++) { for (int C=1; C<=raw; C++) cout<<'*'; cout<<endl; } } Nested for

67  2003 Prentice Hall, Inc. All rights reserved. 67 Problem : display the multiplication table for the numbers from 1 to 5. 12345 246810 3691215 48121620 510152025 Nested for

68  2003 Prentice Hall, Inc. All rights reserved. 68 for (int i=1;i<=5;i++) { for(int j=1;j<=5;j++) cout<<i*j<<“\t”; cout<<endl; } Nested for

69  2003 Prentice Hall, Inc. All rights reserved. 69 S=m 0 + m 1 + … +m n #include void main() {int s=0,n,m; int t=1; cout<<"Enter m please "; cin>>m; cout<<"Enter n please "; cin>>n; for (int i=0;i<=n;i++) { t=1; for (int j=1;j<=i;j++) t=t*m; s=s+t; } cout<<s<<endl; } Nested for

70  2003 Prentice Hall, Inc. All rights reserved. 70 Problem : Draw the following shape * ** *** **** ***** #include void main() { int i=1; while (i <= 5) { int j=1; while (j<=i) { cout<<'*'; j++;} cout<<endl; i++; } } Nested While


Download ppt " 2003 Prentice Hall, Inc. All rights reserved. 1 Sequential execution –Statements executed in order Transfer of control –Next statement executed not next."

Similar presentations


Ads by Google