The do while loop in C programming language checks its condition at the bottom of the loop. The block of code is before the condition, so code will be executed at lease one time. A do while loop is similar to a while loop, except the code block of do-while loop will execute at least once.
The do-while loop is a versatile control flow structure in C programming that allows you to repeatedly execute a block of code as long as a specified condition is true. It shares similarities with the while loop, but with a key distinction: the do-while loop guarantees that the code block is executed at least once, regardless of the initial condition.
Syntax of do while Loop
/* code to be executed */
statement(s);
}while(condition);
- condition
Condition expression is evaluated after code block of do-while loop. It is a boolean expression which decides whether to execute loop's code again or terminate do-while loop. if condition expression evaluates to true, the code block inside do-while loop gets executed otherwise it will terminate do-while loop and control goes to the next statement after the do-while loop. - statement(s)
do while loop can contain any number of statements including zero statements. All statements inside do-while loop will gets executed atleast once. - There is semicolon in the end of while(condition); in do-while loop.
- First do while loop execute the codes inside body. Then, the condition expression is tested. If the value of condition expression is true then code block of do while loop(statements inside {} braces) will be executed again otherwise the loop will be terminated.
- Do While loop iteration continues unless condition expression becomes false or while look gets terminated using break statement.
C Program to find sum of integers from 1 to N using do while Loop
#include <stdio.h> int main(){ /* * Using do while loop to find the sum * of all integers from 1 to N. */ int N, counter, sum=0; printf("Enter a positive number\n"); scanf("%d", &N); /* Initializing loop control variable before do while loop */ counter = 1; do { sum+= counter; /* Incrementing loop control variable */ counter++; }while(counter <= N); printf("Sum of Integers from 1 to %d = %d", N, sum); return(0); }Above program find sum of all integers from 1 to N, using do-while loop.
Output
Enter a positive number 10 Sum of Integers from 1 to 10 = 55
Applications of the Do-While Loop in C
- Menu-Driven Programs : The do-while loop is commonly used in menu-driven programs where the user is presented with a menu of options, and the program executes based on the user's choice. This ensures that the menu is displayed at least once, allowing the user to make a selection.
#include <stdio.h> int main() { int choice; do { // Display menu printf("1. Option 1\n"); printf("2. Option 2\n"); printf("3. Exit\n"); // Get user choice printf("Enter your choice: "); scanf("%d", &choice); // Perform actions based on user choice switch (choice) { case 1: printf("Executing Option 1\n"); break; case 2: printf("Executing Option 2\n"); break; case 3: printf("Exiting the program\n"); break; default: printf("Invalid choice. Please try again.\n"); } } while (choice != 3); return 0; }
In this example, the do-while loop ensures that the menu is displayed at least once, and the user is prompted to make a choice. - Input Validation : The do-while loop is useful for input validation scenarios, ensuring that the user enters valid data. This is particularly beneficial when the input needs to meet specific criteria.
#include <stdio.h> int main() { int age; do { // Get user input for age (validating that age is positive) printf("Enter your age: "); scanf("%d", &age); if (age <= 0) { printf("Invalid age. Please enter a positive value.\n"); } } while (age <= 0); printf("Your age is: %d\n", age); return 0; }
In this example, the do-while loop ensures that the user enters a positive age value. - Password Authentication : The do-while loop is often used in password authentication systems, where users are prompted to enter a password until a correct one is provided.
#include <stdio.h> #include <string.h> int main() { char password[10]; const char correctPassword[] = "secure123"; do { // Get user input for password printf("Enter the password: "); scanf("%s", password); // Check if the entered password is correct if (strcmp(password, correctPassword) != 0) { printf("Incorrect password. Try again.\n"); } } while (strcmp(password, correctPassword) != 0); printf("Authentication successful!\n"); return 0; }
In this example, the do-while loop continues until the user enters the correct password.
- The condition expression in do while loop is a boolean expression. It must evaluate to true or false value(In C, all non-zero and non-null values are considered as true and zero and null value is considered as false).
- Unlike for loop, initialization statements, condition expression and update statements are on different line.
- Opening and Closing braces are not required for single statement inside do while loop code block.
For Example:
do
statement;
while(condition);
- We can also use infinite do while loops which will never terminate. You should add terminating condition using break statement in order to terminate infinite do while loop.
For Example:
do {
if(....){
break;
}
} while(1);
Potential Pitfalls of the Do-While Loop
- Incorrect Loop Initialization : Incorrectly initializing loop variables can result in unexpected behavior. Ensure that loop variables are initialized with appropriate values.
// Incorrect initialization int i; do { // Code } while (i < 5);
In this example, i is not initialized before use, leading to undefined behavior. - Modifying Loop Variables Within the Loop Body : Modifying loop variables within the loop body can lead to unexpected results and errors. Avoid changing loop variables unless it aligns with the loop's logic.
// Avoid int i = 0; do { // Code that modifies i } while (i < 5);
In this example, modifying i within the loop body can lead to unpredictable behavior and should be avoided. - Infinite Loops : Infinite loops can occur if the loop termination condition is not properly defined or if loop variables are not updated correctly within the loop body.
// Infinite loop int i = 0; do { // Code } while (i < 5);
In this example, if there's no update to i inside the loop, it will never reach the termination condition, resulting in an infinite loop.
Conclusion
The do-while loop is an indispensable instrument in C programming, providing a versatile method for executing code repeatedly. It is distinguished from other loop structures by the assurance that at least one execution of the code block will occur. One can develop dependable and user-centric programs by acquiring proficiency in the do-while loop's syntax, comprehending its practical implementations, and being mindful of established conventions.
Develop your proficiency in C programming by applying the do-while loop in a variety of circumstances, conducting experiments with different loop conditions, and maintaining an eye on the updates of loop variables. Developing an in-depth awareness of the do-while loop will enhance your ability to compose code that is both dependable and efficient.