1 Chapter 2 Control Structures Sequential execution Statements

  • Slides: 70
Download presentation
1 Chapter 2 - Control Structures • Sequential execution – Statements executed in order

1 Chapter 2 - Control Structures • 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 2003 Prentice Hall, Inc. All rights reserved.

2. 1 Sequential programs Problem : Compute and print the summation of two numbers.

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

3 Problem : Compute the area of the circle. Where area = R 2

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

4 • C++ keywords – Cannot be used as identifiers or variable names 2003

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

5 2. 2 if Selection Structure • Selection structure – Choose among alternative courses

5 2. 2 if 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. ) 2003 Prentice Hall, Inc. All rights reserved.

6 2. 2 if Selection Structure • Translation into C++ If student’s grade is

6 2. 2 if 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 2003 Prentice Hall, Inc. All rights reserved.

7 2. 3 if/else Selection Structure • if – Performs action if condition true

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"; 2003 Prentice Hall, Inc. All rights reserved.

8 2. 3 if/else Selection Structure • Ternary conditional operator (? : ) –

8 2. 3 if/else Selection Structure • Ternary conditional operator (? : ) – Three arguments (condition, value if true, value if false) • Code could be written: cout << ( grade >= 60 ? “Passed” : “Failed” ); Condition 2003 Prentice Hall, Inc. All rights reserved. Value if true Value if false

2. 3 if/else Selection Structure Nested if/else structures • Example if ( grade >=

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

10 2. 3 if/else Selection Structure • Compound statement – Set of statements within

10 2. 3 if/else Selection Structure • Compound statement – Set of statements within a pair of braces if ( grade cout << else { cout << >= 60 ) "Passed. n"; "Failed. n"; "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 2003 Prentice Hall, Inc. All rights reserved.

11 Another example if ( x>y) {if ( x<z) cout<<“ Hello”; } else cout<<“Hi”;

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

12 2. 4 while Repetition Structure • Repetition structure – Action repeated while some

12 2. 4 while 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; 2003 Prentice Hall, Inc. All rights reserved.

13 • Counter-controlled repetition – Loop repeated until counter reaches certain value • Definite

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. 2003 Prentice Hall, Inc. All rights reserved.

1 2 3 // Fig. 2. 7: fig 02_07. cpp // Class average program

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

21 22 23 24 25 26 27 // processing phase while ( grade. Counter

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

16 2. 5 Assignment Operators • Assignment expression abbreviations – Addition assignment operator c

16 2. 5 Assignment 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 e f g -= *= /= %= 4 5 3 9 2003 Prentice Hall, Inc. All rights reserved. (d (e (f (g = = d e f g * / % 4) 5) 3) 9)

17 2. 5 Increment and Decrement Operators • Increment operator (++) - can be

17 2. 5 Increment 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. 2003 Prentice Hall, Inc. All rights reserved.

18 2. 5 Increment and Decrement Operators • Increment operator (++) – Increment variable

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

19 2. 5 Increment and Decrement Operators • Preincrement – Variable changed before used

19 2. 5 Increment 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--) 2003 Prentice Hall, Inc. All rights reserved.

20 2. 5 Increment and Decrement Operators • If c = 5, then –

20 2. 5 Increment 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 2003 Prentice Hall, Inc. All rights reserved.

21 2. 5 Increment and Decrement Operators • When variable not in expression –

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

1 2 3 // Fig. 2. 14: fig 02_14. cpp // Preincrementing and postincrementing.

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

24 25 26 27 5 5 6 6 return 0; // indicate successful termination

24 25 26 27 5 5 6 6 return 0; // indicate successful termination Outline } // end function main fig 02_14. cpp (2 of 2) fig 02_14. cpp output (1 of 1) 2003 Prentice Hall, Inc. All rights reserved. 23

2. 6 Essentials of Counter-Controlled Repetition • Counter-controlled repetition requires – – Name of

2. 6 Essentials 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 2003 Prentice Hall, Inc. All rights reserved. 24

1 2 3 // Fig. 2. 16: fig 02_16. cpp // Counter-controlled repetition. #include

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

1 2 3 4 5 6 7 8 9 10 Outline fig 02_16. cpp

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

27 Problem : Print the following numbers. 1 3 5 7 9 11 #include

27 Problem : Print the following numbers. 1 3 5 7 9 11 #include <iostream. h> 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. 2003 Prentice Hall, Inc. All rights reserved.

28 Problem : Read five numbers from the user and print the positive numbers

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

29 Problem : Compute and Print the value of M where M = 2

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

2. 6 Essentials of Counter-Controlled Repetition • The declaration int counter = 1; –

2. 6 Essentials 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 2003 Prentice Hall, Inc. All rights reserved. 30

31 2. 7 for Repetition Structure • General format when using for loops for

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

1 2 3 // Fig. 2. 17: fig 02_17. cpp // Counter-controlled repetition with

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

1 2 3 4 5 6 7 8 9 10 Outline fig 02_17. cpp

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

34 Problem : Print the following numbers. 1 3 5 7 #include <iostream. h>

34 Problem : Print the following numbers. 1 3 5 7 #include <iostream. h> void main( ) { for (int k=1; k<=11; k+=2) cout<<k<<“t”; cout<<endl; } 2003 Prentice Hall, Inc. All rights reserved. 9 11

35 Problem : Print the following numbers. 20 17 14 11 8 #include <iostream.

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

36 Problem : Compute and print the summation of any 10 numbers entered by

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

37 Problem : Compute and Print the factorial of the number 5. (Fact =

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

38 • Note: for loops can usually be rewritten as while loops initialization; while

38 • Note: for loops can usually be rewritten as while loops initialization; while ( loop. Continuation. Test){ 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; 2003 Prentice Hall, Inc. All rights reserved.

39 2. 8 switch Multiple-Selection Structure • switch – Test variable for multiple values

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

40 2. 8 switch Multiple-Selection Structure 2003 Prentice Hall, Inc. All rights reserved.

40 2. 8 switch Multiple-Selection Structure 2003 Prentice Hall, Inc. All rights reserved.

41 switch examples Switch(grade) {case ‘A’: cout<<“The Grade is A”; break; case ‘B’: cout<<“The

41 switch examples 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”; } 2003 Prentice Hall, Inc. All rights reserved.

switch examples #include<iostream. h> int main() { int a; cout<<“ Enter an Integer between

switch examples #include<iostream. h> int main() { int a; cout<<“ Enter an Integer between 0 and 10: “; cin>>a; cout<<“n. The 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; 2003 Prentice Hall, Inc. All rights reserved. }//main 42

switch examples Switch(score/10) { case 0: case 1: case 2: case 3: case 4:

switch examples 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; } 2003 Prentice Hall, Inc. All rights reserved. 43

switch examples Switch (age>=18) { case 1: cout<<“old enough to be drafted. ”<<endl; cout<<

switch examples 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; } 2003 Prentice Hall, Inc. All rights reserved. 44

45 2. 9 do/while Repetition Structure • Similar to while structure – Makes loop

45 2. 9 do/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 ); 2003 Prentice Hall, Inc. All rights reserved.

1 2 3 // Fig. 2. 24: fig 02_24. cpp // Using the do/while

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

47 2. 10 break and continue Statements • break statement – Immediate exit from

47 2. 10 break 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 2003 Prentice Hall, Inc. All rights reserved.

1 2 3 // Fig. 2. 26: fig 02_26. cpp // Using the break

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

26 27 28 29 return 0; // indicate successful termination Outline } // end

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

50 2. 10 break and continue Statements • continue statement – Used in while,

50 2. 10 break 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 2003 Prentice Hall, Inc. All rights reserved.

1 2 3 // Fig. 2. 27: fig 02_27. cpp // Using the continue

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

26 27 } // end function main Outline 1 2 3 4 6 7

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

53 2. 11 Logical Operators • Used as conditions in loops, if statements •

53 2. 11 Logical Operators • Used as conditions in loops, if statements • && (logical AND) – true if both conditions are true if ( gender == 1 && age >= 65 ) ++senior. Females; • || (logical OR) – true if either of condition is true if ( semester. Average >= 90 || final. Exam >= 90 ) cout << "Student grade is A" << endl; 2003 Prentice Hall, Inc. All rights reserved.

54 2. 11 Logical Operators • ! (logical NOT, logical negation) – Returns true

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

2. 12 Confusing Equality (==) and Assignment (=) Operators • Common error – Does

2. 12 Confusing 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) 2003 Prentice Hall, Inc. All rights reserved. 55

