C do while Loop

Summary: in this tutorial, you will learn about the C do...while loop statement to execute a code block repeatedly based on a checked condition at the end of each iteration.

Introduction to the C do…while loop statement

The do...while loop statement allows you to execute the statement repeatedly until the expression become false:

do { statement; } while (expression);
Code language: C++ (cpp)

How the do...while loop works.

  • First, the statement inside the do...while statement executes.
  • Second, the do...while statement evaluates the expression. If the result is non-zero (or true), it executes the statement again. This cycle is repeated until the expression is zero (or false).

Unlike the while loop statement:

  • The statement inside the do...while is always executes at least once.
  • The expression is checked at the end instead of at the beginning of each iteration.

The following flowchart illustrates how the do...while loop works:

c do while

C do…while loop examples

Let’s take some examples of using the do...while loop statement.

1) Simple C do…while loop statement example

The following example uses the do...while loop statement to display 5 numbers from 0 to 4:

#include <stdio.h> int main() { int n = 0; do { printf("%d ", n); n++; } while (n < 5); return 0; }
Code language: C++ (cpp)

Output:

0 1 2 3 4
Code language: C++ (cpp)

2) Using C do while loop to calculate the sum of input numbers

The following example uses the do...while statement to allow users to enter multiple numbers. If users enter 0, the loop stops and displays the sum of all the entered numbers:

#include <stdio.h> int main() { int n = 0, total = 0; printf("Enter some numbers (0 to stop): "); do { scanf("%d", &n); total += n; } while (n != 0); printf("Sum = %d", total); return 0; }
Code language: C++ (cpp)

Output:

Enter some numbers (0 to stop): 1 2 3 4 5 0 Sum = 15
Code language: plaintext (plaintext)

Summary

  • Use the C do...while loop statement to execute a block of code repeatedly based on a condition that is checked at the end of each iteration.
Was this tutorial helpful ?