for Loop Statement in C++

In C++, Loops are sequence of instructions that is continually repeated until the end condition will false . In this article you will learn to create a for loop in C++ programming.

Loop repeats a specific part of the code until end condition is met. There are 3 types of loop but here we are focusing on “For loop”.

 for Loop C++ Syntax

For(initialization; end condition; increment/decrement)

{

Statements//body of the loop;

}

Working of for loop C++

  1. For loop starts with the execution of initialization statement.
  2. Then the condition will check.
  3. If the end condition is false loop will terminate. But if end condition is true the body of the loop will execute and change in counter will update.
  4. Again end condition will check and this process repeats until end condition will false.

Example: for loopC++

#include<iostream>
using namespace std;
void main()
{
for (int i = 1; i < 5; i++)
cout << “Body of the loop” << endl;
system(“pause”);
}

Output:

Body of the loop
Body of the loop
Body of the loop
Body of the loop

 

Here you can see that program start with initialization i=1, checks the  end condition i<5 that is true so it will print the body of the loop then increment in i makes it i=2 then again end  will check & this process will repeat until i=5 and condition i<5 will false.

Example: for loop C++

#include<iostream>
using namespace std;
void main()
{
int a;
int y = 0;
cout << “Enter your value” << endl;
cin >> a;
for (int i = 2; i <= a / 2; i++)
{
if (a % 1 == 0)
{
cout << “Entered no is not prime” << endl;
y++;
break;
}
}
if (y == 0)
{
cout << “Entered no is prime” << endl;
}
system(“pause”);
}

 

Output 1:

Enter your value
123
Entered no is not prime

Output 2:

 

In above program user is asked to enter a positive integer that is stored in variable a. suppose user enter 7.

  1. Initially i=2 end condition i<=a/2 is true then the body of for loop will starts execute & if condition in for loop will check, that is false if statement terminated & no increment in counter y. Due to increment in I, i=3 the end condition i<=a/2 is true When process repeats again & again until the end condition i<=a/2 will false.
  2. When end condition false for loop will terminated & if condition will check as there is no increment in counter “y” so condition y==0 is true then the body of if statement will execute.