Thursday, October 18, 2012

C++ Loops

The purpose of loops is to repeat the execution of codes a number of time while the condition is still true.

while loop:
 The form:

while(condition)
{
    statement(s);
}

do while loop:
The form:

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

The difference of the do while is that, it will first execute the statements first then check if the condition is still true then if it is still true, it will iterate or loop (executes the statement(s) again).

for loop:
The form:
for (initialization; condition; increment/decrement)
{
    statement(s);
}


Examples:

int x=10;
int i = 0;
while (i<x)
{
    cout<<i<<": Hi"<<endl;
    i++;
}

do
{
    cout<<i<<": Hi"<<endl;   
    i++;
}while(i<x)

for (int a=0;a<10;a++)
{
     cout<<a<<": Hi"<<endl;
}

Try it and see the difference.

1 comment: