Introduction to Loops
Learn the loops for a fixed number of iterations in C++.
Repetition
The repetition of an instruction or a group of instructions is a commonly encountered phenomenon in programming. It is called a loop. As an example, let’s say we want our program to perform the following tasks:
- To read a document or data file line by line repeatedly until the end of the file
- To draw an image pixel by pixel, repeatedly using color values that show it on the screen
- To iterate through a collection of variables one by one to process their values
- To compute a result by applying a formula to several values
Let’s say we want to display integers from to . We can simply display the numbers to one by one using the cout <<
statement. We can also use one variable and print its value repeatedly by changing the value of the variable, as shown below. For a better understanding, you can take the AI mentor’s help.
#include <iostream>using namespace std;int main(){int a;a = 0;cout << a << endl;a = 1;cout << a << endl;a = 2;cout << a << endl;a = 3;cout << a << endl;a = 4;cout << a << endl;return 0;}
The code above clearly shows the repetitive use of cout << a << endl;
. The benefit of using a single variable is that we can convert this repetition into a loop in C++.
The counter-controlled loop
The counter-controlled loop is used to generate a sequence of values. This loop has four parts after the for
keyword as shown below:
for (initialization; condition; update)
{
// body of loop
}
The initialization value initializes the counter and is executed only once. The condition value checks the value of the counter at the start of each iteration before entering the body of the loop. If true, the body of the for
loop is executed and if false, the for
loop is terminated. The update value updates the value of the counter and again checks the condition.
We use the semicolon (;
) only at the end of the first two parts and enclose these parts in (
and )
. We don’t use a semicolon after )
. The body of the loop is a set of statements to be repeated.
Note: If there is only one statement in the body of the loop, the curly braces
{
and}
are not needed.
The following code demonstrates the same output as the above program in a compact way using the counter-controlled loop.
#include <iostream>using namespace std;int main(){for (int a = 0; a < 5; a++)cout << a << endl; // Body of the loopreturn 0;}
The for
loop causes lines 5 and 6 to be repeated five times. Therefore, we can say the loop has five iterations.
In the code above:
- We use the
int
variable,a
, as the counter and initialize it with0
. - We use
a < 5
as a condition. - We update the value of
a
after each iteration. - The body of the loop starts after
)
. - The loop’s body contains only one statement,
cout << a << endl;
.
There are two repeatable lines in the program, but when we unfold the loop and write out each step as it happens, there are execution steps. The loop iterates all values based on the condition to execute each statement in the body of the loop.
Let’s take an example of generating the first five non-negative even numbers—0
, 2
, 4
, 6
, and 8
.
#include <iostream>using namespace std;int main(){for (int a,e = 0; a < 5; a++){e = a * 2; // Multiplying the value by 2cout << e << endl;}return 0;}
In the for
loop, we can have initialization of multiple variables separated by a comma, as shown in line 5 in the code above.
Lines 7–8 are the body of the loop.
Let’s take another example of generating the first 100 non-negative even numbers: .
#include <iostream>using namespace std;int main(){for (int count = 0; count < 100; count++){int evenNumber = count * 2;cout << evenNumber << endl;}return 0;}
In the program above, the counter generates values from to , and we multiply each value by , displaying 0 * 2
, 1 * 2
, 2 * 2
… 99 * 2
. The lines 6–9 constitute a block of two statements representing the body of the loop.
We may generate even numbers with the same sequence as above using an increment value of 2
in the counter. We may directly use the for (int c = 0; c < 200; c += 2)
, as shown in the following program:
#include <iostream>using namespace std;int main(){for (int c = 0; c < 200; c += 2)cout << c << endl;return 0;}
If we want to generate the multiples of 7
between 1
and 700
, we can use int i = 7; i < 700; i += 7
. We use 7
as starting value so that every increment of 7
may take us to the next multiple of 7
. Incorporating this in the for
loop will allow us to show the generated values as output.
Programming practice for counter-controlled loops
The following are a few examples to help you practice writing the programs in C++. By clicking the “Show Solution” button (after you “Run” the code), you can see one of the possible solutions to the problem. There can be several ways to write correct solutions in programming.
Odd numbers
Write a program that prints the first 100 positive odd numbers .
#include <iostream>using namespace std;int main(){// Write your code herereturn 0;}
Arithmetic sequence
An arithmetic sequence is an ordered set of numbers that have a common difference between each consecutive term.
Write a program that prints the terms of the sequence .
#include <iostream>using namespace std;int main(){// Write your code herereturn 0;}
Table of
Write a program that takes an integer input by the user and prints a multiplication table for the first 20 multiples, as illustrated below.
Sample input
5
Sample output
5 x 1 = 5
5 x 2 = 10
.
.
.
5 x 20 = 100
#include <iostream> using namespace std; int main() { // Write your code here return 0; }
Mean of inputs
Write a program that calculates the average of the numbers input by the user. The program first asks the user how many values they want to average. The number of values should be greater than .
Sample input
4
10
20
30
40
Sample output
The average is : 25
#include <iostream> using namespace std; int main() { // Write your code here return 0; }
Factors of the user input
Write a program that shows all the factors of a number provided by the user.
Sample input
20
Sample output
1
2
4
5
10
20
#include <iostream> using namespace std; int main() { // Write your code here return 0; }
Prime or not
A prime number is divisible only by itself and .
Write a program that shows whether or not the natural number input by the user is a prime number.
Sample input 1
7
Sample output 1
7 is a prime number
Sample input 2
20
Sample output 2
20 is not a prime number
#include <iostream> using namespace std; int main() { // Write your code here return 0; }