Close
Close

Loops in C++


Playing with loops makes programming fun. Before we try to understand loop, you should be thorough with all the previous topics of C++. If not, practice a considerable amount of problems of all the previous topics.

Suppose, we have to print the first 10 natural numbers.

One way to do this is to print the first 10 natural numbers individually using cout. But what if you are asked to print the first 100 natural numbers! You can easily do this with the help of loops.

Broadly classifying, there are three types of loops in C++ which are:

  1. while loop
  2. for loop
  3. do...while loop

while loop

Let's first look at the syntax of while loop.

while(condition)
{
    statement(s)
}

while loop checks whether the condition written in ( ) is true or not. If the condition is true, the statements written in the body of the while loop i.e., inside the braces { } are executed. Then again the condition is checked, and if found true, again the statements in the body of the while loop are executed. This process continues until the condition becomes false.

An example will make this clear.

#include <iostream>
int main(){
    using namespace std;
    int n = 1;
    while( n <= 10){
        cout << n << endl;
        n++;
    }
    return 0;
}
Output
1
2
3
4
5
6
7
8
9
10

In our example, firstly, we assigned a value 1 to a variable 'n'.

while(n <= 10) - checks the condition 'n <= 10'. Since the value of n is 1 which is less than 10, the statements within the braces { } are executed.

The value of 'n' i.e. 1 is printed and n++ increases the value of 'n' by 1. So, now the value of 'n' becomes 2.

Now, again the condition is checked. This time also 'n <= 10' is true because the value of 'n' is 2. So, again the value of 'n' i.e., 2 gets printed and the value of 'n' will be increased to 3.

When the value of 'n' becomes 10, again the condition 'n <= 10' is true and 10 gets printed for the tenth time. Now, n++ increases the value to 'n' to 11.

This time, the condition 'n <= 10' becomes false and the program terminates.

Quite interesting. Isn't it !

loops in C++

The following animation will also help you to understand the while loop.

gif of while loop in C++

Let's see one more example of while loop

#include <iostream>
int main(){
	using namespace std;
	int choice = 1;
	while( choice == 1 ){

		int a;

		cout << "Enter a number to check even or odd" << endl;
		cin >> a;		//input number

		//check whether number is even or odd

		if( a%2 == 0 ){
			cout << "Your number is even" << endl;
		}
		else{
			cout << "Your number is odd" << endl;
		}

		cout << "Want to check more : 1 for yes and 0 for no" << endl;

		cin >> choice;
	}

	cout << "I hope you checked all your numbers" << endl;

	return 0;
}
Output
1
2
3
4
5
6
7
8
9
10

The loop will run until the value of 'choice' becomes other than '1'. So, for the first time, it will run since the value of 'choice' is '1'. Then it will perform the codes inside the loop. At last, it will ask the user whether he wants to check more or not. This can change the value of variable 'choice' and may terminate the loop.

Initially, the value of 'choice' was 1, so, the condition of while got satisfied and codes inside it got executed. We were asked to give the value of choice and we gave 1 again. Things repeated and after that, we gave choice a value of 0. Now, the condition of while was not satisfied and the loop terminated.

for loop


Another type of loop is for loop.

Let's go to our first example in which we printed first 10 natural numbers using while loop. We can also do this with for loop.

Let's look at the syntax of for loop.

for(initialization; condition; propagation)
{
    statement(s)
}

#include <iostream>
int main(){
	using namespace std;
	int n;
	for( n = 1; n <= 10; n++ ){
		cout << n << endl;
	}
	return 0;
}
Output
1
2
3
4
5
6
7
8
9
10

Now let's see how for loop works.

for(n=1; n<=10; n++)

n=1 - This step is used to initialize a variable and is executed first and only once. Here, 'n' is assigned a value 1.

n<=10 - This is a condition which is evaluated. If the condition is true, the statements written in the body of the loop are executed. If it is false, the statement just after the for loop is executed. This is similar to the condition we used in 'while' loop which was being checked again and again.

n++ - This is executed after the code in the body of the for loop has been executed. In this example, the value of 'n' increases by 1 every time the code in the body of for loop executes. There can be any expression here which you want to run after every loop.


In the above example, firstly, 'n=1' assigns a value 1 to 'n'.

Then the condition 'n<=10' is checked. Since the value of 'n' is 1, therefore the code in the body of for loop is executed and thus the current value of 'n' i.e., 1 gets printed.

Once the codes in the body of for loop are executed, step n++ is executed which increases the value of 'n' by 1. So now the value of 'n' is 2.

Again the condition 'n<=10' is checked which is true because the value of 'n' is 2. Again codes in the body of for loop are executed and 2 gets printed and then the value of 'n' is again incremented.

When the value of 'n' becomes 10, the condition 'n <= 10' is true and 10 gets printed. Now, when n++ increases the value to 'n' to 11, the condition 'n<=10' becomes false and the loop terminates.

Don’t you think it’s just a different form of while loop? Yes, it is actually.

for and while same in C++

Let's see the example of adding 10 numbers.

#include <iostream>
int main(){

	using namespace std;
	int sum = 0, i, n;

	for(i = 0; i < 10; i++){

		cout << "Enter number" << endl;
		cin >> n;

		sum = sum + n;

	}
	cout << "Sum is " << sum << endl;

	return 0;

}
Output
Enter number
4
Enter number
3
Enter number
10
Enter number
3
Enter number
5
Enter number
5
Enter number
1
Enter number
8
Enter number
9
Enter number
2
Sum is 50

