Tuesday, February 3, 2015

All Loop At a glance

First we see for loop:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int a = 5;
    int i;

    for (i=1;i<=5;i++)
    {
        scanf  ("%d",&a);
        printf ("%d\n\n",a);

    }


    return 0;
}


Output:
1
1

3
3

5
5

88
88

0
0

After printing 5 times the loop will be terminated as per condition (i<=5)

We may writer the for loop like this way :

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int a = 5;
    int i= 1;

    for (;i<=5;)
    {
        scanf  ("%d",&a);
        printf ("%d\n\n",a);
        i++;

    }


    return 0;
}

Output:

1
1

3
3

5
5

88
88

0
0
 

Note: Important issue, if we remove the condition then the program me will never stop.

While LOOP:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int a = 5;
    int i= 1;

    while(i<=5)
    {
        scanf  ("%d",&a);
        printf ("%d\n\n",a);
        i++;

    }

    return 0;
}

         
Output:
                 
1
1

3
3

5
5

88
88

0
0

When use what type of loop:

For loop: when we know how many times the loop run.
while loop: when we do not know how many times the loop run.

while loop example:
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int a = 5;
    int i= 1;
    scanf ("%d",&a);

    while(a!= 0)
    {
        printf ("%d\n\n",a);
        scanf("%d",&a);

    }


    return 0;
}

 Output:

This programme will not terminate untill you type 0 as per the  condition (a!= 0)

Another advance way to write this while loop:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int a = 5;
    int i= 1;

    while(scanf ("%d",&a)&& a!= 0)
    {
        printf ("%d\n\n",a);
        scanf("%d",&a);

    }


    return 0;
}


Output: Same until type 0 , the programme will not terminate.

No comments:

Post a Comment