Tuesday, May 12, 2009

For Loop

The “For Loop” is another repetitive control structure, and is used to execute set of instruction repeatedly until the condition become false.

The assignment, increment and decrement and condition checking is done in “For” statement only, where as other control structures are not offered all this features in one statements in one statements only.

Syntax:

for(initial value; condition; increment/ decrement )
{
body of the loop
}

The for loop has three parts

1. Initialize counter is used to initialize counter variable.
2. Test condition is used to test the condition
3. Increment / Decrement counter is used to increment or decrement counter variable

If there is a single statement within the for-loop, the blocking with braces is not necessary, if more than one statement in body of the loop, the statements within the body must be blocked with braces.

Example:

for(i=2;i<=10;i+2)
{
cout <<>
}

cout<<"The above example is : Displayed Even numbers between 1 to 10"



Output will be

2 4 6 8 10

The above example is : Displayed Even numbers between 1 to 10

Nested For Loop

Like if Statement for loop also nested the loop with the loop is called nested loop.
To understand how nested loops works, look at the program given below.

Syntax:


for(initial value; condition; increment/ decrement )
{
for(initial value; condition; increment/ decrement )
{
for(initial value; condition; increment/ decrement )
{
body of the loop1
}
body of the loop2
}
body of the loop3
}

Example:

class testforloop
{
int i,j,row;
public:
void display();

}
void testforloop::display()
{
cout<<"Enter the Row Value";
cin>> row;
for(i=1;i<=row;i++)
{
for(j=1;j<=i;j++)
{
cout<<>
}
cout<<"\n";
}

}
void main()
{
clrscr();
testforloop obj;
obj.display();
getch();
}


The output will be


Enter the Row Value
5
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5

No comments:

Post a Comment