...

/

Untitled Masterpiece

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 00 to 44. We can simply display the numbers 00 to 44 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.

C++
#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:

 ...