Control Structures Repetition or Iteration Looping Part I
Sequence Print out a sales report Open the salesperson file Print heading on form Skip 3 lines Read the first record Print salesperson’s name
Decision (selection, branching) sales > quota yes bonus=sales*.01 no bonus = 0
Switch (Multiple Decision) Option=1 Option=2 Option=3 Option=4
Repetition (iteration, looping) More? Comm = Sales*.02 Calculate Pay Print Check No Yes
The for Statement Syntax for (initialize; expression; alter) statement Example: for (cnt=1; cnt < 7; cnt++) { cout << “Yankees are #1\n”; cout << “They’ll win the Series!\n”; } next statement *
The for Statement used as a counting loop semicolons separate the items items 1 and 2 are statements (end with ;) your may declare variable and initialize it ex. for (int cnt = 1; cnt < 7; cnt++) performs the same functions as the while
A Simple Example int num; cout << "NUMBER SQUARE CUBE\n" << "------ ------ ----\n"; Bronson p.170 prog 5-10 [ p.150 prog 5-3 = while version] for (num = 1; num < 11; num++) { cout << setw(3) << num << " " << setw(3) << num * num << " " << setw(4) << num * num * num << "\n"; } *
for Statement Examples for (k = 1; k <= n; k = k + 1) k = k * k; for (j = 2; k % j == 0; j = j + 1) { cout << j << “ is a divisor of “ << k << ‘\n’; sum = sum + j; } *
for Statement Examples Not Valid: for (j = 0, j < n, j = j + 3) // semicolons needed for (j = 0; j < n) // three parts needed
for -- Null Expressions Example 1: j = 1; sum = 0; for ( ; j <= 10; j = j + 1) sum = sum + j; Example 2: j = 1; sum = 0; for ( ; j <= 10; ) sum = sum + j; Example 3: j = 1; sum = 0; for ( ; ; ) { sum = sum + j; j++; cout << "\n" << sum; } * * *
Nested Loops When a decision or control structure is contained within another decision or control sturcture, the inner one is said to be nested. while ... if ... while... You may have repetition within decision and vice versa. * *
Nested Loops - Ex.1 Example int y,z; for (y = 5; y > 0; y--) { cout << "\nAli R."; cout << “**”; } for (z = 1; z < 3; z++) cout <<"\tVic R.\t"; *
Nested Loops - Ex.1 Output Ali R. Vic R. Vic R. ** Ali R. Vic R. Vic R. ** Ali R. Vic R. Vic R. ** Ali R. Vic R. Vic R. ** Ali R. Vic R. Vic R. ** Output Ali R. Vic R. Vic R. ** *
Nested Loops - Ex.1 Execution 1 2 3 4 5 4 5 4 6 2 3 4 5 4 5 4 6 2 7 2 3 4 5 4 5 4 6 2 7 1 int y,z; 2 for (y = 5; y > 0; y--) 3 { cout << "\nAli R."; 4 for (z = 1; z < 3; z++) 5 cout <<"\tVic R.\t"; 6 cout << “**“; 7 } *
Nested Loops - Ex. 2 4 for (trial = 1; trial <=6; trial = trial +1) 5 { cout << "Enter result of trial " << trial <<" : "; 6 cin >> score; 7 total = total + score; 8 } 9 avg = total/(trial-1); 10 cout << "Average for experiment "<< exper 11 << " is “<< setprecision(4)<< avg<< "\n\n"; 12 } 1 for (exper =1; exper<=4; exper=exper +1) 2 { cout << "\tScores for experiment "<< exper <<":\n"; 3 total = 0.0; Bronson p. 175-15 * *
The while Statement Syntax while (expression) statement Example: count = 1; while (count <= 10) { cout << “Yankees are #1\n”; count = count + 1; } next statement *
for vs. while cnt = 1; while (cnt < 7) { cout << … cnt++; } for (cnt = 1; cnt < 7; cnt++) { cout << … } *
The while Statement Syntax while (expression) statement a loop control variable is evaluated in the expression the loop statements contain the lines executed each time the loop repeats
The while Statement 0 or Exit the while False 1 or True Test the loop Exit the while 0 or False Test the expression statements to execute 1 or True
Something to Note Note Note... count = 1; while (count <= 10) { cout << “Yankees are #1\n”; cout << “and will win the series\n”; } next statement *
The while Statement loop control variable is initialized before while statement evaluation or test is performed within the expression the body may contain any number of statements, including branches and other loops the control variable is changed during loop execution in order to exit loop the statement immediately after the while is executed upon exiting * * * * *
A Simple Example int num; cout << "NUMBER SQUARE CUBE\n" << "------ ------ ----\n"; num = 1; while (num < 11) { cout << setw(3) << num << " " << setw(3) << num * num << " " << setw(4) << num * num * num <<‘\n’; num++; // increment num } Bronson p. 150 prog 5-3 [ for is prog 5-10 ] * * *
Another Example double celsius, fahren; cout << "CELSIUS FAHRENHEIT\n" << "------- ----------\n"; celsius = 5; // starting Celsius value while (celsius <= 50) { fahren = (9.0/5.0) * celsius + 32.0; cout << setw(4) << celsius << setiosflags(ios::showpoint) << setw(13) << setprecision(2) << fahren << '\n'; celsius = celsius + 5; } Bronson p. 152 prog 5-4 * * *
Still Another Example year = 1; deprec = 4000; endyr = 28000; accum_depreci = 0; while (year <= 7) { endyr = endyr - deprec; accum_depreci = accum_depreci + deprec; cout << year << deprec << endyr << accum_depreci << "\n"; year = year + 1; } Bronson p. 153-6 * * *
Problem Solving: Finding the Largest Value The program asks for the number of items in the list. Checks to see if that number is positive. Gets user input. Assigns the largest to variable max. * * * *
int count = 0, n = 0; double max = 0, x = 0; cout << "The maximum value will be computed.\n"; cout << "How many numbers do you wish to enter? "; cin >> n; while (n <= 0) { cout << "\nERROR: Positive integer required.\n\n”; cout << "How many numbers to enter? "; cin >> n; } cout << “Enter a real number: “; cin >> x; max = x; // first value to max * * * *
cout << “Maximum value: “ << max << “\n”; } while (count++ < (n-1)) // first n accepted above { cout << “Enter a real number: “; cin >> x; if (max < x) max = x; } cout << “Maximum value: “ << max << “\n”; } Output The maximum value will be computed. How many numbers do you wish to enter? 4 Enter a real number: 1.01 Enter a real number: -3 Enter a real number: 2.2 Enter a real number: 7.07000 Maximum value: 7.07 * * *
Closer look at a counter: cout << “Enter “ << n << … cin >> x; max = x; // count = 0 1 while (count++ < (n-1)) 2 { 3 cout << “LOOP number: “ 4 cin >> x; 5 if (max < x) 6 max = x; 7 } loop count n executed 1 5 1 2 2 3 3 4 4 5 *
Running Totals // count =1 while (count <=4) { cout << “Enter a number: “; cin >> num; total = total + num; cout << “The total is “ << total; count++; } *
Bowling Team Example First write a plan. A bowling team consists of five players each of whom bowls three games. Write a program that allows the user to enter each players scores and displays the players average. The team average is displayed at the end. First write a plan.
Bowling Team Plan display instructions for - players for - games I/O scores sum scores average scores display scores sum player averages team average display team average
Common Errors Improper braces in nested structures Using = in place of == != versus == This changes the logic, be especially careful when used with && or || infinite loops: != versus && versus || *
The End The End The End The End The End The End The End The End The End - part I The End The End The End The End The End The End The End The End The End The End The End The End