0% found this document useful (0 votes)
31 views8 pages

Unit 6 Iteration Statements

The document discusses different types of iteration statements in C/C++ including while loops, do-while loops, and for loops. It provides examples of each loop type and explains how to use them, the syntax, and how the flow works for each. Key learning objectives are to identify different looping statements, differentiate between conditional and looping statements, and write programs using for and do-while loops.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views8 pages

Unit 6 Iteration Statements

The document discusses different types of iteration statements in C/C++ including while loops, do-while loops, and for loops. It provides examples of each loop type and explains how to use them, the syntax, and how the flow works for each. Key learning objectives are to identify different looping statements, differentiate between conditional and looping statements, and write programs using for and do-while loops.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

COLLEGE OF ENGINEERING AND INFORMATION SCIENCES

Agusan del Sur State College of Agriculture and Technology


[email protected] | http://asscat.edu.ph

Iteration Statements
Unit 6

INTRODUCTION

In the previous chapter we had seen the concept of control structure which involves making decision having a condition.
If the condition is satisfied then the decision is to execute a particular set of instructions, if not then another set of
instructions.

This unit is dedicated to looping or iteration. It is used when a set of instructions is to be executed multiple times or for
a fixed number of times until a particular condition is satisfied.

LEARNING OBJECTIVES

At the end of this unit, you are expected to:

1. Identify the different looping statements used in C/C++.


2. Differentiate conditional statements and looping statements.
3. Construct a C/C++ program which uses for loop.
4. Construct a C/C++ program which uses do…while loop.

TOPICS

6.1 The while loop 6.4 Sentinel-Controlled Repetition


6.2 The do-while loop 6.5 The continue statement
5.3 The for loop

Loops
• repeat a statement a certain number of times, or while a condition is fulfilled. They are
introduced by the keywords while, do, and for.

6.1 The while loop

The simplest kind of loop is the while-loop.

Its syntax is:

while (expression/condition)
{
statement(s)
}

The while-loop simply repeats statement while expression/condition is true. If, after any
execution of statement, expression/condition is no longer true, the loop ends, and the
program continues right after the loop.

Figure 6.1a shows the while loop flowchart. The part of the loop that contains the statements to be
repeated is called the loop body. A one-time execution of a loop body is referred to as an iteration (or
repetition) of the loop. Each loop contains a expression/condition, a Boolean expression that
controls the execution of the body. It is evaluated each time to determine if the loop body is executed. If

| Unit 6: Iteration Statements | ES109 – Computer Programming


| Instructor: Jocelyn O. Balolot 1
COLLEGE OF ENGINEERING AND INFORMATION SCIENCES
Agusan del Sur State College of Agriculture and Technology
[email protected] | http://asscat.edu.ph

its evaluation is true, the loop body is executed; if its evaluation is false, the entire loop terminates and
the program control turns to the statement that follows the while loop.

The loop for displaying Welcome to C++! 100 times introduced in the preceding section is an example of
a while loop. Its flowchart is shown in Figure 6.1b. The expression/condition is count < 100 and the loop
body contains the following two statements:

count = 0;

expression/ false
condition false
(count < 100)?

true
true
statement(s)
(loop body)
cout<< “Welcome to
C++\n”;
count++

(6.1a) (6.1b)

Figure 6.1 The while loop repeatedly executes the statements in the loop body when the expression/condition
evaluates to true.

int count = 0; expression/condition


while (count < 100)
{
cout << "Welcome to C++!\n";
count++; loop body }
} In this example, you know exactly how many times the loop body needs to be executed because the control
variable count is used to count the number of executions. This type of loop is known as a counter-controlled
loop

Note
The expression/condition must always appear inside the parentheses. The braces enclosing the loop body can be omitted only if the loop body
contains one statement or none.

Another example, let's have a look at a countdown using a while-loop:


Program 6.1
1 // custom countdown using while
2 #include<iostream>
3 using namespace std;
4
5 int main()
6 {
7 int n = 10; //set the initial value of n=10
8
9 while (n>0) { //test if n is greater than 0, if true execute the loop body
10 cout << n << “, “; //display the value of n
11 --n; //n=n-1
12 }
13
14 cout << “stop!\n”; //outside the loop body
15 }
Output:

10, 9, 8, 7, 5, 4, 3, 2, 1, stop!
The first statement in main sets n to a value of 10. This is the first number in the countdown. Then the
while-loop begins: if this value fulfills the condition n>0 (that n is greater than zero), then the block that
follows the condition is executed, and repeated for as long as the condition ( n>0) remains being true.

| Unit 6: Iteration Statements | ES109 – Computer Programming


| Instructor: Jocelyn O. Balolot 2
COLLEGE OF ENGINEERING AND INFORMATION SCIENCES
Agusan del Sur State College of Agriculture and Technology
[email protected] | http://asscat.edu.ph

The whole process of the previous program can be interpreted according to the following script
(beginning in main):

1. n is assigned a value
2. The while condition is checked (n>0). At this point there are two possibilities:
o condition is true: the statement is executed (to step 3)
o condition is false: ignore statement and continue after it (to step 5)

