STRUCTURED PROGRAMMING Repetition Statements Content 2 Types of









































- Slides: 41
STRUCTURED PROGRAMMING Repetition Statements
Content 2 Types of repetition statements while repetition statement Counter-controlled repetition Sentinel-controlled repetition Nested control statements for repetition statement do. . while repetition statement break and continue statements Common errors
Objectives 3 By the end you should: Recognize the purpose of the loops Identify the problems that require the use of loop structures Differentiate between while, for, and do. . while statement Differentiate between Counter and sentinel controlled loops Understand use break and continue statements Explain what is meant by Nested control statements Apply C++ syntax rules associated with each repetition statement Create, trace, and debug programs that use while, for, do. . while, break and continue statements
Repetition Statements 4 Three types for statement and while statement Perform a group of actions zero or more times do. . while statement Perform a group of actions at least once
while Repetition Statements 5 Actions repeated while condition remains true Syntax One of the actions should causes condition to becomes false Example while (condition) { action 1; action 2; . . action. N; } int product = 3; while ( product <= 30 ) product *= 3;
6 while Repetition Statements (cont. ) Not providing action that causes condition to becomes false Lead to infinite loop Logic error Example int product = 3; while ( product <= 30 ) cout << product;
Counter-controlled Repetition 7 Uses a variable to control number of loops’ iterations Also known as definite repetition Control counting loops with integer values Number of repetitions known beforehand Requires Name of loop control variable Initial value of loop control variable Condition to test of reaching final value Update loop control variable Initialize control var ; while (condition) { action 1; action 2; . . action. N; update control var; }
8
Example 9 A class of ten students took a quiz. The grades (integers in the range 0 to 100) are entered by the user. Determine the class average on the quiz.
Variables used to store totals are normally initialized to zero before being used in programs 10
11
Sentinel-controlled Repetition 12 When number of students’ grades is unknown (prev. example) Using a special value called sentinel value How will loop know when to end? Indicate “end of data entry” A sentinel value cannot also be a valid input value -1 in this case Also known as a signal, dummy or flag value
To read first entry and check condition in 1 st iteration To read remain entries and check condition for further iterations 13
Nested Control Statement 14 Control statements can be one inside the another Nested building blocks Example # 1 A college has a list of test results (1 = pass, 2 = fail) for 10 students. Write a program that analyzes the results. If more than 8 students pass, print "Raise Tuition".
15
16
First Run Second Run 17
18 Nested Control Statement (cont. ) Example # 2 Ask teacher to enter a set of letter grades, then display a summery of the number of students who received each grade.
2 //Counting letter grades. 3#include >iostream< 4 5 using std: : cout; 6 using std: : cin; 7 using std: : endl; 8 9 //function main begins program execution 10 int main() 11} int grade ; //one grade 12 char int a. Count =0 ; //number of As 13 int b. Count =0 ; //number of Bs 14 int c. Count =0 ; //number of Cs 15 int d. Count =0 ; //number of Ds 16 int f. Count =0 ; //number of Fs 17 18 cout >>"Enter the letter grades". >>endl 19 >>"Enter X character to end input". 20 21 cin >> grade ; >>endl; 19
( grade != 'X' && grade != 'x' ) { Compares grade (an int) to the numerical representations of A and a. 20
cin >> grade ; 21
22
Enter the letter grades. Enter X 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 x Totals for each letter grade are : A: 3 B: 2 C: 3 D: 2 F: 1 23
for Repetition Statement 24 Provide counter-controlled repetition details in a single statement Syntax for (initialization; loop. Continuation. Condition; update) action 1; for (initialization; loop. Continuation. Condition; update) { action 1; action 2; … action. N; } for loop repeats actions until condition becomes false
25
26 for Repetition Statement (cont. ) When loop counter is declared in initialization expression, it can ONLY be used inside for statement (local variable) initialization and update expressions can be comma-separated lists of expressions for(int i=0, j=0; i<4 && j<8; i++, j++) cout << “*”;
27 for Repetition Statement (cont. ) initialization, condition and update expressions are optional, but separated semicolon are required Omit initialization Omit condition Initializes control variable earlier in program Always condition is true, may lead to infinite loop Omit update Calculated as statement in for body
Examples Using for Statement 28 Vary control variable from 100 to 1 in increments by -1 (decrement by 1) for(int i = 100; i >= 1; i-- ) Vary control variable from 7 to 77 in steps of 7 for(int i = 7; i <= 77; i += 7 ) Vary control variable over the sequence: 99, 88, 77, 66, 55, 44, 33, 22, 11, 0 for(int i = 99; i >= 0; i -= 11 )
29 Examples Using for Statement (cont. ) Using a comma-separated list of expressions int total =0; for ( int number = 2; // initialization number <= 20; // loop continuation condition total += number, number += 2 ) // total and increment ; // empty statement can be written as int total =0; for ( int number = 2; number <= 20; number += 2 ) total += number;
Example 30 A person invests 1000$ in a savings account yielding 5% 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 formula: where p is the original amount invested r is the annual rate n is the number of years a is the amount of deposit at the end of the n year
31
32
33 do. . while Repetition Statement Similar to while statement but while statement tests loopcontinuation before performing body of loop do. . while tests loop-continuation after performing body of loop Loop body always executes at least once Syntax do { action 1; action 2; . . action. N; } while (condition)
int counter=1; do { cout << counter << endl; } while (++counter <= 10); What is the output produced by this loop ? ? 34
break Statement 35 Alter flow of control Causes immediate exit from control structure Used with while, for, do…while or switch statements Escape early from a loop (while, for, do…while ) Skip the remainder of switch
36
continue Statement 37 Used with while, for or do…while statements Alter flow of control Skips remainder of loop body of current iteration Proceeds with next iteration of loop With while and do…while statements Loop-continuation test is evaluated immediately after continue statement With for statement Update expression is executed Next, loop-continuation test is evaluated
38
Common Errors 39 Compilation errors Using commas instead of the two required semicolons in a for header Logic errors Not initializing counters and totals Choosing a sentinel value that is also a legitimate data value Placing semicolon immediately after for header or while condition
Exercise - 1 40 Write a program that asks for a number and reports the summation from 1 to the number. Use while statement. Write another version of program using for statement.
Included Sections 41 Chapter 4: from section 7 to 10 Chapter 5