For loop in C++

C++ for loop

It is an entry control loop which provides a more concise structure. Basically this loop is used when we know the starting and ending point.

For Statement is further dived into three expression and these three are separated by semicolon (;):

i) initialization expression is used to initialize variables.
ii) test expression is responsible of continuing the loop. If it is true, then the program control flow goes inside the loops and executes the block of statements associated with it .If test expression is false loops terminates.
iii) increment/decrement expression consists of increment or decrement operator This process continues until test condition satisfies.

Syntax of for loop:

for (initialization;condition;increment/decrement)
{
Statements;
}

Program 1.1 :

# include<iostream.h>
void main()
{
int i,sum=0,n;
cout<<”Enter a number”;
cin>>n;
for (i=1;i<=n;i++)
{
sum = sum+I;
}
cout<<sum;
}

Output :

Enter a number 5
15

Nested for loops

Writing one loop control statement within another loop control statement is called nested loops statement.

Syntax of Nested for loops :

for (i=1;i<n;i++)
{
for (j =1;j<I;j++)
{
statement
}
}

Program 1.2 :

# include<iostream.h>
void main ()
{
int n, i, fact,j;
cout<<”Enter a number”;
cin>>n;
for (i = 1; i<=n; i++)
{
fact = 0;
for (j = 1; j<=i; j++)
{
if(i%j == 0)
fact ++;
}
if (fact == 2)
cout<<i<<”\t”;
}
}

Output :
Enter the number 5
2 3 5


2 thoughts on “For loop in C++”

  1. Pingback: Switch Statement in C++ - AskAtul.com

  2. Pingback: While Loop in C++ - AskAtul.com

Leave a Comment

Your email address will not be published. Required fields are marked *