Loop Construct – do while
The do-while loop is a control flow statement in programming languages that allows you to repeatedly execute a block of code while a certain condition is true, similar to the while loop. However, the key difference is that the do-while loop executes the block of code at least once, even if the condition is false.
The syntax of the do-while loop varies slightly depending on the programming language, but the basic structure is as follows:
do {
// code to execute at least once
} while (condition);
In this syntax, the block of code inside the do
statement is executed first, and then the condition
is evaluated. If the condition
is true, the block of code is executed again, and the process repeats until the condition
is false. If the condition
is false initially, the block of code inside the do
statement is still executed once.
Here is an example of a do-while loop in C that reads input from the user until they enter a non-negative number:
int num;
do {
printf("Enter a non-negative number: ");
scanf("%d", &num);
} while (num < 0);
In this example, the block of code inside the do
statement prompts the user to enter a non-negative number and reads the input from the user using the scanf
function. The while
statement checks if the number entered by the user is less than 0, and if it is, the loop executes again and prompts the user to enter another number. This process repeats until the user enters a non-negative number, at which point the loop terminates.
Apply for PHP Certification!
https://www.vskills.in/certification/certified-php-developer