- What a loop is and why we use loops in C programming
- How the do-while loop works with real examples
- Where to use do-while loops in real applications
- How to write a menu driven program using do-while
- Complete program examples with explanations
Introduction
In this tutorial, we will learn what a do-while loop is in C programming.
Before learning the do-while loop, it is important to understand what a loop is. Once the concept of loops is clear, learning the do-while loop becomes much easier.
What is a Loop?
A loop in C is used when we want to execute the same block of code repeatedly. Instead of writing the same statements multiple times, we use a loop to automate repetition. The loop continues to execute as long as a specified condition remains true.
💡 Think of it like this: Imagine you need to print your name 10 times. Without a loop, you would write the printf() statement 10 times.
With a loop, you write it just once, and the loop repeats it 10 times.
What is a do-while Loop in C?
A do-while loop is a looping statement that executes the statements inside the loop at least once, even if the condition is false.
The statements inside the do block execute first. After execution, the condition is evaluated. If the condition is true, the loop executes again. Otherwise, the loop terminates.
Since the condition is checked after executing the loop body, the do-while loop is also known as a post-tested loop.
Where is a do-while Loop Used?
The do-while loop is mainly used when a block of code must execute at least once before checking a condition.
It is commonly used in:
- ATM menu-driven applications
- Online shopping applications
- Spell checking tools
- Text editors such as Notepad, MS Word, and Sublime Text
- Menu-based software where the user decides whether to continue or exit
Advantages of Using do-while Loop in C Programming
1. Simple and easy to understand — The syntax is beginner-friendly
2. Ensures the loop body executes at least once — Perfect for menu-driven applications
3. Repeats execution automatically — While the condition remains true
4. Useful for interactive and menu-driven applications
Disadvantages of Using do-while Loop in C Programming
1. Infinite loop risk: If the loop condition always remains true, an infinite loop occurs
2. Incorrect exit conditions — May produce unexpected results
3. Care must be taken — While writing the condition to avoid logical errors
Flowchart of do-while Loop
The flowchart of a do-while loop works as follows:
Step-by-step explanation:
- Control enters the
doblock - The statements inside the loop execute without checking any condition
- After execution, the condition is evaluated
- If the condition is true, control returns to the beginning of the loop
- The process repeats until the condition becomes false
- Once the condition is false, execution continues with the statements after the loop
Syntax of do-while Loop in C
The do-while loop consists of four important parts:
/* Declaration or Initialization */
int i = 1;
do {
/* Loop Body (Instructions) */
printf("Value: %d\n", i);
/* Update Expression */
i++;
} while (i <= 5); /* Condition */
Let's break down each part:
🔹 Declaration or Initialization: Variables used inside the loop are declared and initialized before the loop starts. Proper initialization ensures correct execution.
🔹 Loop Body (Instructions): The loop body contains the statements that perform the required task. These statements execute every time the loop runs.
🔹 Update Expression: The update expression modifies the loop control variable, usually by incrementing or decrementing it. It determines how many times the loop executes.
🔹 Condition: The condition is evaluated after the loop body executes. If it evaluates to true, the loop continues; otherwise, it terminates.
⚠️ Note: A semicolon ; is mandatory after the while(condition) statement. Forgetting it will cause a syntax error.
Menu-Driven Program Using do-while Loop
The do-while loop is commonly used in menu-driven applications.
In a typical menu-driven program:
- Variables are declared before the loop begins
- The menu options are displayed
- The user selects an option
- The corresponding operation is executed
- The user is asked whether they want to continue
- If the user chooses to continue, the menu is displayed again
- Otherwise, the program exits
This approach allows users to perform multiple operations without restarting the program.
Here's a complete example of an ATM-style menu:
#include <stdio.h>
#include <stdlib.h>
int main() {
char choice;
int option;
do {
// Display menu options
printf("\n=== ATM MENU ===\n");
printf("1. Withdrawal\n");
printf("2. Balance Enquiry\n");
printf("3. Deposit\n");
printf("4. Transfer Money\n");
printf("5. Change PIN\n");
printf("6. Exit\n");
printf("Enter your choice: ");
scanf("%d", &option);
// Process user choice
switch(option) {
case 1:
printf("✅ You selected: Withdrawal\n");
break;
case 2:
printf("✅ You selected: Balance Enquiry\n");
break;
case 3:
printf("✅ You selected: Deposit\n");
break;
case 4:
printf("✅ You selected: Transfer Money\n");
break;
case 5:
printf("✅ You selected: Change PIN\n");
break;
case 6:
printf("Thank you for using our ATM!\n");
exit(0);
break;
default:
printf("❌ Invalid choice! Please select 1-6.\n");
}
// Ask if user wants to continue
printf("\nDo you want to continue? (y/n): ");
scanf(" %c", &choice);
} while(choice == 'y' || choice == 'Y');
printf("Thank you for visiting!\n");
return 0;
}
Sample Output:
=== ATM MENU === 1. Withdrawal 2. Balance Enquiry 3. Deposit 4. Transfer Money 5. Change PIN 6. Exit Enter your choice: 2 ✅ You selected: Balance Enquiry Do you want to continue? (y/n): y === ATM MENU === 1. Withdrawal 2. Balance Enquiry 3. Deposit 4. Transfer Money 5. Change PIN 6. Exit Enter your choice: 6 Thank you for using our ATM!
Explanation:
- We declare two variables:
option(int) andchoice(char) - The
do-whileloop starts and shows the menu - User enters a choice (like 2 for Balance Enquiry)
- The
switchstatement runs the matching case - After the switch, we ask if the user wants to continue
- If user enters 'y' or 'Y', the loop runs again
- If user enters 'n' or 'N', the loop ends
Program to Find Total and Average of First N Natural Numbers Using do-while Loop
This program calculates both the total and the average of the first N natural numbers.
Working of the Program:
- Required variables are declared and initialized
- The program accepts the value of N from the user
- The do-while loop starts execution
- During each iteration, the current value is added to the total
- The loop control variable is updated
- The loop continues until all numbers from 1 to N have been processed
- After the loop finishes, the average is calculated by dividing the total by N
- Finally, the total and average are displayed
#include <stdio.h>
int main() {
int n, i = 1;
int sum = 0;
float average;
// Ask user for input
printf("Enter the value of n: ");
scanf("%d", &n);
// Calculate sum using do-while loop
do {
sum = sum + i; // Add current number to sum
i++; // Move to next number
} while (i <= n);
// Calculate average
average = (float)sum / n;
// Display results
printf("Sum of first %d numbers: %d\n", n, sum);
printf("Average of first %d numbers: %.2f\n", n, average);
return 0;
}
Sample Output:
Enter the value of n: 10 Sum of first 10 numbers: 55 Average of first 10 numbers: 5.50
Explanation:
- We declare variables:
n(user input),i = 1(counter),sum = 0, andaverage - User enters the value of n (like 10)
- The do-while loop starts and adds
itosum - Then
i++increases the counter by 1 - The loop runs until
ibecomes greater thann - After the loop, we calculate the average
- The
(float)converts sum to float for accurate division - Finally, we display the sum and average
💻 Practice Exercise
Challenge: Write a program that asks the user to enter numbers. The program should keep asking until the user enters 0. Then display the sum of all entered numbers.
🔍 Click to Show Solution
#include <stdio.h>
int main() {
int num, sum = 0;
printf("Enter numbers (0 to stop):\n");
do {
scanf("%d", &num);
sum = sum + num;
} while (num != 0);
printf("Sum of all numbers: %d\n", sum);
return 0;
}
📝 Summary
- A do-while loop always executes at least once
- The loop condition is checked after executing the loop body
- It is also known as a post-tested loop
- It is especially useful in menu-driven and interactive applications
- Proper initialization, update expressions, and loop conditions are necessary to avoid infinite loops and logical errors
Frequently Asked Questions About do-while Loop in C
1. What is the difference between while loop and do-while loop?
The main difference is that a while loop checks the condition first – if it's false, the loop never runs. A do-while loop runs the code first, then checks the condition – so it always runs at least once.
2. When should I use a do-while loop?
Use a do-while loop when you need the code to run at least once, like in menu driven programs, user input validation, or games where you need to show options before asking the user to continue.
3. Can a do-while loop run forever?
Yes! If the condition is always true, the loop will run forever. This is called an infinite loop. For example, if you write while(1) or while(i < 10) but never update i, the loop will never end.
4. Is the semicolon after while required in do-while?
Yes! The semicolon ; after while(condition) is required. Without it, the compiler will show a syntax error. This is one of the most common mistakes beginners make.
5. Can I use break and continue in do-while loop?
Yes, you can use both break and continue in a do-while loop. break exits the loop immediately. continue skips the rest of the current iteration and jumps to the condition check.
💡 Tip: When writing a do-while loop, always make sure the update expression changes the variable used in the condition. Otherwise, you might create an infinite loop.