# Chapter 2 - Control Structures

Size: px
Start display at page:

Transcription

1 Chapter 2 - Control Structures Assignment Operators 2.12 Increment and Decrement Operators 2.13 Essentials of Counter-Controlled Repetition 2.1 for Repetition Structure 2.15 Examples Using the for Structure 2.16 switch Multiple-Selection Structure 2.1 do/while Repetition Structure 2.18 break and continue Statements 2.19 Logical Operators 2.20 Confusing Equality (==) and Assignment (=) Operators 2.21 Structured-Programming Summary

2 Assignment Operators Assignment expression abbreviations Addition assignment operator c = c + 3; abbreviated to c += 3; Some statements of the form variable = variable operator expression; can be rewritten as variable operator= expression; For example: d -= ; d = d - ; e *= 5; e = e * 5; f /= 3; f = f / 3; g %= 9; g = g % 9;

3 Increment and Decrement Operators Increment operator (c++ or ++c) can be used instead of c += 1 Decrement operator (c-- or --c) can be used instead of c -= 1 Pre-increment (++c, --c) When the operator is used before the variable (++c or --c) Variable is changed, then the surrounding expression evaluated. Post-increment (c++, c--) When the operator is used after the variable (c++ or c--) Surrounding expression is evaluated/executed, then the variable is changed.

4 2.12 Example Exam Questions (c++ vs ++c) Suppose c contains 5. What gets printed? cout << ++c; Answer c is changed to 6, then (cout << c) is evaluated, and 6 is printed. Suppose c contains 5. What gets printed? cout << c++; Answer: 5 is printed. (cout << c) is evaluated before the increment c then becomes 6

5 Increment and Decrement Operators When variable not in expression Preincrementing and postincrementing have same effect ++c; and cout << c; c++; cout << c; are the same

6 1 // Fig. 2.1: fig02_1.cpp 2 // Preincrementing and postincrementing. 3 #include <iostream> 5 using std::cout; 6 using std::endl; 8 // function main begins program execution 9 int main() 10 { 11 int c; // declare variable // demonstrate postincrement 1 c = 5; // assign 5 to c 15 cout << c << endl; // print 5 16 cout << c++ << endl; // print 5 then postincrement 1 cout << c << endl << endl; // print // 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 fig02_1.cpp return 0; // indicate successful termination 26 2 } // end function main

7 1 // Fig. 2.16: fig02_16.cpp 2 // Counter-controlled repetition. 3 #include <iostream> 5 using std::cout; 6 using std::endl; 8 // function main begins program execution 9 int main() 10 { 11 int counter = 1; // initialization while ( counter <= 10 ) { // repetition condition 1 cout << counter << endl; // display counter 15 ++counter; // increment 16 1 } // end while return 0; // indicate successful termination } // end function main fig02_16.cpp (1 of 1) Counter-controlled repetition requires Control variable (loop counter) Initial value for control variable Condition to test for final value Modify control variable while looping (Increment or decrement)

8 1 // Fig. 2.16: fig02_16.cpp 2 // Counter-controlled repetition. 3 #include <iostream> 5 using std::cout; 6 using std::endl; 8 // function main begins program execution 9 int main() 10 { 11 int counter = 1; // initialization while ( counter <= 10 ) { // repetition condition 1 cout << counter << endl; // display counter 15 ++counter; // increment 16 1 } // end while return 0; // indicate successful termination } // end function main fig02_16.cpp (1 of 1) Counter-controlled repetition requires Control variable (loop counter) Initial value for control variable Condition to test for final value Modify control variable while looping (Increment or decrement)

9 1 // Fig. 2.16: fig02_16.cpp 2 // Counter-controlled repetition. 3 #include <iostream> 5 using std::cout; 6 using std::endl; 8 // function main begins program execution 9 int main() 10 { 11 int counter = 1; // initialization while ( counter <= 10 ) { // repetition condition 1 cout << counter << endl; // display counter 15 ++counter; // increment 16 1 } // end while return 0; // indicate successful termination } // end function main fig02_16.cpp (1 of 1) Counter-controlled repetition requires Control variable (loop counter) Initial value for control variable Condition to test for final value Modify control variable while looping (Increment or decrement)

10 1 // Fig. 2.16: fig02_16.cpp 2 // Counter-controlled repetition. 3 #include <iostream> 5 using std::cout; 6 using std::endl; 8 // function main begins program execution 9 int main() 10 { 11 int counter = 1; // initialization while ( counter <= 10 ) { // repetition condition 1 cout << counter << endl; // display counter 15 ++counter; // increment 16 1 } // end while return 0; // indicate successful termination } // end function main fig02_16.cpp (1 of 1) Counter-controlled repetition requires Control variable (loop counter) Initial value for control variable Condition to test for final value Modify control variable while looping (Increment or decrement)

11 1 // Fig. 2.16: fig02_16.cpp 2 // Counter-controlled repetition. 3 #include <iostream> 5 using std::cout; 6 using std::endl; 8 // function main begins program execution 9 int main() 10 { 11 int counter = 1; // initialization while ( counter <= 10 ) { // repetition condition 1 cout << counter << endl; // display counter 15 ++counter; // increment 16 1 } // end while return 0; // indicate successful termination } // end function main fig02_16.cpp (1 of 1) Counter-controlled repetition requires Control variable (loop counter) Initial value for control variable Condition to test for final value Modify control variable while looping (Increment or decrement)

12 2.13 Essentia ls of Counter-Controlled Repetition 8 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

13 9 2.1 for 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

14 1 // Fig. 2.1: fig02_1.cpp 2 // Counter-controlled repetition with the for structure. 3 #include <iostream> 5 using std::cout; 6 using std::endl; 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 for ( int counter = 1; counter <= 10; counter++ ) 15 cout << counter << endl; 16 1 return 0; // indicate successful termination } // end function main fig02_1.cpp (1 of 1) 10 Control variable (loop counter) Initial value for control variable Condition to test for final value Modify control variable while looping (Increment or decrement)

15 1 // Fig. 2.1: fig02_1.cpp 2 // Counter-controlled repetition with the for structure. 3 #include <iostream> 5 using std::cout; 6 using std::endl; 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 for ( int counter = 1; counter <= 10; counter++ ) 15 cout << counter << endl; 16 1 return 0; // indicate successful termination } // end function main fig02_1.cpp (1 of 1) 10 Control variable (loop counter) Initial value for control variable Condition to test for final value Modify control variable while looping (Increment or decrement)

