C++ for loop with detailed explanation and examples

What is for loop?

The basic definition of for loop is that it executes one or more statements a specified number of times. For loop is also called a counter control loop. It is the most flexible loop and is most frequently used by programmers. The for loop is used when you know the fixed number of iterations or the exact number of iterations.


A for loop runs provided the given test expression or condition is true and stops execution immediately when the given condition becomes false.


This means that before the execution of the loop body in every iteration. The condition is first evaluated if it is true, it evaluates the loop body, and if the condition is false, it stops evaluation.

Flow of execution of the for loop:

Flow of execution of for loop
The flow of execution of for loop

Flow chart explanation:

  • In the first step, the compiler evaluates the initialization step. This step is only done once as the execution of the loop begins.
  • After the initialization step, the test expression or condition is executed.
  • After the execution of test expression, if the condition returns true, the loop’s body is executed, and the test expression or condition is updated.
  • The increment or decrement is executed to update the loop’s control variable value after the execution of the loop body.
  • The test expression is re-evaluated, and this process continues until the condition becomes false.
  • In the sixth step, which also comes after the second step, the condition is executed if the condition returns false, the loop body statements are skipped, and the compiler moves outside the loop.

Syntax of for loop:

// syntax of for loop
for (initialization; condition; increment/decrement)
{
     Statement(s);
}

Syntax of nested for loop:

// syntax of Nested For loop
for (initialization; condition; increment/decrement)
{
     for (initialization; condition; increment/decrement)
     {
         Statement(s);
     }
      Statement(s);
}

Initialization expression:

It specifies the starting value of the counter variable. One or many variables can also be initialized in this part. To initialize more than one variable, we separate each variable with a comma (,). The initialization part is only executed once.

Example of initializing more than one variable is as follow:

// initializing more than one variable in for loop
for(int i = 0, j = 1;i<5;i++)
    {
        cout<<" i =  "<< i <<" j = "<< j<<endl;
        j++;
    }

We can also initialize values outside the for loop.

We can also initialize the values outside the for loop.

// initialize values outside the for loop
int i = 0, j = 2;
for (i, j; i < 5; i++, j = j + 2)
{
	cout << " i " << i << " j " << j << endl;
}

Conditional statement:

The conditional statement part is executed after the initialization step. To run the loop body, it must be true. If the condition is true, then the body of the for loop is executed, and if the condition is false, execution will directly jump on the statement after the for loop.

If the condition is incorrect in the first attempt, then the loop body will never be executed.

Increment:

After executing the loop body, the control jumps to this part and performs increments.
We can also remove this part and only use a semicolon instead.


After executing this part again, the condition is evaluated, and if it is true, then the loop body is again performed, and this is continued. The loops terminated immediately the condition becomes false.

Example of increment in for loop:

// example of increment in for loop 
int i = 0, j = 2;
for (i, j; i < 5;)
{
	cout << " i " << i << " j " << j << endl;
	i++;
	j++;
}

Jumping out of a loop:

While executing a loop, it becomes essential to skip the part of the loop’s body or leave the loop when a specific condition becomes true. This is also called jumping out of the loop.


C++ provides us with many methods or statements of jumping from one statement to another within a loop and jumping out of the loop.

Break statement:

When the break statement is used inside the loop, the loop is exited, and the program continues with the statement after the loop.

Example of break statement in for loop:

// example of break statement in for loop
#include<iostream>
using namespace std;
int main()
{
	int i = 0, j = 2;
	for (i, j; i < 5;)
	{
		cout << " i " << i << " j " << j << endl;
		i++;
		if (i == 3)// this condition checks that the value of i is 3 or not
			break;
		j++;
	}
	system("pause");
	return 0;
}

Output:

Example of break statement in for loop

From the given example, you can easily see that the control quits the loop cycle when the value of I becomes three and the control moves outside the loop, and the program quits.

Continue statement:

The main work of the continue statement is that it causes the control to go to the loop’s base condition directly, and then the loop process again continued.


When this statement is executed, the control leaves the current cycle of the loop and starts with the new cycle.

Example of continue statement:

// example of continue statement in for loop
#include<iostream>
using namespace std;
int main()
{
	int i = 0, j = 2;
	for (i, j; i < 5;)
	{
		
		i++;
		if (i == 3)// this condition checks that the value of i is 3 or not
			continue;
		cout << " i " << i << " j " << j << endl;
		j++;
	}
	system("pause");
	return 0;
}

Output.

Example of continue statement in for loop

From the given example, you can easily see that the control moves to the loop’s starting when the I value becomes 3.


This means it quits the current cycle when the value of I becomes three and the control moves to the starting of the loop, and the new cycle begins.

goto statement:

The goto statement is used to transfer control to the tabled statement. The goto statement provides an unconditional jump from the goto statement to the label in the same function.


Most programmers restrict us from using the goto statement in the program because it creates an unconditional transfer of control, and it is also difficult to track it.

Syanax of goto statement.

The syntax of the goto statement is as follow.

// syntax of goto statement
goto label;

label:
statements;

Example of goto statement:

// example of goto statement
#include<iostream>
using namespace std;
int main()
{
	int n = 10;
        cout << " Required output is : " << endl;
label:// label
	cout << " " << n;
	n--;
	if (n > 0)
		goto label;
	cout << endl;
	system("pause");
	return 0;
}

Output:

output of goto statement in C++

Infinite for loop:

When a loop executes repeatedly and never ends, then it is called an infinite loop. This loop occurs because of an error.