3. Execute statement:
cout << n << ", ";
--n;
(prints the value of n and decreases n by 1)
4. End of block. Return automatically to step 2.

5. Continue the program right after the block:


print liftoff! and end the program.

• A thing to consider with while-loops is that the loop should end at some point, and thus the
statement shall alter values checked in the condition in some way, so as to force it to become
false at some point.
• Otherwise, the loop will continue looping forever.
• In this case, the loop includes --n, that decreases the value of the variable that is being evaluated
in the condition (n) by one - this will eventually make the condition ( n>0) false after a certain
number of loop iterations.
• To be more specific, after 10 iterations, n becomes 0, making the condition no longer true, and
ending the while-loop.

6.2 The do-while loop

A very similar loop is the do-while loop, whose syntax is:

do {
statement(s)
} while (condition)

Its execution flowchart is shown in Figure 6.1.

• It behaves like a while-loop, except that condition is evaluated after the execution
of statement instead of before, guaranteeing at least one execution of statement, even
if condition is never fulfilled.
• The do-while loop is usually preferred over a while-loop when the statement needs to be
executed at least once, such as when the condition that is checked to end of the loop is
determined within the loop statement itself.

| Unit 6: Iteration Statements | ES109 – Computer Programming


| Instructor: Jocelyn O. Balolot 3
COLLEGE OF ENGINEERING AND INFORMATION SCIENCES
Agusan del Sur State College of Agriculture and Technology
[email protected] | http://asscat.edu.ph

statement(s)
(loop body)

Figure 6.2 The do-while loop executes the loop body first, then checks
true
Expression/ the expression/condition to determine whether to continue or terminate
condition the loop.

false

Program 6.2 Program Output