16 1 // Fig. 2.1: fig02_1.cpp 2 // Counter-controlled repetition with the for structure. 3 #include <iostream> 5 using std::cout; 6 using std::endl; 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 for ( int counter = 1; counter <= 10; counter++ ) 15 cout << counter << endl; 16 1 return 0; // indicate successful termination } // end function main fig02_1.cpp (1 of 1) 10 Control variable (loop counter) Initial value for control variable Condition to test for final value Modify control variable while looping (Increment or decrement)

17 1 // Fig. 2.1: fig02_1.cpp 2 // Counter-controlled repetition with the for structure. 3 #include <iostream> 5 using std::cout; 6 using std::endl; 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 for ( int counter = 1; counter <= 10; counter++ ) 15 cout << counter << endl; 16 1 return 0; // indicate successful termination } // end function main fig02_1.cpp (1 of 1) 10 Control variable (loop counter) Initial value for control variable Condition to test for final value Modify control variable while looping (Increment or decrement)

18 1 // Fig. 2.1: fig02_1.cpp 2 // Counter-controlled repetition with the for structure. 3 #include <iostream> 5 using std::cout; 6 using std::endl; 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 for ( int counter = 1; counter <= 10; counter++ ) 15 cout << counter << endl; 16 1 return 0; // indicate successful termination } // end function main fig02_1.cpp (1 of 1) 10 Control variable (loop counter) Initial value for control variable Condition to test for final value Modify control variable while looping (Increment or decrement)

19 for Repetition Structure 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;

20 1 // Fig. 2.20: fig02_20.cpp 2 // Summation with for. 3 #include <iostream> 5 using std::cout; 6 using std::endl; 8 // function main begins program execution 9 int main() 10 { 11 int sum = 0; // initialize sum // sum even integers from 2 through for ( int number = 2; number <= 100; number += 2 ) 15 sum += number; // add number to sum 16 1 cout << "Sum is " << sum << endl; // output sum 18 return 0; // successful termination } // end function main fig02_20.cpp (1 of 1) fig02_20.cpp output (1 of 1) 12 Sum is 2550

21 2.15 Examples Using the for Structure 13 Program to calculate compound interest A person invests \$ in a savings account yielding 5 percent interest. Assuming that all interest is left on deposit in the account, calculate and print the amount of money in the account at the end of each year for 10 years. Use the following formula for determining these amounts: n a = p(1+r) p is the original amount invested (i.e., the principal), r is the annual interest rate, n is the number of years and a is the amount on deposit at the end of the nth year

22 1 // Fig. 2.21: fig02_21.cpp 2 // Calculating compound interest. 3 #include <iostream> 5 using std::cout; 6 using std::endl; using std::ios; 8 using std::fixed; 9 10 #include <iomanip> using std::setw; 13 using std::setprecision; 1 15 #include <cmath> // enables program to use function pow 16 1 // function main begins program execution 18 int main() 19 { 20 double amount; // amount on deposit 21 double principal = ; // starting principal 22 double rate =.05; // interest rate 23 fig02_21.cpp (1 of 2) 1

23 1 // Fig. 2.21: fig02_21.cpp 2 // Calculating compound interest. 3 #include <iostream> 5 using std::cout; 6 using std::endl; using std::ios; 8 using std::fixed; 9 10 #include <iomanip> using std::setw; 13 using std::setprecision; <cmath> header needed for the pow function (program will not compile without it) #include <cmath> // enables program to use function pow 16 1 // function main begins program execution 18 int main() 19 { 20 double amount; // amount on deposit 21 double principal = ; // starting principal 22 double rate =.05; // interest rate 23 fig02_21.cpp (1 of 2) 1

24 2 // output table column heads 25 cout << "Year" << setw( 21 ) << "Amount on deposit" << endl; 26 2 // set floating-point number format 28 cout << fixed << setprecision( 2 ); // calculate amount on deposit for each of ten years 31 for ( int year = 1; year <= 10; year++ ) { // calculate new amount for specified year 3 amount = principal * pow( rate, year ); // output one table row 3 cout << setw( ) << year 38 << setw( 21 ) << amount << endl; 39 0 } // end for 1 2 return 0; // indicate successful termination 3 } // end function main fig02_21.cpp (2 of 2) Year Amount on deposit

25 2 // output table column heads 25 cout << "Year" << setw( 21 ) << "Amount on deposit" << endl; 26 2 // set floating-point number format 28 cout << fixed << setprecision( 2 ); // calculate amount on deposit for each of ten years 31 for ( int year = 1; year <= 10; year++ ) { // calculate new amount for specified year 3 amount = principal * pow( rate, year ); // output one table row 3 cout << setw( ) << year 38 << setw( 21 ) << amount << endl; 39 0 } // end for 1 2 return 0; // indicate successful termination 3 } // end function main Sets the field width to at least 21 characters. If output less than 21, it is right-justified. fig02_21.cpp (2 of 2) Year Amount on deposit

26 2 // output table column heads 25 cout << "Year" << setw( 21 ) << "Amount on deposit" << endl; 26 2 // set floating-point number format 28 cout << fixed << setprecision( 2 ); // calculate amount on deposit for each of ten years 31 for ( int year = 1; year <= 10; year++ ) { // calculate new amount for specified year 3 amount = principal * pow( rate, year ); // output one table row 3 cout << setw( ) << year 38 << setw( 21 ) << amount << endl; 39 0 } // end for 1 2 return 0; // indicate successful termination 3 } // end function main pow(x,y) = x raised to the yth power. fig02_21.cpp (2 of 2) Year Amount on deposit

27 2.16 switch Multiple-Selection Structure 16 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;

28 2.16 switch Multiple-Selection Structure 1 true case a case a action(s) break false true case b case b action(s) break... false true case z case z action(s) break false default action(s)

29 2.16 char data type Example of switch Multiple-Selection Structure upcoming... Program to read grades (A-F) Display number of each grade entered First a few details about characters Single characters typically stored in a char data type char a 1-byte integer, so chars can be stored as ints Can treat character as int or char 9 is the numerical representation of lowercase a (ASCII) 65 is upper case 'A' Use single quotes Cast to int to get numerical representation cout << "The character (" << 'a' << ") has the value " << static_cast< int > ( 'a' ) << endl; 18 The character (a) has the value 9

