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

C++ 5. Loop Statements

The document discusses loops in programming, including for, while, and do...while loops. It defines what loops are and why they are useful for avoiding repeated code. It then explains the basic syntax and flow of each loop type, providing examples of printing text a certain number of times using each loop. Key details covered include initializing and updating a counter variable, evaluating loop conditions, and executing loop bodies sequentially until the condition is no longer met.

Uploaded by

Thomas Graham
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)
11 views

C++ 5. Loop Statements

The document discusses loops in programming, including for, while, and do...while loops. It defines what loops are and why they are useful for avoiding repeated code. It then explains the basic syntax and flow of each loop type, providing examples of printing text a certain number of times using each loop. Key details covered include initializing and updating a counter variable, evaluating loop conditions, and executing loop bodies sequentially until the condition is no longer met.

Uploaded by

Thomas Graham
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/ 33

Bachelor of Information Technology

PRG1002 - Programming I

Loop Statements

Repeating steps in a program


● What is a loop?
Contents
● Types of loop statements

● Loop control statements


What are loops?

● 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:

cout << "Hello, world!" << endl;


cout << "Hello, world!" << endl;
cout << "Hello, world!" << endl;
cout << "Hello, world!" << endl;
cout << "Hello, world!" << endl;

● But we can use loops to make our code more succinct and DRY.
DRY: Don’t Repeat Yourself

● One programming principle is that code should be DRY

● It means that when possible, avoid repeating lines of code

● 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

C++ programming language provides the following type of loops:

● for loop

● while loop

● do...while loop
for loop
for loop statement

● A loop that executes a sequence of statement(s) a specific number of times.

● Syntax is: for (init; condition; expression)


{
statement(s);
}

○ 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

for (init; condition; expression)


init {
statement(s);
}

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.

● The loop continues until i reaches 10, and will


print out “hello, world!“10 times.
Activity - for loop

● Create a new C++ project that goes by the name ActFLoop.

● Create a for loop that prints out your name 7 times on the console window.

● Build and run the program to check the output.

● 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

● Build and run the program to check the output.


while loop
while loop statement

● 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

statements statements after


inside while loop while loop
Example - while loop
● The body of the loop lives inside the curly {
and } brackets.

● In this example, the condition is m <= 10, as


long as this condition is true, the body of the
int main()
{ loop will execute.
int m = 1;
while (m <= 10)
● So, m starts at 1 and the current value of m is
{
cout << "hello, world!" << endl; less than or equal to 10, so it executes the
m++; statements inside the loop, which means it will
}
print out hello, world!.
return 0;
}
● After the above step, it increments the value
of m by 1 and rechecks the condition.

● The loop will execute until m > 10, printing


“hello, world!” 10 times
Discuss the code

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.

● The main difference between while and do...while is:


○ do...while evaluates the condition at the end of loop body.
○ while evaluates the condition at the start of the loop body.

● do...while is called an exit controlled loop, whereas for and while loops are entry controlled
loops.

● A do...while loop will always execute at least once.


do...while loop syntax

● Syntax: do
{
statement(s);
} while (condition);

○ Note: The while statement ends with a semicolon (;)

○ 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

true false statements after


condition
while loop
Example - do...while loop
● In this example, the body of the statements
gets executed first and then the condition is
evaluated. The condition is m <= 6, as long as
this condition is true, the body of the loop will
int main() execute.
{
int m = 1;
do ● It executes the statements inside the loop
{ first, which means it will print out Value of
cout << "Value of m: " << m << endl;
m++;
m: 1.
} while (m <= 6);
return 0; ● After the above step, it increments the value
}
of m by 1.

● The loop executes until m > 6, and prints each


value of m in the loop body. The last thing it
prints is Value of m: 6.
Activity - do...while loop

● Create a C++ project called ColourPicker.

● 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.

● In the below example,


○ it starts the row loop first, and enters the column loop and executes the statements inside the column loop until
it reaches 5.
○ Then, it exits out of the column loop and goes through the row loop and the above steps are repeated until the
value of row reaches 5.
for (int row = 1; row <= 5; row++)
{
for (int col = 1; col <= 5; col++)
{
cout << "row " << row << ", col " << col;
cout << "\t";
}
cout << endl;
}
Infinite loop

● A loop that never stops executing the int main()


{
statements inside its body is said to be an
for (int i=1; i<5 ;i--)
infinite loop. {
cout << "Infinite for loop\n";
}
● An infinite loop occurs when a condition never
return 0;
evaluates to false. Usually this is an error. }

● In the first example, the for loop i will always


int main()
be less than 5, so the message will be printed {
infinite times, until we force close the app. int m = 0;
while (m <= 10)
{
● In the second example, the the value of m is cout << "Infinite while loop\n";
never changed to the program is stuck in an }
return 0;
infinite loop.
}
Loop control statements
Altering normal loop execution
Loop control statements

● 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;

● In practice, continue statement is almost always used inside conditional statement.


How continue statement works?

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

● Open ActDWLoop project. Input Color

● 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

● Build and run the program. B or b Blue

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.

● for loop is used to execute a sequence of statements specific number of times.

● 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.

● break statement terminates the loop or switch statement.

● 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

Tutorialspointcom. 2019. Wwwtutorialspointcom. [Online]. [11 July 2019]. Available from:


https://www.tutorialspoint.com/cplusplus/cpp_loop_types

Programizcom. 2019. Programizcom. [Online]. [11 July 2019]. Available from:


https://www.programiz.com/cpp-programming/do-while-loop

You might also like