Software & Finance





C Programming (Turb C++ Compiler) Loops - display numbers using for loop, while loop and do while loop





The main difference between for loop, while loop, and do while loop is
1.While loop checks for the condition first. so it may not even enter into the loop, if the condition is false.2.do while loop, execute the statements in the loop first before checks for the condition. At least one iteration takes places, even if the condition is false. 3.for loop is similar to while loop except that •initialization statement, usually the counter variable initialization •a statement that will be executed after each and every iteration in the loop, usually counter variable increment or decrement.

The following sample code that can display numbers explains all 3 different loops:


Source Code


#include <stdio.h>

 

int main()

{

 

    int num = 0;

    printf("Using while loop\n");

    while(1)

    {

        num = num + 1;
printf(
"%d\n", num);

        if(num >= 5)

            break;

    }

 

    printf("Using do while loop\n");

 

    num = 0;

    do

    {

        num = num + 1;
        printf(
"%d\n", num);
}
while(num < 5);

 

    printf("Using for loop\n");

 

    for(num = 1; num <= 5; num++)

    {
printf(
"%d\n", num);   
};

 

    return 0;

   

}

Output


Using while loop

1

2

3

4

5

Using do while loop

1

2

3

4

5

Using for loop

1

2

3

4

5

Press any key to continue . . .