30 1 // Fig. 2.22: fig02_22.cpp 2 // Counting letter grades. 3 #include <iostream> 5 using std::cout; 6 using std::cin; using std::endl; 8 9 // function main begins program execution 10 int main() 11 { 12 int grade; // one grade 13 int acount = 0; // number of As 1 int bcount = 0; // number of Bs 15 int ccount = 0; // number of Cs 16 int dcount = 0; // number of Ds 1 int fcount = 0; // number of Fs cout << "Enter the letter grades." << endl 20 << "Enter the EOF character to end input." << endl; 21 fig02_22.cpp (1 of ) 19 Enter the letter grades. Enter the EOF character to end input.

31 22 // loop until user types end-of-file key sequence 23 while ( ( grade = cin.get() )!= EOF ) { 2 25 // determine which grade was input 26 switch ( grade ) { // switch structure nested in while 2 28 case 'A': // grade was uppercase A 29 case 'a': // or lowercase a 30 ++acount; // increment acount 31 break; // necessary to exit switch case 'B': // grade was uppercase B 3 case 'b': // or lowercase b 35 ++bcount; // increment bcount 36 break; // exit switch 3 38 case 'C': // grade was uppercase C 39 case 'c': // or lowercase c 0 ++ccount; // increment ccount 1 break; // exit switch 2 fig02_22.cpp (2 of ) Enter the EOF character to end input. a B c C A d f C E Incorrect letter grade entered. Enter a new grade. D A b ^Z 20

32 22 // loop until user types end-of-file key sequence 23 while ( ( grade = cin.get() )!= EOF ) { 2 25 // determine which grade was input 26 switch ( grade ) { // switch structure nested in while 2 28 case 'A': // grade was uppercase A 29 case 'a': // or lowercase a 30 ++acount; // increment acount 31 break; // necessary to exit switch case 'B': // grade was uppercase B 3 case 'b': // or lowercase b 35 ++bcount; // increment bcount 36 break; // exit switch 3 38 case 'C': // grade was uppercase C 39 case 'c': // or lowercase c 0 ++ccount; // increment ccount 1 break; // exit switch 2 fig02_22.cpp (2 of ) Enter the EOF character to end input. a B c C A d f C E cin.get() uses dot notation (explained chapter 6). This function gets 1 character from the keyboard (after Enter pressed), and it is assigned to grade. cin.get() returns EOF (end-of-file) after the EOF character is input, to indicate the end of data. EOF may be ctrl-d or ctrl-z, depending on your OS. Incorrect letter grade entered. Enter a new grade. D A b ^Z 20

33 22 // loop until user types end-of-file key sequence 23 while ( ( grade = cin.get() )!= EOF ) { 2 25 // determine which grade was input 26 switch ( grade ) { // switch structure nested in while 2 28 case 'A': // grade was uppercase A 29 case 'a': // or lowercase a 30 ++acount; // increment acount 31 break; // necessary to exit switch 32 Assignment statements have a 33 case 'B': // grade value, was which uppercase is the same B as the B 3 case 'b': // or variable lowercase on the b left of the =. c 35 ++bcount; // increment The value bcount of this statement isc 36 break; // exit switch A the same as the value returned by cin.get() case 'C': // grade was uppercase C 39 case 'c': // or lowercase c 0 ++ccount; // increment ccount 1 break; // exit switch 2 a = b = c = 0; This can also be used to initialize multiple variables: fig02_22.cpp (2 of ) Enter the EOF character to end input. d f C E Incorrect letter grade entered. Enter a new grade. D A b ^Z 20

34 22 // loop until user types end-of-file key sequence 23 while ( ( grade = cin.get() )!= EOF ) { 2 25 // determine which grade was input 26 switch ( grade ) { // switch structure nested in while 2 28 case 'A': // grade was uppercase A 29 case 'a': // or lowercase a 30 ++acount; // increment acount 31 break; // necessary to exit switch case 'B': // grade was uppercase B 3 case 'b': // or lowercase b 35 ++bcount; // increment bcount 36 break; // exit switch Compares grade (an int) 3 38 to the numerical case 'C': // grade was uppercase C 39 representations case of 'c': A and a. // or lowercase c 0 ++ccount; // increment ccount 1 break; // exit switch 2 fig02_22.cpp (2 of ) Enter the EOF character to end input. a B c C A d f C E Incorrect letter grade entered. Enter a new grade. D A b ^Z 20

35 22 // loop until user types end-of-file key sequence 23 while ( ( grade = cin.get() )!= EOF ) { 2 25 // determine which grade was input 26 switch ( grade ) { // switch structure nested in while 2 28 case 'A': // grade was uppercase A 29 case 'a': // or lowercase a 30 ++acount; // increment acount 31 break; // necessary to exit switch case 'B': // grade was uppercase B 3 case 'b': // or lowercase b 35 ++bcount; // increment bcount 36 break; // exit switch 3 38 case 'C': // grade was uppercase C 39 case 'c': // or lowercase c 0 ++ccount; // increment ccount 1 break; // exit switch 2 break causes switch to end and the program continues with the first statement after the switch structure. fig02_22.cpp (2 of ) Enter the EOF character to end input. a B c C A d f C E Incorrect letter grade entered. Enter a new grade. D A b ^Z 20

36 3 case 'D': // grade was uppercase D case 'd': // or lowercase d 5 ++dcount; // increment dcount 6 break; // exit switch 8 case 'F': // grade was uppercase F 9 case 'f': // or lowercase f 50 ++fcount; // increment fcount 51 break; // exit switch case '\n': // ignore newlines, 5 case '\t': // tabs, 55 case ' ': // and spaces in input 56 break; // exit switch 5 58 default: // catch all other characters 59 cout << "Incorrect letter grade entered." 60 << " Enter a new grade." << endl; 61 break; // optional; will exit switch anyway } // end switch 6 65 } // end while 66 fig02_22.cpp (3 of ) 21 Enter the EOF character to en a B c C A d f C E Incorrect letter grade entere a new grade. D A b ^Z

