do while loop in C Programming language

C Programming Language / Loop control in C Language

1129

Program:

// Program to add numbers until user enters zero

#include <stdio.h>
int main()
{
    double number, sum = 0;

    // loop body is executed at least once
    do
    {
        printf("Enter a number: ");
        scanf("%lf", &number);
        sum += number;
    }
    while(number != 0.0);

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

    return 0;
}

Output:

Enter a number: 1.5
Enter a number: 2.6
Enter a number: 2.3
Enter a number: 5.6
Enter a number: 1.5
Enter a number: 0
Sum = 13.50

Explanation:

The code block (loop body) inside the braces is executed once.

Then, the test expression is evaluated. If the test expression is true, the loop body is executed again. This process goes on until the test expression is evaluated to 0 (false).

When the test expression is false (nonzero), the do...while loop is terminated.


This Particular section is dedicated to Programs only. If you want learn more about C Programming Language. Then you can visit below links to get more depth on this subject.