0% found this document useful (0 votes)
2 views

Control Statements part II

This chapter covers repetition control structures in programming, including count-controlled, sentinel-controlled, flag-controlled, and EOF-controlled loops. It explains the use of while, do...while, and for loops, along with break and continue statements for controlling loop execution. Additionally, it emphasizes good programming practices and the importance of nested control structures.

Uploaded by

erensahmet
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Control Statements part II

This chapter covers repetition control structures in programming, including count-controlled, sentinel-controlled, flag-controlled, and EOF-controlled loops. It explains the use of while, do...while, and for loops, along with break and continue statements for controlling loop execution. Additionally, it emphasizes good programming practices and the importance of nested control structures.

Uploaded by

erensahmet
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

5.

Chapter
Control Structures II
(Repetition)
Objectives
In this chapter, you will:
• Learn about repetition (looping) control
structures
• Explore how to construct and use count-
controlled, sentinel-controlled, flag-
controlled, and EOF-controlled repetition
structures
• Examine break and continue
statements
• Discover how to form and use nested
control structures
Why Is Repetition Needed?
Why Is Repetition Needed?

• Repetition allows you to efficiently use


variables
• Can input, add, and average multiple numbers
using a limited number of variables
• For example, to add five numbers:
– Declare a variable for each number, input the numbers and
add the variables together
– Create a loop that reads a number into a variable and adds
it to a variable that contains the sum of the numbers
Repetition Structures
• These structures allow program commands to be
repeated multiple times.

• There are two different repetition structures.


- Number Controlled (Counted / Count Controlled)
• Used for a certain number of repetitions.
• Example: Add numbers from 1 to 10.
- Condition Controlled (Uncounted / Condition
Controlled)
• The repetition process continues until the given
condition is met.
• Ex: Add up the numbers until the number entered
becomes negative.
while
Looping (Repetition) Structure
while Looping (Repetition)
Structure
• The general form of the while
statement is:

while is a reserved word


• Statement can be simple or compound
• Expression acts as a decision maker and
is usually a logical expression
• Statement is called the body of the loop
• The parentheses are part of the syntax
while Looping (Repetition)
Structure (continued)

• Infinite loop: continues to execute


endlessly
– Avoided by including statements in loop body
that assure exit condition is eventually false
while Looping (Repetition)
Structure (continued)
Designing while Loops
Counter-Controlled while Loops
Case 1: Counter-Controlled
while Loops
• If you know exactly how many pieces of
data need to be read, the while loop
becomes a counter-controlled loop
1 // Name Surname, Date, Time
2 // Counter-controlled repetition.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
Control-variable name is counter
6
with variable initial value 1
7 int main()
8 {
9 int counter = 1; // declare and initialize control variable
10
Condition tests for
11 while ( counter <= 10 ) // loop-continuation condition
counter’s final valu
12 {
13 cout << counter << " ";
14 counter++; // increment control variable by 1
15 } // end while
16 Increment the value in counte
17 cout << endl; // output a newline
18 return 0; // successful termination
19 } // end main

1 2 3 4 5 6 7 8 9 10
Sentinel-Controlled while Loops
Case 2: Sentinel-Controlled
while Loops
• Sentinel variable is tested in the condition
and loop ends when sentinel is encountered

We use a sentinel value to indicate ‘’end of data entry’’


Common Programming Error
Floating-point values are approximate, so controlling
counting loops with floating-point variables can
result in imprecise counter values and inaccurate
tests for termination.
Error-Prevention Tip
Control counting loops with integer values.
Good Programming Practice
• Put a blank line before and after each control
statement to make it stand out in the program.

• Too many levels of nesting can make a program


difficult to understand. As a rule, try to avoid
using more than three levels of indentation.
• Vertical spacing above and below control
statements and indentation of the bodies of control
statements within the control statement headers
give programs a two-dimensional appearance that
greatly improves readability.
do…while
Looping (Repetition) Structure
do…while Looping (Repetition)
Structure
• General form of a do...while:

• The statement executes first, and then


