Curriculum
The do-while
loop in C programming is a post-tested loop, meaning that the body of the loop is executed at least once before the condition is tested. This feature distinguishes it from the while
and for
loops, where the condition is tested before the loop body is executed. The do-while
loop is particularly useful when you want to ensure that the loop body executes at least once regardless of the condition. This tutorial will guide you through understanding and using do-while
loops in C.
do-while
LoopThe basic syntax of a do-while
loop in C is as follows:
do { // Code to execute } while (condition);
do-while
Loop ExampleLet’s start with a simple example that prints numbers from 1 to 5.
#include <stdio.h> int main() { int counter = 1; do { printf("%dn", counter); counter++; } while (counter <= 5); return 0; }
In this example, the loop prints numbers from 1 to 5. The counter
variable is incremented within the loop, and the condition checks if counter
is less than or equal to 5.
do-while
Loop for User Input Validationdo-while
loops are excellent for scenarios where you need to prompt the user for input at least once and repeat the prompt if the input doesn’t meet certain criteria.
#include <stdio.h> int main() { int number; do { printf("Enter a positive number: "); scanf("%d", &number); } while (number <= 0); printf("You entered: %dn", number); return 0; }
This example repeatedly asks the user for a positive number. It ensures that the prompt is shown at least once and continues until the user enters a positive number.
do-while
LoopAlthough less common, you can create an infinite do-while
loop if the condition always evaluates to true. This might be useful in certain applications, like game loops or server processes that should run indefinitely until manually stopped.
do { // Perform tasks // Break the loop based on some condition to prevent a true infinite loop } while (1);
do-while
Loopsbreak
Statement: Immediately exits the loop, regardless of the loop condition.continue
Statement: Skips the rest of the loop body and proceeds with the next iteration. In do-while
loops, continue
goes to the while
condition check.#include <stdio.h> int main() { int counter = 1; do { if (counter == 3) { counter++; // Ensure increment before continue to avoid infinite loop continue; } if (counter == 5) { break; } printf("%dn", counter); counter++; } while (counter <= 5); return 0; }
The do-while
loop is a powerful control structure in C that ensures the loop body is executed at least once. It is especially useful for situations where an operation needs to be performed before the condition can be evaluated accurately, such as user input validation. Understanding how to effectively use do-while
loops will enhance your ability to write robust and interactive C programs. Remember to manage the condition carefully to avoid unintended infinite loops.