1 #include <iostream> Enter an integer (the input ends if it
2 using namespace std; is 0): 3
3 Enter an integer (the input ends if it
4 int main() is 0): 5
5 { Enter an integer (the input ends if it
6 // Keep reading data until the input is 0 is 0): 6
7 int sum = 0; Enter an integer (the input ends if it
8 int data = 0; is 0): 0
9 The sum is 14
10 do
11 {
12 sum += data;
13
14 // Read the next data
15 cout << "Enter an integer (the input ends "
16 << "if it is 0): ";
17 cin >> data;
18 }
19 while (data != 0)
20
21 cout << "The sum is " << sum << endl;
22
23 return 0;
24 }

What would happen if sum and data were not initialized to 0? Would it cause a syntax error? No. It would cause a
logic error, because sum and data could be initialized to any value.

Tip
Use the do-while loop if you have statements inside the loop that must be executed at least once, as in the case of the do-while loop
in the preceding TestDoWhile Program 8.4. These statements must appear before the loop as well as inside it if you use a while loop.

6.3 The for loop

The for loop is designed to iterate a number of times. Its syntax is:

for (initialization; expression/condition; increase/decrease) {


statement(s);
}

• Like the while-loop, this loop repeats statement while condition is true.
• But, in addition, the for loop provides specific locations to contain an initialization and
an increase/decrease expression, executed before the loop begins the first time, and after
each iteration, respectively.
• Therefore, it is especially useful to use counter variables as condition.

| Unit 6: Iteration Statements | ES109 – Computer Programming


| Instructor: Jocelyn O. Balolot 4
COLLEGE OF ENGINEERING AND INFORMATION SCIENCES
Agusan del Sur State College of Agriculture and Technology
[email protected] | http://asscat.edu.ph

It works in the following way:

1. initialization is executed. Generally, this declares a counter variable, and sets it to some
initial value. This is executed a single time, at the beginning of the loop.
2. condition is checked. If it is true, the loop continues; otherwise, the loop ends,
and statement is skipped, going directly to step 5.
3. statement is executed. As usual, it can be either a single statement or a block enclosed in curly
braces { }.
4. increase/decrease is executed, and the loop gets back to step 2.
5. the loop ends: execution continues by the next statement after it.

The flowchart of the loop is shown.

initialization i = 100

expression/ false false


(i < 100)?
condition

true tru
statement(s) e ”Welcome to
cout<<
(loop body) C++\n”;

Increase/decrease i++

Figure 6.3. A for loop performs an initial action once, then repeatedly executes the statements in the
loop body, and performs an action after an iteration when the expression/condition evaluates to true.

A for loop generally uses a variable to control how many times the loop body is executed and when the
loop terminates. This is called a control variable. The initialization often initializes a control variable, the
increase/decrease usually increments or decrements the control variable, and the expression/condition
tests whether the control variable has reached a termination value. For example, the following for loop
displays Welcome to C++! 100 times:

int i;
for (i = 0; i < 100; i++)
{
cout << "Welcome to C++!\n";
}

The loop control variable can be declared and initialized in the for loop. Here is an example:

for (int i = 0; i < 100; i++)


{
cout << "Welcome to C++!\n";
}

| Unit 6: Iteration Statements | ES109 – Computer Programming


| Instructor: Jocelyn O. Balolot 5
COLLEGE OF ENGINEERING AND INFORMATION SCIENCES
Agusan del Sur State College of Agriculture and Technology
[email protected] | http://asscat.edu.ph

If there is only one statement in the loop body, as in this example, the braces can be omitted as shown below:

for (int i = 0; i < 100; i++)


cout << "Welcome to C++!\n";

Tip
The control variable must be declared inside the control structure of the loop or before the loop. If the loop control
variable is used only in the loop, and not elsewhere, it is good programming practice to declare it in the initial-action of
the for loop. If the variable is declared inside the loop control structure, it cannot be referenced outside the loop. In the
preceding code, for example, you cannot reference i outside the for loop, because it is declared inside the for loop.

Note
The initialization in a for loop can be a list of zero or more comma-separated variable declaration statements or assignment
expressions. For example:

for (int i = 0, j = 0; i + j < 10; i++, j++)


{
// Do something
}

The increase/decrease in a for loop can be a list of zero or more comma-separated statements. For example:

for (int i = 1; i < 100; cout << i << endl, i++);

This example is correct, but it is a bad example, because it makes the code difficult to read. Normally, you declare and initialize a
control variable as an initial action and increment or decrement the control variable as an action after each iteration.

Note
If the expression/condition in a for loop is omitted, it is implicitly true. Thus, the statement given below in (a), which is an infinite
loop, is the same as in (b). To avoid confusion, though, it is better to use the equivalent loop in (c).

for ( ; ; ) Equivalent for ( ; true; ) while (true)


Equivalent
{ { {
// Do something // Do something // Do something
} } }

Here is the countdown example using a for loop:

Program 6.3 Program Output


1 // countdown using a for loop
10, 9, 8, 7, 6, 5, 4, 3, 2, 1, stop!
2 #include<iostream>
3 using namespace std;
4
5 int main()
6 {
7 for (int n=10; n>0; n--) {
8 cout << n << “, “;
9 }
10 cout << “stop!\n”;
11 }

| Unit 6: Iteration Statements | ES109 – Computer Programming


| Instructor: Jocelyn O. Balolot 6
COLLEGE OF ENGINEERING AND INFORMATION SCIENCES
Agusan del Sur State College of Agriculture and Technology
[email protected] | http://asscat.edu.ph

6.4 Sentinel-Controlled Repetition


- Indicates “end of data entry”
- Loop ends when sentinel input
- Sentinel variable tested in condition; loop ends when sentinel encountered

Syntax of sentinel-controlled while statement:

cin >> variable; //initialize loop control variable

while (variable !=sentinel value) // test loop control variable


{

..
..
cin>> variable: //update loop control variable

..
}

Program 6.4 Program Output


1 #include<iostream> Enter an integer [-1] to exit: 4
using namespace std; Value entered was 4
2
Enter another integer [-1] to exit: 10
3 Value entered was 10
4 int main()
Enter another integer [-1] to exit: 0
{
5 int num;
Value entered was 0
Enter another integer [-1] to exit: -1
6 cout << "Enter an integer [-1] to exit: "; Out of loop
7 cin >> num;
8 while (num != -1)
9 {
10 cout << "Value entered was " << num << endl;
11 cout << "Enter another integer [-1] to exit: ";
12 cin >> num;
13 }
14 cout << "Out of loop" << endl;
15 return 0;
16 }

6.5 The continue statement

Sometimes there may be situations when you require the control to exit the loop or skip the particular iteration and go
to the next. This can be done using the keyword continue.

A continue statement causes the rest of the body of the loop to be omitted, for the current iteration. The control is
transferred to the code that evaluates the normal test condition for loop termination.

The continue statement is similar to the break statement but instead of terminating the loop, it transfers execution to
the next iteration of the loop. It continues the loop after skipping the remaining statements in its current iteration.

The general form of continue is as follows:

while(condition)
do{
{
statements;
statements;
if(condition)
if(condition)
continue;
continue;
statements;
statements;
}while(condition;
}
statements;
statements;

| Unit 6: Iteration Statements | ES109 – Computer Programming


| Instructor: Jocelyn O. Balolot 7
COLLEGE OF ENGINEERING AND INFORMATION SCIENCES
Agusan del Sur State College of Agriculture and Technology
[email protected] | http://asscat.edu.ph

Example program shows the use of continue to print the following pattern.

Program 6.5 Program Output


1 //Program to display the following pattern 1
2 using continue 12
3 1234
4 #include<iostream> 12345
5 using namespace std;
6 int main()
7 {
8 for(int i = 0; i <= 5; i++)
9 {
10 if (i == 3)continue;
11 for(int j = 1; j <= i; j++)
12 {
13 cout<<j;
14 }
15 cout<<endl;
16 }
17
18 return 0;
19 }

Note
The continue statement is always inside a loop. In the while and do-while loops, the loop-continuation-condition is
evaluated immediately after the continue statement. In the for loop, the action-after-each-iteration is performed, then
the loop-continuation-condition is evaluated, immediately after the continue statement.

| Unit 6: Iteration Statements | ES109 – Computer Programming


| Instructor: Jocelyn O. Balolot 8

You might also like