C – do…while Loop
In a programming language, a loop is useful for running iterative tasks. Using a loop a program can execute code block for multiple times as required.
Mainly there are 3 types of loops available in C programming language. Where while loop is one of them. Below is the list if loop available.
- for loop
- while loop
- do-while loop
do while Loop
A do while loop is similar to while loop. It is exit restricted loops. It means the condition is checked at end of the loop. The do while loop must be run for once.
Syntax:
1 2 3 4 | do { // code block }while (condition); |
do…while Loop Working
- Loop start
- Code block is executed.
- The conditions are checked. If the condition evaluates to false go to step 4. If the condition evaluates to true then go to step 2.
- Exit loop
do while Loop Example
A sample C programme to calculate the sum of user input integers. The program will exit when the user enters 0.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | // C Program to add integers until user enters 0 #include <stdio.h> int main() { int num, sum = 0; do { printf("Enter a number: "); scanf("%lf", &num); sum += num; }while(num != 0); printf("Total = %d",sum); return 0; } |
Output:
Enter a number: 5 Enter a number: 18 Enter a number: 1 Enter a number: 0 Total = 24