Loops in C

Loops let you repeat a block of code until a certain condition is reached.Each repetition is called an iteration.Suppose your loop runs n times you say that the loop iterated n times.


The statements executed inside the loop is called the loop body.

for loop


Syntax

for(initialization ; condition ; after)
{
    loop body
} 
initialization : Variables are initialized.

condition : condition is checked before executing loop body.

after :  executed once each time after the loop body has executed.


Sequence of execution


 



Key points


  • Suppose loop body consists of only 1 statement,then no need of braces.
  • initialization,condition and after all are optional.

Without initialization
for(;condition;after)
{
    loop body
}

Without condition
for(initialization;;after)
{ 
    loop body
}
This would be an infinite loop until you don't have a break statement in the loop body to transfer control out of the loop.

Without after
for(initialization;condition;)
{ 
    loop body
}
  • You can have multiple initializations seperated by comma,multiple after seperated by comma.To introduce multiple conditions use &&,|| operators.


Example


Lets see a program to calculate sum of numbers (0 - 10).
#include<stdio.h>

int main()
{
    int i,sum;

    for(i = 0 ; i <= 10 ; i++)
        sum = sum + i;

    printf("%d",sum);

    return 0;
}



while loop


Syntax

while(condition)
{
    loop body
}
condition is compulsory.



Sequence of execution




Key point


Loop body executes only when the condition evaluates to true.If the condition is false very first time it is checked,the loop body will not execute even once.



do while loop


Syntax

  do
  {
       loop body

  }while(condition);


Sequence of execution





Key point


If the condition is false the very first time it is checked,the while loop will not execute even once but do-while loop would execute once.
Below program will make this distinction clear.
#include<stdio.h>

int main()
{
    int i=2;

    while(i==1)
    {
        printf("%d ",i);
        i--;
    }   


    return 0;
}
This would not print anything.

#include<stdio.h>

int main()
{
    int i=2;

    do
    {
        printf("%d ",i);
        i--;

    }while(i==1);

    return 0;
}
O/P 2 1



No comments:

Post a Comment