About C 'do...while' Loop
In C program, the 'do...while' loop is a control flow statement that is used to execute a block of code for once. Then it evaluates the 'while' condition and repeatedly executes block of code as long as the specified condition of 'while' is true.
The condition is evaluated after each iteration. If it is true, the code block inside the 'do' loop will be executed. If the condition is false, the loop will stop to execute the block of code.
It's important to ensure that the condition in a 'do...while' loop will eventually become false. Otherwise, the loop will continue indefinitely. Infinite loops can cause a program to become unresponsive or consume excessive CPU resources.
Syntax of 'while' loop
xxxxxxxxxx
do {
//block of code statements
//updating condition
} while (condition);
-
do
: The 'do' keyword begins the 'do...while' loop. -
//block of code statements
: The line will be replaced by a block of code which will be executed repeatedly. The block of code needs to be placed inside curly braces '{}'. -
//updating condition
: The line will be replaced by a block of code to update the variable of 'while' condition. It is important to ensure that some change has been made to the variable of loop condition. Otherwise, the loop may run indefinitely and the program becomes unresponsive. -
while (condition)
: In the line, 'while' keyword indicates that the loop should continue as long as the condition is true. Condition will be replaced by user defined condition.
Create a 'do...while' loop statement
A 'do...while' loop statement has been created in the following example that will print number from 1 to 5:
Example of 'do...while' loop
xxxxxxxxxx
#include <stdio.h>
int main() {
int i = 1; //initializes i variable
do { //loop begins
printf("%d\n", i); //prints value of i variable
i++; //increments i variable value by 1
}
while (i <= 5); //checking condition
return 0;
}
Output of the above example
1 2 3 4 5
Explanation of code:
-
int i = 1;
: The line declares an integer variable named 'i' and assigns value 1. It will be used in the 'while' condition. -
do
: The 'do' keyword starts the 'do...while' loop. -
printf("%d\n", i);
: The line prints the value of 'i' variable. '%d' is the format specifier for integer data and '\n' creates a newline. -
i++;
: The line increments the value of the 'i' variable by 1. -
while (i <= 5)
: In the line, 'while' keyword is followed by the condition 'i <= 5'. The loop condition is checked once the statement inside the loop has been executed. As long as the value of 'i' is less than or equal to 5, the statements inside the loop will be executed repeatedly. When the value of the 'i' variable becomes 6, the 'while' condition will be false and the loop will terminate.