37 3 case 'D': // grade was uppercase D case 'd': // or lowercase d 5 ++dcount; // increment dcount 6 break; // exit switch 8 case 'F': // grade was Enter uppercase is pressed F after each 9 case 'f': // or lowercase f 50 ++fcount; // increment fcount 51 break; // exit switch be removed. Likewise, we case '\n': // ignore newlines, want to ignore any 5 case '\t': // tabs, whitespace. 55 case ' ': // and spaces in input 56 break; // exit switch 5 58 default: // catch all other characters 59 cout << "Incorrect letter grade entered." 60 << " Enter a new grade." << endl; 61 break; // optional; will exit switch anyway } // end switch 6 65 } // end while 66 This test is necessary because letter grade is input. This adds a newline character that must fig02_22.cpp (3 of ) 21 Enter the EOF character to en a B c C A d f C E Incorrect letter grade entere a new grade. D A b ^Z

38 3 case 'D': // grade was uppercase D case 'd': // or lowercase d 5 ++dcount; // increment dcount 6 break; // exit switch 8 case 'F': // grade was uppercase F 9 case 'f': // or lowercase f 50 ++fcount; // increment fcount 51 break; // exit switch case '\n': // ignore newlines, 5 case '\t': // tabs, 55 case ' ': // and spaces in input 56 break; // exit switch 5 catches all other cases. 58 default: // catch all other characters 59 cout << "Incorrect letter grade entered." 60 << " Enter a new grade." << endl; 61 break; // optional; will exit switch anyway } // end switch 6 65 } // end while 66 Notice the default statement, which fig02_22.cpp (3 of ) 21 Enter the EOF character to en a B c C A d f C E Incorrect letter grade entere a new grade. D A b ^Z

39 6 // output summary of results 68 cout << "\n\ntotals for each letter grade are:" 69 << "\na: " << acount // display number of A grades 0 << "\nb: " << bcount // display number of B grades 1 << "\nc: " << ccount // display number of C grades 2 << "\nd: " << dcount // display number of D grades 3 << "\nf: " << fcount // display number of F grades << endl; 5 6 return 0; // indicate successful termination 8 } // end function main fig02_22.cpp ( of ) Totals for each letter grade are: A: 3 B: 2 C: 3 D: 2 F: 1 22

40 Enter the letter grades. Enter the EOF character to end input. a B c C A d f C E Incorrect letter grade entered. Enter a new grade. D A b ^Z fig02_22.cpp output (1 of 1) 23 Totals for each letter grade are: A: 3 B: 2 C: 3 D: 2 F: 1

41 2 2.1 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 ); Conrad's preferred indentation: do { statement } while ( condition ); action(s) condition false true

42 1 // Fig. 2.2: fig02_2.cpp 2 // Using the do/while repetition structure. 3 #include <iostream> 5 using std::cout; 6 using std::endl; 8 // function main begins program execution 9 int main() 10 { 11 int counter = 1; // initialize counter do { 1 cout << counter << " "; // display counter 15 } while ( ++counter <= 10 ); // end do/while 16 1 cout << endl; return 0; // indicate successful termination } // end function main fig02_2.cpp (1 of 1) fig02_2.cpp output (1 of 1)

43 1 // Fig. 2.2: fig02_2.cpp 2 // Using the do/while repetition structure. 3 #include <iostream> 5 using std::cout; 6 using std::endl; 8 // function main begins program execution 9 int main() 10 { 11 int counter = 1; // initialize counter Notice the preincrement in loop-continuation test do { 1 cout << counter << " "; // display counter 15 } while ( ++counter <= 10 ); // end do/while 16 1 cout << endl; return 0; // indicate successful termination } // end function main fig02_2.cpp (1 of 1) fig02_2.cpp output (1 of 1)

44 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

45 1 // Fig. 2.26: fig02_26.cpp 2 // Using the break statement in a for structure. 3 #include <iostream> 5 using std::cout; 6 using std::endl; 8 // function main begins program execution 9 int main() 10 { int x; // x declared here so it can be used after the loop 13 1 // loop 10 times 15 for ( x = 1; x <= 10; x++ ) { 16 1 // if x is 5, terminate loop 18 if ( x == 5 ) 19 break; // break loop only if x is cout << x << " "; // display value of x } // end for 2 25 cout << "\nbroke out of loop when x became " << x << endl; 26 2 return 0; // indicate successful termination } // end function main fig02_26.cpp (1 of 1) 2

46 1 // Fig. 2.26: fig02_26.cpp 2 // Using the break statement in a for structure. 3 #include <iostream> 5 using std::cout; 6 using std::endl; 8 // function main begins program execution 9 int main() 10 { int x; // x declared here so it can be used after the loop 13 1 // loop 10 times 15 for ( x = 1; x <= 10; x++ ) { Exits for structure when break executed // if x is 5, terminate loop 18 if ( x == 5 ) 19 break; // break loop only if x is cout << x << " "; // display value of x } // end for 2 25 cout << "\nbroke out of loop when x became " << x << endl; 26 2 return 0; // indicate successful termination } // end function main fig02_26.cpp (1 of 1) 2

47 1 // Fig. 2.26: fig02_26.cpp 2 // Using the break statement in a for structure. 3 #include <iostream> 5 using std::cout; 6 using std::endl; 8 // function main begins program execution 9 int main() 10 { int x; // x declared here so it can be used after the loop 13 1 // loop 10 times 15 for ( x = 1; x <= 10; x++ ) { Exits for structure when break executed // if x is 5, terminate loop 18 if ( x == 5 ) 19 break; // break loop only if x is cout << x << " "; // display value of x } // end for 2 25 cout << "\nbroke out of loop when x became " << x << endl; fig02_26.cpp (1 of 1) Broke out of loop when x became return 0; // indicate successful termination } // end function main

48 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

49 1 // Fig. 2.2: fig02_2.cpp 2 // Using the continue statement in a for structure. 3 #include <iostream> 5 using std::cout; 6 using std::endl; 8 // function main begins program execution 9 int main() 10 { 11 // loop 10 times 12 for ( int x = 1; x <= 10; x++ ) { 13 1 // if x is 5, continue with next iteration of loop 15 if ( x == 5 ) 16 continue; // skip remaining code in loop body 1 18 cout << x << " "; // display value of x } // end for structure cout << "\nused continue to skip printing the value 5" 23 << endl; 2 25 return 0; // indicate successful termination fig02_2.cpp (1 of 1) Used continue to skip printing the value } // end function main