For example, your entered condition in for loop will never return false, or you forgot to write anything in the condition part of for loop.

Some examples of infinite for loop are as follows.

1st example of infinite for loop:

// 1st example of infinite for loop
#include<iostream>
using namespace std;
int main()
{
	int i = 0, j = 2;
	for (; 😉
	{
		cout << " Infinite loop : " << endl;
	}
	system("pause");
	return 0;
}

2nd example of infinite for loop:

// 2nd example of infinite for loop
#include<iostream>
using namespace std;
int main()
{
	for (int i = 0; ;i++)
	{
		cout << " The value of i is : "<< i << endl;
	}
	system("pause");
	return 0;
}

3rd example of infinite for loop:

// 3rd example of infinite for loop
#include<iostream>
using namespace std;
int main()
{
	for (int i = 1; i > 0; i++)
	{
		cout << " The value of i is : " << i << endl;
	}
	system("pause");
	return 0;
}

C++ Examples of For loop with scenario questions:

Write a program that displays product of all odd numbers from 1 to N.

// C++ program to display product of all odd numbers from 1 to N using for loop.
#include<iostream>
using namespace std;
int main()
{
	int n = 0, product = 1;
	cout << " Enter last limit : ", cin >> n;// enter the last limit
	for (int i = 1; i < n; i = i+2)// loop to calculate the product of numbers from 1 to the given last limit
	{
		product = product *i;// in each iteration the previous product is multiplied by the odd number
	}
	cout << " Required product is : "<< product << endl;
	system("pause");
	return 0;
}

Output:

Output of displaying product of all odd numbers from 1 to N

Write a C++ program that displays the elements of a character array using for loop:

// C++ program to display the elements of character array using for loop.
#include<iostream>
using namespace std;
int main()
{
	char arr[12] = { 'C', 'O', 'D', 'E', 'F', 'O', 'S', 'S', 'I', 'L', 'S', '\0' };
	cout << " Data in array is as follow : " << endl;
	for (int i = 0; arr[i] != '\0'; i++)// loop to display all data in character array
	{
		cout << " " << arr[i];
	}
	cout << endl;
	system("pause");
	return 0;
}

Output:

The output of displaying the elements of characters array

Write a C++ program that finds the sum of the squares of integers from 1 to N.

// C++ program to find the sum of the square of intigers from 1 to N.
#include<iostream>
using namespace std;
int main()
{
	int sum = 0, n = 0;
	cout << " Enter the last limit : ",cin >> n;
	for (int i = 1; i<=n; i++)// loop to find the sum of the square of intigers
	{
		sum = sum + (i*i);// in each iteration it first find square of I and then add it to sum
	}
	cout << " Required output is as follow : " << sum << endl;
	cout << endl;
	system("pause");
	return 0;
}

Output:

The output of the C++ program that finds the sum of the squares of integers from 1 to N.

C++ examples of nested for loop:

Write a C++ program that displays hollow square using for loop.

// C++ program to display hollow square
#include<iostream>
using namespace std;
int main()
{
	int size = 0;
	cout << " Enter the size of pattern : ", cin >> size;
	for (int i = 0; i < size; i++)// loop runs the given number fo times
	{
		for (int j = 0; j < size; j++)// inner loop 
		{
			if (i == 0 || i == size - 1 || j == 0 || j == size - 1)// check to print stars when the condition meets
				cout << "*";
			else
				cout << " ";
		}
		cout << endl;
	}
	system("pause");
	return 0;
}

Output:

The output of displaying the hollow square using for loop.

Write a C++ program that display the list of all prime numbers from 1 to N.

// C++ program to display the list of prime numbers from 1 to N
#include<iostream>
using namespace std;
int main()
{
	int size = 0;
	cout << " Enter the size of pattern : ", cin >> size;
	for (int i = 1; i < size; i++)// loop runs the given number fo times
	{
		int flag = 0;
		for (int j = i-1; j > 1; j--)// inner loop 
		{
			if (i%j == 0)// check to find that the number is prime or not
			{
				flag = 1;
				break;
			}
		}
		if (flag == 0)// this check means that the number is prime
			cout << " " << i;
	}
	cout << endl;
	system("pause");
	return 0;
}

Output:

The output of displaying the list of prime numbers using for loop

Frequently Asked Questions:

The basic definition of for loop is that it executes one or more statements a specified number of times. It is also called a counter control loop.

It is the most flexible loop and is most frequently used by programmers. The for loop is used when you know the fixed number of iterations or the exact number of iterations.

The for loop is the most flexible loop and is most frequently used by programmers.

It specifies the starting value of the counter variable. One or many variables can also be initialized in this part.

To initialize more than one variable, we separate each variable with a comma (,). The initialization part is only executed once.

This part is executed after the initialization step. To run the loop body, it must be true.

If the condition is true, then the body of the for loop is executed, and if the condition is false, execution will directly jump on the statement after the for loop.

If the condition is incorrect in the first attempt, then the loop body will never be executed.

After executing the loop body, the control jumps to this part and performs increments or decrements based on the given scenario

.
We can also remove this part and only use a semicolon instead.


After executing this part again, the condition is evaluated, and if it is true, then the loop body is again performed, and this is continued. The loops terminated immediately the condition becomes false.

When the break statement is used inside the loop, the loop is exited, and the program continues with the statement after the loop.

The main work of the continue statement is that it causes the control to go to the loop’s base condition directly, and then the loop process again continued.


When this statement is executed, the control leaves the current cycle of the loop and starts with the new cycle.

If you find it helpful then don't forget to Share it :

Leave a Comment