Initially, the value of the variable sum is 0.
In the first iteration, the value of n is entered 4 and thus the value of sum becomes 4 since sum = sum + n (i.e. sum = 0 + n).
In the second iteration, the value of sum is 4 and we entered the value of n as 3. Therefore, the expression sum = sum + n gets evaluated as sum = 4 + 3, thus making the value of sum as 7.
In this way, this loop will add all the 10 numbers entered by the user.

There are other ways also to write program of for loop.

The first example of for loop in which we printed the first 10 natural numbers can also be written in other ways which are :

int n = 1;
for( ; n <= 10; n++)
{
    cout << n << endl;
}

Another way is shown below.

int n;
for( n = 1; n <= 10; )
{
    cout << n << endl;
    n++;
}

It means that we can also write the for loop by skipping one or more of its three statements (initialization, condition, propagation) as done above.

There is also an another form of for loop which is discussed in the chapter 'array'.

do...while loop


This is another kind of loop. This is just like while and for loop but the only difference is that the code in its body is executed once before checking the conditions.

Syntax of do...while loop is:

do{
    statement(s)
}
while( condition );

Consider the same example of printing the first 10 natural numbers for which we wrote programs using while and for loop. Now, let's write its program using do...while loop.

#include <iostream>
int main(){

    using namespace std;
    int n = 1;
    do{
    	cout << n << endl;
      	n++;
    }while( n <= 10 );
    return 0;
}
Output
1
2
3
4
5
6
7
8
9
10

Let's try to understand this.

At first, the statements inside the body of loop (i.e., within the braces { } following do ) are executed. This will print the value of 'n' i.e., 1 and n++ increments the value of 'n' by 1. So now, the value of 'n' becomes 2.

Once the code inside the braces { } is executed, condition 'n <= 10' is checked. Since the value of 'n' is 2, so the condition is satisfied.

Again the code inside the body of loop is executed and the value of 'n' becomes 2. When the value of 'n' is 10 and 10 is printed, n++ increases the value of 'n' to 11. After this, the condition becomes false and the loop terminates.

As you have seen, in do while loop, codes inside the loop got executed for the first time without checking any condition and then it started checking the condition from the second time.


Nesting of loops

Like 'if/else' we can also use one loop inside another. This is called nesting of loop. See this example to make it clear.

#include <iostream>
int main(){
	using namespace std;
	int i;
  	int j;

  	for(i = 12; i <= 14; i++){            /*outer loop*/

  		cout << "Table of " << i << endl;

    		for(j = 1; j <= 10; j++){         /*inner loop*/

      			cout << i << "*" << j << "=" << (i*j) << endl;

    		}
  	}
	return 0;
}
Output
Table of 12
12*1 = 12
12*2 = 24
12*3 = 36
12*4 = 48
12*5 = 60
12*6 = 72
12*7 = 84
12*8 = 96
12*9 = 108
12*10 = 120
Table of 13
13*1 = 13
13*2 = 26
13*3 = 39
13*4 = 52
13*5 = 65
13*6 = 78
13*7 = 91
13*8 = 104
13*9 = 117
13*10 = 130
Table of 14
14*1 = 14
14*2 = 28
14*3 = 42
14*4 = 56
14*5 = 70
14*6 = 84
14*7 = 98
14*8 = 112
14*9 = 126
14*10 = 140

When the first for loop is executed, the value of i is 12 and "Table of 12" gets printed.
Now coming to the second loop, the value of j is 1 and thus 12*1 = 12 gets printed.
In the second iteration of the inner for loop, while the value of i is still 12, the value of j becomes 2 and thus 12 * 2 = 24 gets printed.
In the last iteration of the inner for loop, the value of i is still 12 and the value of j becomes 10, thus printing 12 * 10 = 120.
Now after all the iterations of the inner for loop are complete, there will be the second iteration of the outer for loop increasing the value of i to 13 and printing Table of 13. Again the inner for loop will be iterated with i equals 13.

We can use any loop inside any other loop according to the requirement. In the above example, we used one for loop inside another.

Infinite Loop


There may exist some loops which can iterate or occur infinitely. These are called Infinite Loop. These loops occur infinitely because their condition is always true. We can make an infinite loop by leaving its conditional expression empty (this is one of the many possible ways). When the conditional expression is empty, it is assumed to be true. Let's see an example on how to make a for loop infinite.

#include <iostream>
int main(){
	using namespace std;
	for( ; ; ){
		cout << "This loop will never end" << endl;
	}
	return 0;
}
Output
This loop will never end
This loop will never end
This loop will never end
This loop will never end
This loop will never end
This loop will never end
This loop will never end
This loop will never end
This loop will never end
This loop will never end
This loop will never end
This loop will never end
This loop will never end
...

I told you, it's fun!

To terminate an infinite loop, press Ctrl + C.
To learn from simple videos, you can always look at our C++ video course on CodesDope Pro. It has over 750 practice questions and over 200 solved examples.

Don't spend so much time trying to choose the perfect opportunity that you miss the right opportunity.
-Michael Dell

Ask Yours
Post Yours
Doubt? Ask question