50 1 // Fig. 2.2: fig02_2.cpp 2 // Using the continue statement in a for structure. 3 #include <iostream> 5 using std::cout; 6 using std::endl; 8 // function main begins program execution 9 int main() 10 { 11 // loop 10 times 12 for ( int x = 1; x <= 10; x++ ) { 13 Skips to next iteration of the loop. 1 // if x is 5, continue with next iteration of loop 15 if ( x == 5 ) 16 continue; // skip remaining code in loop body 1 18 cout << x << " "; // display value of x } // end for structure cout << "\nused continue to skip printing the value 5" 23 << endl; 2 25 return 0; // indicate successful termination fig02_2.cpp (1 of 1) Used continue to skip printing the value } // end function main

51 Logical 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;

52 Logical 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;

53 2.20 Confusing Equa lity (==) a nd Assignment (=) Operators Does not typically cause syntax errors Expressions that have a value can be used for decision Zero = false, nonzero = true Assignment statements produce a value Example if ( paycode == ) cout << "You get a bonus!" << endl; bonus given only if paycode is If == was replaced with = if ( paycode = ) cout << "You get a bonus!" << endl; Paycode set to (no matter what it was before) yields "true" (since is non-zero), so bonus always given 32

54 2.20 lvalues vs. rvalues lvalues (pronounced "ell values") Expressions that can appear on left side of equation Can be changed (i.e., variables) x = ; target of an assignment statement; where the data gets stored. "arrr values" ) 33

55 2.20 lvalues vs. rvalues lvalues (pronounced "ell values") Expressions that can appear on left side of equation Can be changed (i.e., variables) x = ; target of an assignment statement; where the data gets stored. rvalues (pronounced "arrr values" ) 33

56 2.20 lvalues vs. rvalues lvalues (pronounced "ell values") Expressions that can appear on left side of equation Can be changed (i.e., variables) x = ; target of an assignment statement; where the data gets stored. rvalues (pronounced "arrr values" ) 33

57 2.20 lvalues vs. rvalues lvalues (pronounced "ell values") Expressions that can appear on left side of equation Can be changed (i.e., variables) x = ; target of an assignment statement; where the data gets stored. "arrr values" ) rvalues (pronounced ) appear on right side of equation may be variables, constants, or expressions, e.g. x = ; x = y ; x = y + ; 33

58 2.20 lvalues vs. rvalues lvalues (pronounced "ell values") Expressions that can appear on left side of equation Can be changed (i.e., variables) x = ; target of an assignment statement; where the data gets stored. "arrr values" ) rvalues (pronounced ) appear on right side of equation may be variables, constants, or expressions, e.g. x = ; x = y ; x = y + ; lvalues can be used as rvalues, but not vice versa (i.e. cannot write = x; or y + = x) 33

59 2.21 Structured-Progra mming Summa ry According to Bohm and Jacopini, all programs can be broken down into 3 Sequence Selection if, if/else, or switch Any selection can be rewritten as an if statement Repetition while, do/while or for Any repetition structure can be rewritten as a while statement

60 2.21 Structured-Progra mming Summa ry 35 Only use single-entry/single-exit control structures Easier to understand, test, debug and modify Rules 1) start with a single rectangle, then apply rules (2) and (3) in either order, as many times as necessary 2) Any rectangle (action) can be replaced by two rectangles (actions) in sequence 3) Any rectangle (action) can be replaced by any control structure (sequence, if, if/else, switch, while, do/while or for) Rule 2 Rule 3 Rule 1

61 2.21 Structured-Progra mming Summa ry 36 Representation of Rule 3 (replacing any rectangle with a control structure) Rule 3 Rule 3 Rule 3

### Chapter 2 - Control Structures

Chapter 2 - Control Structures 1 2.1 Introduction 2.2 Algorithms 2.3 Pseudocode 2.4 Control Structures 2.5 if Selection Structure 2.6 if/else Selection Structure 2.7 while Repetition Structure 2.8 Formulating

### Chapter 2 - Control Structures

Chapter 2 - Control Structures 1 Outline 2.1 Introduction 2.2 Algorithms 2.3 Pseudocode 2.4 Control Structures 2.5 if Selection Structure 2.6 if/else Selection Structure 2.7 while Repetition Structure

### 2.11 Assignment Operators. Assignment expression abbreviations c = c + 3; can be abbreviated as c += 3; using the addition assignment operator

2.11 Assignment Operators 1 Assignment expression abbreviations c = c + 3; can be abbreviated as c += 3; using the addition assignment operator Statements of the form variable = variable operator expression;

### Chapter 4 C Program Control

1 Chapter 4 C Program Control Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 2 Chapter 4 C Program Control Outline 4.1 Introduction 4.2 The Essentials of Repetition

### Chapter 4 C Program Control

Chapter C Program Control 1 Introduction 2 he Essentials of Repetition 3 Counter-Controlled Repetition he for Repetition Statement 5 he for Statement: Notes and Observations 6 Examples Using the for Statement

### C Program Control. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

C Program Control Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan Outline The for repetition statement switch multiple selection statement break

1 5 Control Statements: Part 2 2 Not everything that can be counted counts, and not every thing that counts can be counted. Albert Einstein Who can control his fate? William Shakespeare The used key is

1 5 Control Statements: Part 2 2 Not everything that can be counted counts, and not every thing that counts can be counted. Albert Einstein Who can control his fate? William Shakespeare The used key is

CHAPTER 2.1 CONTROL STRUCTURES (SELECTION) Dr. Shady Yehia Elmashad Outline 1. The if Selection Structure 2. The if/else Selection Structure 3. The switch Multiple-Selection Structure 1. The if Selection

### بسم اهلل الرمحن الرحيم

بسم اهلل الرمحن الرحيم Fundamentals of Programming C Session # 10 By: Saeed Haratian Fall 2015 Outlines Examples Using the for Statement switch Multiple-Selection Statement do while Repetition Statement

### Introduction to C Programming

1 2 Introduction to C Programming 2.6 Decision Making: Equality and Relational Operators 2 Executable statements Perform actions (calculations, input/output of data) Perform decisions - May want to print

### IS 0020 Program Design and Software Tools

1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Spring 2005 Lecture 1 Jan 6, 2005 Course Information 2 Lecture: James B D Joshi Tuesdays/Thursdays: 1:00-2:15 PM Office Hours:

### Chapter 2 - Control Structures

Chapter 2 - Control Structures 1 Outline 2.1 Introduction 2.2 Algorithms 2.3 Pseudocode 2.4 Control Structures 2.5 if Selection Structure 2.6 if/else Selection Structure 2.7 while Repetition Structure

