In this article do while loop in c we give the information about do while it may be necessary to execute the main part of the loop before testing it. Such situations can be controlled with the help of Do…while statement.
do while loop loop in C:
The while loop construct, which we discussed in the previous article, tests the condition before the loop is executed. Therefore, if the conditions are not met on the first attempt, the main part of the loop cannot be executed at all. In some cases it may be necessary to execute the main part of the loop before testing it. Such situations can be controlled with the help of Do…while statement.
do while flowchart:
Body of the loop
Upon reaching the do statement, the program proceeds to evaluate the main part of the first loop. At the end of the loop, the test-position is evaluated in the while statement. If the condition is true, the program continues to evaluate the main part of the loop once again. This process continues as long as the situation is true. When the condition is false, the loop will end and control will be moved to the statement that appears immediately after the statement.
Since the test-position at the bottom of the loop is being evaluated, the do construction provides an exit-controlled loop and therefore the main part of the loop is always executed at least once.
// Program to add numbers until user enters zero
int number, sum = 0;
// loop body is executed at least once
printf(“Enter a number: “);
sum = sum + number;
while(number != 0);
printf(“Sum = %d”,sum);
Enter a number: 5
Sum = 16
// Program to show first ten natural numbers.