C++ 5. Loop Statements
C++ 5. Loop Statements
PRG1002 - Programming I
Loop Statements
● So far, we have been writing statements that get executed sequentially, one statement followed by
another.
● Loops allows a programmer to repeatedly execute a block of statements until a condition is satisfied.
● Let’s say we want to print “hello, world!” 5 times. We can do it sequentially, like this:
● But we can use loops to make our code more succinct and DRY.
DRY: Don’t Repeat Yourself
● This is important because it makes our code easier to read and to maintain
● If we repeat code, and that code requires a change, we have to remember to make the change in
multiple places if the code is repeated
● Loops are one tool you can use to keep code DRY
Loop types
● for loop
● while loop
● do...while loop
for loop
for loop statement
○ The init step is executed first, and only once. It is used to initialize the loop counter to some value.
For example: int i = 0;
○ If the condition evaluates to true the body of the loop is executed. If the condition evaluates to false, the
body of the loop is skipped and the next statement after the for loop is executed.
For example: i <= 10;
○ The expression modifies the variable in the init statement.
For example: i++ or i--. It is evaluated after each iteration of the loop.
○ The condition is evaluated and the process repeats (body of the loop->increment->evaluates the condition) until
the condition becomes false. Then the for loop terminates.
○ init, condition and expression are separated with a semicolon.
Flow diagram - for loop
false
condition
true
statements
statements after for loop
inside for loop
expression
Example - for loop
● init statement is executed only once at the ● Next, condition i < 10 is evaluated. If the
start of the loop. In this example, i is defined value of i is less than 10, the statements in the
and initialized to zero. for body is executed. Otherwise, the loop
terminates. If the condition is false on the first
int main() iteration, then the for body is not executed at
{ all.
for (int i = 0; i < 10; ++i)
{
cout << "hello, world!" << endl; ● In this example, “hello, world!” is printed
} out.
return 0;
}
● Finally, the expression is evaluated. In this
example, i is incremented by 1.
● Create a for loop that prints out your name 7 times on the console window.
● Create another for loop that prints out all the values from 1 to 100 on the console window.
○ Modify the for loop to include 0 and include 100
○ Modify the for loop to include 0 and not 100
○ Modify the for loop to not include 0 and include 100
○ Modify the for loop to increment by 2
● A while loop statement repeatedly executes a block of statement until the condition is satisfied.
● Syntax:
while (condition)
{
statement(s);
}
○ The condition is evaluated first and if it evaluates to true, then the statements inside while loop executes, this
happens repeatedly until the condition evaluates to false.
If the condition evaluates to false, the next statement after the while loop is executed.
● Inside the while loop make sure that the loop variable used in the condition is modified, so that at
some point the condition evaluates to false. If the loop condition never evaluates to false, the loop will
run indefinitely, and you have an infinite loop!
Flow diagram - while loop
while (condition)
{
statement(s);
}
false
condition
true
int option = 0;
int a = 0;
int b = 0; What happens in this loop?
while (option != 3)
{
cin >> option;
cin >> a;
cin >> b;
When will the loop terminate?
switch (option)
{
case 1:
cout << a + b << endl;
break;
case 2:
cout << a - b << endl;
break;
case 3:
cout << "Exiting the application.\n";
break;
default:
cout << "Invalid option! Please select a valid option";
break;
}
}
do...while loop
do...while loop statement
● It is very similar to while loop, executes a sequence of instructions until a condition is satisfied.
● do...while is called an exit controlled loop, whereas for and while loops are entry controlled
loops.
● Syntax: do
{
statement(s);
} while (condition);
○ First, the statements inside the loop get executed and then the condition gets evaluated.
○ If the condition evaluates to true, then the statements inside the loop execute again, this
happens repeatedly until the condition returns false.
○ Once the condition evaluates to false, the next statement after the while loop is executed.
Flow diagram - do...while loop
do
{
statements statement(s);
inside do...while } while (condition);
loop
● Create a while loop that prints out the name of the color based
on the input from the user.
Input Color
● Use the information in the table.
R or r Red
● Inside the loop, ask for input from the user and print the colour, G or g Green
until the user presses ‘q’ or ‘Q’.
Y or y Yellow
● Build and run the program.
B or b Blue
P or p Pink
Q or q Quit
Nested loops
Infinite loops
Nested loops
● The body of a loop can contain another loop; this is known as nested loops.
● The inner loop must be completed each time through the outer loop.
● Sometimes, it is desirable to skip the execution of a loop for a certain condition or terminate it
immediately without checking the condition.
● In C++, there are two statements to specifically alter the normal flow of a loop. They are:
○ break
○ continue
● For example, we want to loop through the data of all aged people except people aged 55. Or if we want
to find the first person aged 20. In these scenarios, break and continue statements can be used.
break statement
● Used to terminate the loop or switch statement and transfers execution to the statement immediately
following the loop or switch.
● In practice, break statement is always used inside the body of conditional statement (if..else)
inside the loop.
● Syntax:
break;
● If we are using nested loops (one loop inside another loop), the break statement in the innermost loop
will terminate the inner loop and start executing the next line of code in the outer loop after the inner
loop block.
How break statements work
int main()
{
int m = 1;
What two conditions
will result in exiting while (m != 0)
the while loop? {
cin >> m;
if (m == 20)
{
cout << "Found the first person aged 20.\n";
break;
}
}
cout << "This statement is always executed\n";
return 0;
}
continue statement
● Causes the loop to skip the rest of the statements in the body and immediately forces the next
iteration of the loop to take place.
● When used in for loop, continue causes the condition test and increment portions of the loop to
execute. For the while and do...while loops, continue causes the condition test of the loop to
execute.
● Syntax: continue;
int main()
{
for (int i = 1; i <= 10; i++)
{
// the program skips 6 and 7
if (i == 6 || i == 7)
continue;
else
cout << i << endl;
}
return 0;
}
Activity - continue and break
● Use break statement when the user input ‘q’ or ‘Q’ R or r Red
G or g Green
● Use continue statement when the user input does not match with any
one of inputs from the table. Y or y Yellow
P or p Pink
Q or q Quit
Summary
● Loop statements are used when we need to execute a block of statements repeatedly.
● while loop is used to repeat a statement or group of statements when a given condition is true.
● do...while loop is similar to while loop, but it tests the condition at the end of the loop body.
● Nested loops are one or more loops inside any another while, for or do...while loop.
● continue statement causes the loop to skip the rest of the statements in the body of the loop.
References
Grimes, R (2017). Beginning C++ Programming. (1st ed.). United Kingdom: Packt Publishing Ltd