### C++ Programming Lecture 7 Control Structure I (Repetition) Part I

C++ Programming Lecture 7 Control Structure I (Repetition) Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department while Repetition Structure I Repetition structure Programmer

### In this chapter you will learn:

1 In this chapter you will learn: Essentials of counter-controlled repetition. Use for, while and do while to execute statements in program repeatedly. Use nested control statements in your program. 2

Assoc. Prof. Dr. Marenglen Biba (C) 2010 Pearson Education, Inc. All for repetition statement do while repetition statement switch multiple-selection statement break statement continue statement Logical

### Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

Programming - 1 Computer Science Department 011COMP-3 لغة البرمجة 1 011 عال- 3 لطالب كلية الحاسب اآللي ونظم المعلومات 1 1.1 Machine Language A computer programming language which has binary instructions

### Programming for Engineers Iteration

Programming for Engineers Iteration ICEN 200 Spring 2018 Prof. Dola Saha 1 Data type conversions Grade average example,-./0 class average = 23450-67 893/0298 Grade and number of students can be integers

### C++ PROGRAMMING SKILLS Part 2 Programming Structures

C++ PROGRAMMING SKILLS Part 2 Programming Structures If structure While structure Do While structure Comments, Increment & Decrement operators For statement Break & Continue statements Switch structure

### Control Statements. Musa M. Ameen Computer Engineering Dept.

2 Control Statements Musa M. Ameen Computer Engineering Dept. 1 OBJECTIVES In this chapter you will learn: To use basic problem-solving techniques. To develop algorithms through the process of topdown,

### Introduction to Programming

Introduction to Programming session 6 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Spring 2011 These slides are created using Deitel s slides Sharif University of Technology Outlines

### Fundamentals of Programming Session 9

Fundamentals of Programming Session 9 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2013 These slides have been created using Deitel s slides Sharif University of Technology Outlines

### c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

Chapter 1 File Extensions: Source code (cpp), Object code (obj), and Executable code (exe). Preprocessor processes directives and produces modified source Compiler takes modified source and produces object

### Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 1 ARRAYS Arrays 2 Arrays Structures of related data items Static entity (same size

### Fundamentals of Programming Session 8

Fundamentals of Programming Session 8 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2013 These slides have been created using Deitel s slides Sharif University of Technology Outlines

### Week 2. Relational Operators. Block or compound statement. if/else. Branching & Looping. Gaddis: Chapters 4 & 5. CS 5301 Spring 2018.

Week 2 Branching & Looping Gaddis: Chapters 4 & 5 CS 5301 Spring 2018 Jill Seaman 1 Relational Operators l relational operators (result is bool): == Equal to (do not use =)!= Not equal to > Greater than

### C++ As A "Better C" Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

C++ As A "Better C" Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan 2013 Fall Outline 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.5

### Why Is Repetition Needed?

Why Is Repetition Needed? Repetition allows efficient use of variables. It lets you process many values using a small number of variables. For example, to add five numbers: Inefficient way: Declare a variable

### C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition)

C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 5: Control Structures II (Repetition) Objectives In this chapter, you will: Learn about repetition (looping) control structures

### IS 0020 Program Design and Software Tools

1 Course Information 2 IS 0020 Program Design and Software Tools Introduction to C++ Programming Lecture 1 May 10, 2004 Lecture: James B D Joshi Mondays: 6:00-8.50 PM One (two) 15 (10) minutes break(s)

### Outline. Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples.

Outline Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples. 1 Arrays I Array One type of data structures. Consecutive group of memory locations

### Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) A few types

Chapter 4 - Arrays 1 4.1 Introduction 4.2 Arrays 4.3 Declaring Arrays 4.4 Examples Using Arrays 4.5 Passing Arrays to Functions 4.6 Sorting Arrays 4.7 Case Study: Computing Mean, Median and Mode Using

### Structured Program Development in C

1 3 Structured Program Development in C 3.2 Algorithms 2 Computing problems All can be solved by executing a series of actions in a specific order Algorithm: procedure in terms of Actions to be executed

### Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

Repetition Contents 1 Repetition 1.1 Introduction 1.2 Three Types of Program Control Chapter 5 Introduction 1.3 Two Types of Repetition 1.4 Three Structures for Looping in C++ 1.5 The while Control Structure

### Chapter 15 - C++ As A "Better C"

Chapter 15 - C++ As A "Better C" Outline 15.1 Introduction 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.4 C++ Standard Library 15.5 Header Files 15.6 Inline Functions 15.7 References and Reference

### Chapter 3 Structured Program Development

1 Chapter 3 Structured Program Development Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 3 - Structured Program Development Outline 3.1 Introduction

CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad Outline 1. C++ Iterative Constructs 2. The for Repetition Structure 3. Examples Using the for Structure 4. The while Repetition Structure

### Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition 5.2 Q1: Counter-controlled repetition requires a. A control variable and initial value. b. A control variable

### BITG 1233: Introduction to C++

BITG 1233: Introduction to C++ 1 Learning Outcomes At the end of this lecture, you should be able to: Identify basic structure of C++ program (pg 3) Describe the concepts of : Character set. (pg 11) Token

### C++ Programming: From Problem Analysis to Program Design, Third Edition

C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 5: Control Structures II (Repetition) Why Is Repetition Needed? Repetition allows you to efficiently use variables Can input,

### Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program)

Chapter - Arrays 1.1 Introduction 2.1 Introduction.2 Arrays.3 Declaring Arrays. Examples Using Arrays.5 Passing Arrays to Functions.6 Sorting Arrays. Case Study: Computing Mean, Median and Mode Using Arrays.8

### I/O Streams and Standard I/O Devices (cont d.)

Chapter 3: Input/Output Objectives In this chapter, you will: Learn what a stream is and examine input and output streams Explore how to read data from the standard input device Learn how to use predefined

### Chapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed?

Chapter 5: Control Structures II (Repetition) Objectives In this chapter, you will: Learn about repetition (looping) control structures Explore how to construct and use countercontrolled, sentinel-controlled,

### Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

Loops! Loops! Loops! Lecture 5 COP 3014 Fall 2017 September 25, 2017 Repetition Statements Repetition statements are called loops, and are used to repeat the same code mulitple times in succession. The

### Arrays. Outline. Multidimensional Arrays Case Study: Computing Mean, Median and Mode Using Arrays Prentice Hall, Inc. All rights reserved.

