Introduction to Loops
Learn how a block of statements can be repeated n times using "for" and "while" loops.
If we look at the table printing program, we’ll notice that we’re repeating a similar kind of instruction with some changes in each instruction. Instead of writing the same instruction repeatedly, we can avoid rewriting the code using repetition statements.
To repeat a piece of code (set of statements), almost every programming language offers loops. Using loops, our work becomes a lot easier and more manageable.
We will learn about two types of loops, the while
loop and the for
loop.
The while
loop
The syntax of the while
loop is as follows:
while(condition){// Body(statements) of while}
If the condition is true
, then the body of the loop will be executed. After completely executing the body once, the condition of the while
loop will be rechecked. If it is true
, then the body will be executed again, and this process will continue until the condition becomes false
.
See the animation below to understand the working process of a while
loop.
Observe in the above animation:
- In line 1,
a
is initialized to1
. - In line 2, the
while
condition(a < 5)
is checked. Since the condition istrue
(1 is less than 5), the body of thewhile
loop executes. - In line 4, the value of
a
is printed.
The value of
a
throughout the life of the program can be seen in the “Watches” box.
- In line 5, the value of
a
is incremented by2
(from 1 to 3, then 5 and so on) in each iteration. - After having executed all the statements in the body of the loop (lines 4–5), the
while
condition in line 2 is checked again. If it istrue
, the body executes again and this continues until thewhile
condition isfalse
, which is when the value ofa
becomes5
after the 3rd iteration.
Now let’s use the while
loop in our code.
#include <iostream>using namespace std;//This program should print the quoted message infinitelyint main(){while(true){cout << "hello" << endl;}cout << "Program ended...!";return 0;}
Did you notice something interesting about the program above?
The while loop above has no stopping condition and the loop is infinite!
Every time after the execution of the body statements, the condition will be true
and therefore the body will be executed again.Thus, this program will never end and keep printing the word “hello” infinitely. The instruction on line 12 will never get executed.
The loop that repeats its iteration continuously and never stops is called an infinite loop. An infinite loop must be avoided.
Exercise
Now, what happens if we replace true
with false
in the while
condition above?
Instruction: Change the line 8 above to while(false)
to see whether the body of the loop executes or not. You will see that the inside of the loop will never get executed, and it will execute line 12.
Printing “hello” multiple times using while loop
Now let’s see a while
loop where the condition eventually will become false
and the loop will terminate. Let’s write a program that prints hello
10 times.
#include <iostream>using namespace std;/*This program should print the quoted message until the conditionof while loop becomes false.In this program while loop runs 10 times. */int main( ){int time = 1;while(time <= 10){cout << time << ": hello" << endl;time = time + 1;}return 0;}
Read the code carefully to understand it. We can see the following:
- In line 8, the
time
variable is initialized to1
. - In line 9, the loop is executed until
time
is less than or equal to10
. - If the condition is
true
, everything inside the block{...}
(lines 10 to 13) is executed. - In line 11, it prints
hello
and the value oftime
. - In line 12, the value of
time
is incremented by1
on each iteration. This is to maintain the count of how many times we have already printed and what should be the next count. - After line 13, the condition on line 9 is rechecked, and the process is repeated until the condition becomes
false
.
Quiz: Understanding the execution of loops.
If we add the instruction cout << time;
after the loop, what will be the output?
The for
loop
The for
loop is another loop that can be used to execute a block of statements times.
The syntax of the for
loop is as follows:
for(variable initialization; condition; variable increment/decrement){// Body(statements) of for loop}
See the animation below to understand the working process of the for
loop.
In a for
loop:
-
First, the control variable is declared and initialized. In the above animation,
int i=1
is the control variable. This part gets executed only once during the execution of the loop. -
Then, the condition expression is evaluated. In the above animation,
i<5
is the condition that is checked before entering the body part of the loop.- If
true
, each instruction inside the loop body is executed. - If
false
, thefor
loop breaks, and the control goes after the loop.
- If
-
Variable increment/decrement: We usually increase or decrease the control variable using arithmetic operations. After executing all the instructions in the loop’s body, the control variable is updated according to the instruction in this step. We will see in the later chapter further what kind of changes can be performed in this step.
- An important point to note is that this part is not executed in the first iteration and only gets executed from the second iteration.
Did you notice that everything we did before using the
while
loop can also be done using thefor
loop as well? The only difference is that the variable’s initialization and update step in thefor
loop is part of its syntax. This was done as a precautionary measure as programmers usually tend to forget these statements of initialization and update, causing logical errors which usually leads to infinite loops.
Let’s write our first program using the for
loop.
Printing “hello” multiple times using for loop
The program below prints hello 10 times and also shows the incremented value of time. Click “Run” to see the output.
#include <iostream>using namespace std;/*This program should print the quoted message until the condition of for loop becomes false.In this program for loop runs 10 times.*/int main(){for(int time = 1; time <= 10; time++){cout << time << ": hello" << endl;// On every iteration, time will be replaced by its value followed by “hello” message.}return 0;}
Exercise
Change the above two (both while
and for
loop) programs in the respective two code editors above such that the message "hello"
is printed 15 times.
Now that we have learned what loops are and how to use them, let’s use them in our table printing program!
Table printing (cont.)
We had already established how inconvenient and repetitive it was to write the same code lines again and again. In fact, when printing a table in all the previous lessons so far, we saw that printing a certain number’s table up to a certain limit is very cumbersome. We have to remove or rewrite more lines depending on the program’s requirement.
Table printing using the for loop
The following code uses a for loop that prints the first multiples of some number stored in Table
:
for(int i = 1; i <= 15; i++){cout << Table << " x " << i << " = " << Table*i << endl;}
We can see how the for
loop has reduced our original table printing code. Let’s suppose the number stored in Table
is 3.
Initially as i
is 1
and as i <= 15
, the code in line 3 will print 3 x 1 = 3
. The i
will be incremented by 1
and then will print 3 x 2 = 6
and so on until i
becomes 16
. As soon as it becomes 16
, the loop ends.
Table printing using while loop
The following code uses the while
loop that prints the first ten multiples of some number stored in Table
:
int i=1;while(i <= 15){cout << Table << " x " < i << " = " << Table*i << endl;i = i + 1;}
The while
loop works the same way as the for
loop except that it has a different syntax. The i
in the while
loop is incremented in line 5.
Initially as i
is 1
and as i <= 15
, the code in line 4 will print 3 x 1 = 3
. The i
will be incremented by 1
and then will print 3 x 2 = 6
and so on until i
becomes 16
. As soon as i
becomes equal to 16
, the condition in line 2 is checked but since the condition is false
, the loop ends.
#include <iostream>
using namespace std;
/* Printing the table up to
15th multiple using while loop
according to the user's input */
int main()
{
int Table;
cout << "Which Table: ";
//Let us say the user entered 12
cin >> Table;
int i=1;
while(i <= 15)
{
cout << Table << " x "
<< i << " = "
<< Table*i << endl;
i = i + 1;
}
return 0;
}
#include <iostream>
using namespace std;
/* Printing the table up to
15th multiple using for loop
according to the user's input */
int main()
{
int Table;
cout << "Which Table: ";
//Let us say the user entered 12
cin >> Table;
for(int i = 1; i <= 15; i++)
{
cout << Table << " x "
<< i << " = "
<< Table*i << endl;
}
return 0;
}
From the above two code snippets, we can see how our table printing code has now become super concise and convenient to both write and modify.
Exercise
Now test and run the above code by writing it down in the code editor below.
#include <iostream>using namespace std;/*Print the table of a number up to its15th multiple using while or for loop*/int main(){//add code here}
Enter the input below
Before moving forward to print the table, let’s practice more on loops in the upcoming lessons.