Home / Programs / do while loop in C Programming language
Programming Example

do while loop in C Programming language

👁 1,189 Views
💻 Practical Program
📘 Step by Step Learning
When the test expression is false (nonzero), the do...while loop is terminated.

Program Code

// 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.

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.