Arrays 1 Multidimensional Arrays Case Study: Computing Mean, Median and Mode Using Arrays Multidimensional Arrays 2 Multiple subscripts a[ i ][ j ] Tables with rows and columns Specify row, then column

CHAPTER 3 ARRAYS Dr. Shady Yehia Elmashad Outline 1. Introduction 2. Arrays 3. Declaring Arrays 4. Examples Using Arrays 5. Multidimensional Arrays 6. Multidimensional Arrays Examples 7. Examples Using

### Introduction to Programming

Introduction to Programming session 5 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2010 These slides are created using Deitel s slides Sahrif University of Technology Outlines

1 2 Introduction to C++ Programming 2 What s in a name? that which we call a rose By any other name would smell as sweet. William Shakespeare When faced with a decision, I always ask, What would be the

### CS 151 Review #3. // More than one variable can be defined // in a statement. Multiple variables are // separated by a comma.

REVIEW cout Statement The cout statement invokes an output stream, which is a sequence of characters to be displayed to the screen. cout

### Computer Programming : C++

The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2003 Muath i.alnabris Computer Programming : C++ Experiment #1 Basics Contents Structure of a program

### Chapter 2 Basic Elements of C++

C++ Programming: From Problem Analysis to Program Design, Fifth Edition 2-1 Chapter 2 Basic Elements of C++ At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion

### Structured Programming. Flowchart Symbols. Structured Programming. Selection. Sequence. Control Structures ELEC 330 1

ELEC 330 1 Structured Programming Control Structures ELEC 206 Computer Applications for Electrical Engineers Dr. Ron Hayne Algorithm Development Conditional Expressions Selection Statements Loops 206_C3

### Structured Programming. Dr. Mohamed Khedr Lecture 9

Structured Programming Dr. Mohamed Khedr http://webmail.aast.edu/~khedr 1 Two Types of Loops count controlled loops repeat a specified number of times event-controlled loops some condition within the loop

### 1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol. B. Outputs to the console a floating point number f1 in scientific format

### Introduction to C++ Programming. Adhi Harmoko S, M.Komp

Introduction to C++ Programming Adhi Harmoko S, M.Komp Machine Languages, Assembly Languages, and High-level Languages Three types of programming languages Machine languages Strings of numbers giving machine

### THE INTEGER DATA TYPES. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

THE INTEGER DATA TYPES STORAGE OF INTEGER TYPES IN MEMORY All data types are stored in binary in memory. The type that you give a value indicates to the machine what encoding to use to store the data in

### Chapter 3 - Functions

Chapter 3 - Functions 1 Outline 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3.4 Functions 3.5 Function Definitions 3.6 Function Prototypes 3.7 Header Files 3.8 Random Number

### Chapter 1 Introduction to Computers and C++ Programming

Chapter 1 Introduction to Computers and C++ Programming 1 Outline 1.1 Introduction 1.2 What is a Computer? 1.3 Computer Organization 1.7 History of C and C++ 1.14 Basics of a Typical C++ Environment 1.20

### Arrays. Week 4. Assylbek Jumagaliyev

Arrays Week 4 Assylbek Jumagaliyev a.jumagaliyev@iitu.kz Introduction Arrays Structures of related data items Static entity (same size throughout program) A few types Pointer-based arrays (C-like) Arrays

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING Dr. Shady Yehia Elmashad Outline 1. Introduction to C++ Programming 2. Comment 3. Variables and Constants 4. Basic C++ Data Types 5. Simple Program: Printing

### CS 007A Midterm 1 Practice Chapters 1 5

CS 007A Midterm 1 Practice Chapters 1 5 1. Consider the 4 bytes stored in contiguous memory, as shown to the right. a. Determine the decimal representation of these 4 one-byte integers: b. Determine the

### Arithmetic Operators. Binary Arithmetic Operators. Arithmetic Operators. A Closer Look at the / Operator. A Closer Look at the % Operator

1 A Closer Look at the / Operator Used for performing numeric calculations C++ has unary, binary, and ternary s: unary (1 operand) - binary ( operands) 13-7 ternary (3 operands) exp1? exp : exp3 / (division)

### LECTURE 5 Control Structures Part 2

LECTURE 5 Control Structures Part 2 REPETITION STATEMENTS Repetition statements are called loops, and are used to repeat the same code multiple times in succession. The number of repetitions is based on

### o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

Last Time Let s all Repeat Together 10/3/05 CS150 Introduction to Computer Science 1 1 We covered o Counter and sentinel controlled loops o Formatting output Today we will o Type casting o Top-down, stepwise

### Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program

Overview - General Data Types - Categories of Words - The Three S s - Define Before Use - End of Statement - My First Program a description of data, defining a set of valid values and operations List of

### Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Computer Programming Basic Control Flow - Loops Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Objectives To learn about the three types of loops: while for do To avoid infinite

### ADARSH VIDYA KENDRA NAGERCOIL COMPUTER SCIENCE. Grade: IX C++ PROGRAMMING. Department of Computer Science 1

NAGERCOIL COMPUTER SCIENCE Grade: IX C++ PROGRAMMING 1 C++ 1. Object Oriented Programming OOP is Object Oriented Programming. It was developed to overcome the flaws of the procedural approach to programming.

### C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

C++ Basics Data Processing Course, I. Hrivnacova, IPN Orsay The First Program Comments Function main() Input and Output Namespaces Variables Fundamental Types Operators Control constructs 1 C++ Programming

### The American University in Cairo Department of Computer Science & Engineering CSCI &09 Dr. KHALIL Exam-I Fall 2011

The American University in Cairo Department of Computer Science & Engineering CSCI 106-07&09 Dr. KHALIL Exam-I Fall 2011 Last Name :... ID:... First Name:... Form I Section No.: EXAMINATION INSTRUCTIONS

### CS110D: PROGRAMMING LANGUAGE I

CS110D: PROGRAMMING LANGUAGE I Computer Science department Lecture 5&6: Loops Lecture Contents Why loops?? While loops for loops do while loops Nested control structures Motivation Suppose that you need

### Chapter 2. Outline. Simple C++ Programs

Chapter 2 Simple C++ Programs Outline Objectives 1. Building C++ Solutions with IDEs: Dev-cpp, Xcode 2. C++ Program Structure 3. Constant and Variables 4. C++ Operators 5. Standard Input and Output 6.