2. 12 Confusing Equality (==) and Assignment (=) Operators • Example if ( pay.

2. 12 Confusing Equality (==) and Assignment (=) Operators • Example if ( pay. Code == 4 ) cout << "You get a bonus!" << endl; – If paycode is 4, bonus given • If == was replaced with = if ( pay. Code = 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 2003 Prentice Hall, Inc. All rights reserved. 56

2. 12 Confusing Equality (==) and Assignment (=) Operators • Lvalues – Expressions that

2. 12 Confusing 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 2003 Prentice Hall, Inc. All rights reserved. 57

58 2. 13 Operator Precedence Operator Description ( ) parentheses +, – , !

58 2. 13 Operator Precedence Operator Description ( ) parentheses +, – , ! unary plus, unary minus, Not Precedence Highest *, /, % + , - Binary plus, binary minus <, <=, >, >= == , != Equal, not equal && || = Assignment 2003 Prentice Hall, Inc. All rights reserved. Lowest

59 2. 13 Operator Precedence • Find the value of the following expression: (1)

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

2. 13 Operator Precedence Find value of the following expression ( 9 + 3

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

2. 13 Operator Precedence Find the value of the following Expression If x =

2. 13 Operator Precedence 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 (the final result) 2003 Prentice Hall, Inc. All rights reserved. 61

2. 13 Operator Precedence • X=true, Y=false, Z= true X || Y && Z

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

2. 13 Operator Precedence Find the value of the following Expression If a =

2. 13 Operator Precedence Find the value of the following Expression 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) 2003 Prentice Hall, Inc. All rights reserved. 63

64 2. 13 Operator Precedence What is the output of the following code: #include

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

2. 14 Nested Loops Nested for Print the following shape ***** ***** cin>>n; for(int

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

66 Nested for Problem : Draw the following shape * ** ***** #include <iostream.

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

Nested for Problem : display the multiplication table for the numbers from 1 to

Nested for Problem : display the multiplication table for the numbers from 1 to 5. 1 2 3 4 5 2 4 6 8 10 2003 Prentice Hall, Inc. All rights reserved. 3 6 9 12 15 4 8 12 16 20 5 10 15 20 25 67

Nested for (int i=1; i<=5; i++) { for(int j=1; j<=5; j++) cout<<i*j<<“t”; cout<<endl; }

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

Nested for S=m 0 + m 1 + … +mn #include <iostream. h> void

Nested for S=m 0 + m 1 + … +mn #include <iostream. h> 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; } 2003 Prentice Hall, Inc. All rights reserved. 69

Nested While Problem : Draw the following shape * ** ***** #include <iostream. h>

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