LECTURE # 8 : STRUCTURED PROGRAMMING Repetition Statements Tr.Hadeel

advertisement
LECTURE # 8 :
STRUCTURED PROGRAMMING
Repetition Statements
Tr.Hadeel
Content
2

Types of repetition statements

while repetition statement

Counter-controlled repetition

Sentinel-controlled repetition

for repetition statement

do..while repetition statement

break and continue statements

Common errors
Tr.Hadeel@hotmail.com
Repetition Statements
3

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
Tr.Hadeel@hotmail.com
while Repetition Statements
4

Actions repeated while condition remains true

Syntax

One of the actions should causes condition to becomes false

Example
while (condition)
{
action1;
action2;
.
.
actionN;
}
int product = 3;
while ( product <= 30 )
product *= 3;
Tr.Hadeel@hotmail.com
while Repetition Statements (cont.)
5


Not providing action that causes condition to becomes false

Lead to infinite loop

Logic error
Example
int product = 3;
while ( product <= 30 )
cout << product;
Tr.Hadeel@hotmail.com
Counter-controlled Repetition
6

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)
{
action1;
action2;
.
.
actionN;
update control var;
}
1
// Fig. 5.1: fig05_01.cpp
2
// Counter-controlled repetition.
3
#include <iostream>
4
using std::cout;
5
using std::endl;
6
7
int main()
8
{
9
Control-variable name is counter
with variable initial value 1
int counter = 1; // declare and initialize control variable
10
11
while ( counter <= 10 ) // loop-continuation condition
12
{
13
cout << counter << " ";
14
counter++; // increment control variable by 1
15
Condition tests for
counter’s final value
} // end while
Increment the value in counter
16
17
cout << endl; // output a newline
18
return 0; // successful termination
19 } // end main
1 2 3 4 5 6 7 8 9 10
Tr.Hadeel@hotmail.com
7
Example
8
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.
Tr.Hadeel@hotmail.com
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Fig. 2.7: fig02_07.cpp
// Class average program with counter-controlled repetition.
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
// function main begins
int main()
{
int total;
//
int gradeCounter; //
int grade;
//
int average;
//
program execution
sum of grades input by user
number of grade to be entered next
grade value
average of grades
// initialization phase
total = 0;
// initialize total
gradeCounter = 1;
// initialize loop counter
Variables used to store totals are
normally initialized to zero before
being used in programs
Tr.Hadeel@hotmail.com
9
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// processing phase
while ( gradeCounter <= 10 ) {
cout << "Enter grade: ";
cin >> grade;
total = total + grade;
gradeCounter = gradeCounter + 1;
}
// termination phase
average = total / 10;
//
//
//
//
//
loop 10 times
prompt for input
read grade from user
add grade to total
increment counter
// integer division
// display result
cout << "Class average is " << average << endl;
return 0;
// indicate
} // end function main
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Class
The counter gets incremented each
time theended
loop executes.
program
successfully
Eventually, the counter causes the
loop to end.
grade: 98
grade: 76
grade: 71
grade: 87
grade: 83
grade: 90
grade: 57
grade: 79
grade: 82
grade: 94
average is 81
Tr.Hadeel@hotmail.com
10
Sentinel-controlled Repetition
11

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
Tr.Hadeel@hotmail.com
To read first entry and check condition in
1st iteration
To read remain entries and check condition
for further iterations
12
Tr.Hadeel@hotmail.com
13
13
Tr.Hadeel@hotmail.com
for Repetition Statement
14

Provide counter-controlled repetition details in a single statement

Syntax
for (initialization; loopContinuationCondition; update)
action1;
for (initialization; loopContinuationCondition; update)
{
action1; action2; … actionN;
}

for loop repeats actions until condition becomes false
1
// Fig. 5.2: fig05_02.cpp
2
// Counter-controlled repetition with the for statement.
3
#include <iostream>
4
using std::cout;
5
using std::endl;
6
7
int main()
8
{
9
// for statement header includes initialization,
10
// loop-continuation condition and increment.
11
for ( int counter = 1; counter <= 10; counter++ )
12
cout << counter << " ";
13
Increment for counter
14
cout << endl; // output a newline
15
return 0; // indicate successful termination
16 } // end main
1 2 3 4 5 6 7 8 9 10
Condition tests for counter’s final value
Control-variable name is counter with initial value 1
Tr.Hadeel@hotmail.com
15
for Repetition Statement (cont.)
16

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 << “*”;
Examples Using for Statement
17

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 )
Examples Using for Statement (cont.)
18

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;
do..while Repetition Statement
19

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
{
action1;
action2;
.
.
actionN;
} while (condition)
1
// Fig. 5.7: fig05_07.cpp
2
// do...while repetition statement.
3
#include <iostream>
4
using std::cout;
5
using std::endl;
6
7
int main()
8
{
9
Declare and initialize
control variable counter
int counter = 1; // initialize counter
10
11
do
12
{
do…while loop displays counter’s value
before testing for counter’s final value
13
cout << counter << " "; // display counter
14
counter++; // increment counter
15
} while ( counter <= 10 ); // end do...while
16
17
cout << endl; // output a newline
18
return 0; // indicate successful termination
19 } // end main
1 2 3 4 5 6 7 8 9 10
int counter=1;
do
{
cout << counter << endl;
}
while (++counter <= 10);
What is the output produced by this loop ??
Tr.Hadeel@hotmail.com
20
break Statement
21

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
Tr.Hadeel@hotmail.com
1
// Fig. 5.13: fig05_13.cpp
2
3
// break statement exiting a for statement.
#include <iostream>
4
using std::cout;
5
6
7
8
9
using std::endl;
10
11
int main()
{
int count; // control variable also used after loop terminates
Loop 10 times
for ( count = 1; count <= 10; count++ ) // loop 10 times
12
13
14
15
16
{
17
18
} // end for
if ( count == 5 )
break; // break loop only if x is 5
Exit for statement (with a
break) when count equals 5
cout << count << " ";
19
cout << "\nBroke out of loop at count = " << count << endl;
20
return 0; // indicate successful termination
21 } // end main
1 2 3 4
Broke out of loop at count = 5
Tr.Hadeel@hotmail.com
22
continue Statement
23

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 testTr.Hadeel@hotmail.com
is evaluated
1
// Fig. 5.14: fig05_14.cpp
2
// continue statement terminating an iteration of a for statement.
3
#include <iostream>
4
using std::cout;
5
using std::endl;
6
7
int main()
8
{
Loop 10 times
9
for ( int count = 1; count <= 10; count++ ) // loop 10 times
10
{
11
12
if ( count == 5 ) // if count is 5,
continue;
// skip remaining code in loop
13
14
15
Skip line 14 and proceed to
line 9 when count equals 5
cout << count << " ";
} // end for
16
17
cout << "\nUsed continue to skip printing 5" << endl;
18
return 0; // indicate successful termination
19 } // end main
1 2 3 4 6 7 8 9 10
Used continue to skip printing 5
Tr.Hadeel@hotmail.com
24
Common Errors
25

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
Tr.Hadeel@hotmail.com
Exercise - 1
26

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.
Tr.Hadeel@hotmail.com
27
End
Tr.Hadeel@hotmail.com
Download