### Intro to Programming & C Why Program? 1.2 Computer Systems: Hardware and Software. Why Learn to Program?

Intro to Programming & C++ Unit 1 Sections 1.1-4 and 2.1-10, 2.12-13, 2.15-17 CS 1428 Spring 2019 Jill Seaman 1.1 Why Program? Computer programmable machine designed to follow instructions Program a set

### CS242 COMPUTER PROGRAMMING

CS242 COMPUTER PROGRAMMING I.Safa a Alawneh Variables Outline 2 Data Type C++ Built-in Data Types o o o o bool Data Type char Data Type int Data Type Floating-Point Data Types Variable Declaration Initializing

### Chapter 4 - Notes Control Structures I (Selection)

Chapter 4 - Notes Control Structures I (Selection) I. Control Structures A. Three Ways to Process a Program 1. In Sequence: Starts at the beginning and follows the statements in order 2. Selectively (by

### 3 The L oop Control Structure

3 The L oop Control Structure Loops The while Loop Tips and Traps More Operators The for Loop Nesting of Loops Multiple Initialisations in the for Loop The Odd Loop The break Statement The continue Statement

### Full file at C How to Program, 6/e Multiple Choice Test Bank

2.1 Introduction 2.2 A Simple Program: Printing a Line of Text 2.1 Lines beginning with let the computer know that the rest of the line is a comment. (a) /* (b) ** (c) REM (d)

### BBM 101 Introduc/on to Programming I Fall 2014, Lecture 5. Aykut Erdem, Erkut Erdem, Fuat Akal

BBM 101 Introduc/on to Programming I Fall 2014, Lecture 5 Aykut Erdem, Erkut Erdem, Fuat Akal 1 Today Itera/on Control Loop Statements for, while, do- while structures break and con/nue Some simple numerical

### Chapter 5: Control Structures II (Repetition)

Chapter 5: Control Structures II (Repetition) 1 Objectives Learn about repetition (looping) control structures Explore how to construct and use count-controlled, sentinel-controlled, flag-controlled, and

### Engineering Problem Solving with C++, Etter/Ingber

Engineering Problem Solving with C++, Etter/Ingber Chapter 2 Simple C++ Programs C++, Second Edition, J. Ingber 1 Simple C++ Programs Program Structure Constants and Variables C++ Operators Standard Input

### INTRODUCTION TO C++ PROGRAM CONTROL. Dept. of Electronic Engineering, NCHU. Original slides are from

INTRODUCTION TO C++ PROGRAM CONTROL Original slides are from http://sites.google.com/site/progntut/ Dept. of Electronic Engineering, NCHU Outline 2 Repetition Statement for while do.. while break and continue

### Objectives. In this chapter, you will:

Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates arithmetic expressions Learn about

### C++, How to Program. Spring 2016 CISC1600 Yanjun Li 1

Chapter 6 Function C++, How to Program Deitel & Deitel Spring 2016 CISC1600 Yanjun Li 1 Function A function is a collection of statements that performs a specific task - a single, well-defined task. Divide

### 5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators

Chapter 5: 5.1 Looping The Increment and Decrement Operators The Increment and Decrement Operators The Increment and Decrement Operators ++ is the increment operator. It adds one to a variable. val++;

### Structured Program Development

Structured Program Development Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan Outline Introduction The selection statement if if.else switch The

### ! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char

Week 1 Operators, Data Types & I/O Gaddis: Chapters 1, 2, 3 CS 5301 Fall 2016 Jill Seaman Programming A program is a set of instructions that the computer follows to perform a task It must be translated

### 2 nd Week Lecture Notes

2 nd Week Lecture Notes Scope of variables All the variables that we intend to use in a program must have been declared with its type specifier in an earlier point in the code, like we did in the previous

### C++ Programming: From Problem Analysis to Program Design, Third Edition

C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 2: Basic Elements of C++ Objectives (continued) Become familiar with the use of increment and decrement operators Examine

### Control Structures (Deitel chapter 4,5)

Control Structures (Deitel chapter 4,5) 1 2 Plan Control Structures ifsingle-selection Statement if else Selection Statement while Repetition Statement for Repetition Statement do while Repetition Statement

### Control Structures. Control Structures Conditional Statements COMPUTER PROGRAMMING. Electrical-Electronics Engineering Dept.

EEE-117 COMPUTER PROGRAMMING Control Structures Conditional Statements Today s s Objectives Learn about control structures Examine relational and logical operators Explore how to form and evaluate logical

### Chapter Overview. I/O Streams as an Introduction to Objects and Classes. I/O Streams. Streams and Basic File I/O. Objects

Chapter 6 I/O Streams as an Introduction to Objects and Classes Overview 6.1 Streams and Basic File I/O 6.2 Tools for Stream I/O 6.3 Character I/O Copyright 2008 Pearson Addison-Wesley. All rights reserved.

Chapter 2 C++ Basics 1 Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style Slide 2-3 2.1 Variables and Assignments 2

### Chapter 6. I/O Streams as an Introduction to Objects and Classes. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Chapter 6 I/O Streams as an Introduction to Objects and Classes Overview 6.1 Streams and Basic File I/O 6.2 Tools for Stream I/O 6.3 Character I/O Slide 6-3 6.1 Streams and Basic File I/O I/O Streams I/O

### Fundamental of Programming (C)

Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 3 Constants, Variables, Data Types, And Operations Department of Computer Engineering

### Looping. Arizona State University 1

Looping CSE100 Principles of Programming with C++, Fall 2018 (based off Chapter 5 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University

### 2/29/2016. Definition: Computer Program. A simple model of the computer. Example: Computer Program. Data types, variables, constants

Data types, variables, constants Outline.1 Introduction. Text.3 Memory Concepts.4 Naming Convention of Variables.5 Arithmetic in C.6 Type Conversion Definition: Computer Program A Computer program is a

### ECET 264 C Programming Language with Applications. C Program Control

ECET 264 C Programming Language with Applications Lecture 7 C Program Control Paul I. Lin Professor of Electrical & Computer Engineering Technology http://www.etcs.ipfw.edu/~lin Lecture 7 - Paul I. Lin

### The cin Object. cout << "Enter the length and the width of the rectangle? "; cin >> length >> width;

The cin Object Short for console input. It is used to read data typed at the keyboard. Must include the iostream library. When this instruction is executed, it waits for the user to type, it reads the