the expression is evaluated
• To avoid an infinite loop, body must
contain a statement that makes the
expression false
• The statement can be simple or
compound
• Loop always iterates at least once
do…while Looping (Repetition)
Structure (continued)
Good Programming Practice
Always including braces in a do...while
statement helps eliminate ambiguity between
the while statement and the do...while
statement containing one statement.
1 // Name Surname, Date, Time.
2 // do...while repetition statement.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
Declare and initialize
6
control variable counter
7 int main()
8 {
9 int counter = 1; // initialize counter
10
do…while loop displays counter’s
11 do
before testing for counter’s final va
12 {
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
for
Looping (Repetition) Structure
• The general form of the for statement is:

• The initial statement, loop


condition, and update statement
are called for loop control statements
− initial statement usually initializes a
variable (called the for loop control, or
for indexed, variable)
• In C++, for is a reserved word
1 // Name Surname, Date, Time.
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
14 cout << endl; // output a newline Increment for counter
15 return 0; // indicate successful termination
16 } // end main Condition tests for counter’s fi

1 2 3 4 5 6 7 8 9 10 Control-variable name is counter with initial value 1


Common Programming Error
Using an incorrect relational operator or using an
incorrect final value of a loop counter in the
condition of a while or for statement can
cause off-by-one errors.
for Looping (Repetition) Structure
(continued)
for Looping (Repetition)
Structure (continued)
• C++ allows you to use fractional
values for loop control variables of the
double type
− Results may differ
• The following is a semantic error:

• The following is a legal for loop:


for (;;)
cout << "Hello" << endl;
for Looping (Repetition)
Structure (continued)
for Looping (Repetition) Structure
(continued)
• Increment of the for statement
– The following expressions are all equivalent in the
increment portion of the for statement (when no other
code appears there)
• counter = counter + 1
• counter += 1
• ++ counter
• counter++
– However, many programmers prefer form counter++,
because for loop evaluates the increment expression after
the loop body executes.
Common Programming Error
When the control variable of a for statement is
declared in the initialization section of the for
statement header, using the control variable after
the body of the statement is a compilation error.
Common Programming Error

• Using commas instead of the two required


semicolons in a for header is a syntax error.
• Placing a semicolon immediately to the right of
the right parenthesis of a for header makes the
body of that for statement an empty
statement. This is usually a logic error.
Error-Prevention Tip
•Frequently, the control variable is printed or used in
calculations in the body of a for statement, but this
is not required. Although the value of the control
variable can be changed in the body of a for
statement, avoid doing so, because this practice can
lead to slight logic errors.
•It is better to use the control variable for controlling
repetition while never mentioning it in the body of the
for statement.
Examples Using the for Statement

• for statement examples


– Vary control variable from 1 to 100 in increments of 1
• for ( int i = 1; i <= 100; i++ )
– Vary control variable from 100 to 1 in increments of -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 from 20 to 2 in steps of -2
• for ( int i = 20; i >= 2; i -= 2 )
– Vary control variable over the sequence: 2, 5, 8, 11, 14, 17, 20
• for ( int i = 2; i <= 20; i += 3 )
– Vary control variable over the sequence: 99, 88, 77, 66, 55, 44,
33, 22, 11, 0
• for ( int i = 99; i >= 0; i -= 11 )
1 // Name Surname, Date, Time.
2 // Summing integers with the for statement.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6 Vary number from 2
7 int main() to 20 in steps of 2
8 {
9 int total = 0; // initialize total
10
11 // total even integers from 2 through 20
12 for ( int number = 2; number <= 20; number += 2 ) Add the current value of
13 total += number; number to total
14
15 cout << "Sum is " << total << endl; // display results
16 return 0; // successful termination
17 } // end main

Sum is 110
Examples Using the for Statement
(Cont.)

• Using a comma-separated list of


expressions
– Lines 12-13 of previous program can be
rewritten as
for ( int number = 2; // initialization
number <= 20; // loop continuation
condition
total += number, number += 2 ) //
total and
//
increment
; // empty statement
Good Programming Practice
Although statements preceding a for and
statements in the body of a for often can be
merged into the for header, doing so can make
the program more difficult to read, maintain,
modify and debug.
Choosing the Right Looping
Structure
• All three loops have their place in C++
− If you know or can determine in advance
the number of repetitions needed, the
for loop is the correct choice
− If you do not know and cannot determine
in advance the number of repetitions
needed, and it could be zero, use a
while loop
− If you do not know and cannot determine
in advance the number of repetitions
needed, and it is at least one, use a
do...while loop
break and continue
Statements
• break and continue alter the flow of
control
• break statement is used for two purposes:
– To exit early from a loop
• Can eliminate the use of certain (flag) variables
– To skip the remainder of the switch
structure
• After the break statement executes, the
program continues with the first statement
after the structure
break & continue
Statements (continued)
• continue is used in while, for,
and do…while structures
• When executed in a loop
– It skips remaining statements and
proceeds with the next iteration of the
loop
1 // Name Surname, Date, Time.
2 // break statement exiting a for statement.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 int main()
8 {
9 int count; // control variable also used after loop terminates
10
Loop 10 times
11 for ( count = 1; count <= 10; count++ ) // loop 10 times
12 {
13 if ( count == 5 ) Exit for statement (with a
14 break; // break loop only if x is 5 break) when count equals 5
15
16 cout << count << " ";
17 } // end for
18
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
1 // Name Surname, Date, Time.
2 // continue statement terminating an iteration of a for statement.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
Loop 10 times
7 int main()
8 {
9 for ( int count = 1; count <= 10; count++ ) // loop 10 times
10 {
11 if ( count == 5 ) // if count is 5,
12 continue; // skip remaining code in loop
13
14 cout << count << " ";
Skip line 14 and proceed to
15 } // end for line 9 when count equals 5
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
Good Programming Practice
Some programmers feel that break and
continue violate structured programming. The
effects of these statements can be achieved by
structured programming techniques, so these
programmers do not use break and continue.
Most programmers consider the use of break in
switch statements acceptable.
Performance Tip
The break and continue statements,
when used properly, perform faster than do
the corresponding structured techniques.
Software Engineering Observation

There is a tension between achieving quality


software engineering and achieving the best-
performing software. Often, one of these
goals is achieved at the expense of the other.
For all but the most performance-intensive
situations, apply the following rule of thumb:
•First, make your code simple and correct;
•Then make it fast and small, but only if
necessary.
Nested Control Structures
Nested Control Structures

• To create the following pattern:


*
**
***
****
*****
• We can use the following code:
for (i = 1; i <= 5 ; i++)
{
for (j = 1; j <= i; j++)
cout << "*";
cout << endl;
}
Nested Control Structures
(continued)
• What is the result if we replace the first
for statement with the following?
for (i = 5; i >= 1; i--)

• Answer:
*****
****
***
**
*
Summary (continued)
• while: expression is the decision
maker, and the statement is the body
of the loop
• A while loop can be:
− Counter-controlled
− Sentinel-controlled
• In the Windows console environment,
the end-of-file marker is entered using
Ctrl+z
Summary (continued)
• for loop: simplifies the writing of a
counter-controlled while loop
− Putting a semicolon at the end of the
for loop is a semantic error
• Executing a break statement in the
body of a loop immediately terminates
the loop
• Executing a continue statement in the
body of a loop skips to the next iteration

You might also like