Difference Between | While and Do-While Loop | C-Program

While Loop :-

The while loop evaluates the test expression, if the test expression is true (nonzero), codes inside the body of while loop is executed. 
The test expression is evaluated again. The process goes on until the test expression is false. When the test expression is false, the while loop is terminated.                                                                                                                                                                                             

Example :

#include<stdio.h>
 
void main()
{
    int number;

    long long factorial;

    printf("Enter an integer: ");

    scanf("%d",&number);

    factorial = 1;

    while (number > 0) // loop terminates when number is less than or equal to 0
    {
        factorial *= number;  // factorial = factorial*number;
        --number;
    }

    printf("Factorial= %lld", factorial);
}

OUTPUT :- 

Enter an integer: 5
Factorial = 120

Do While Loop:-

do while loop flowchart in C programming
The do..while loop is similar to the while loop with one important difference. 
The body of do...while loop is executed once, before checking the test expression. 
Hence, the do while loop is executed at least once.

Example :-


#include<stdio.h> 

void main()

{
     double number, sum = 0;

     do     // body of loop is executed at least once 

     {
         printf("Enter a number: ");

         scanf("%lf", &number);

         sum += number;

     } while(number != 0.0);

     printf("Sum = %.2lf",sum);

}

OUTPUT :- 

Enter a number: 5.2

Enter a number: -6.9
Enter a number: 1.02
Enter a number: 9.9
Enter a number: 0

Sum = 9.22

Comments

Popular posts from this blog

TOP 10 PROGRAMMING LANGAUAGES COMMING 2021 | ARTICLE

Write a C-program to swap two number:

Print Fibonacci Series using Recursion | C program :