While and do while in C: solved exercises step by step
If you are looking for while and do while exercises in C, this post gives solved examples with practical loop scenarios.
Core difference:
whilechecks the condition before running,do whileruns at least once and then checks the condition.
Problem statement
Solve these 4 mini exercises:
- read a positive number using
do while, - count digits of a number using
while, - sum values until
0is entered usingwhile, - build a simple menu loop using
do while.
C solution
#include <stdio.h>
int read_positive(void) {
int n;
do {
printf("Enter a positive number: ");
scanf("%d", &n);
} while (n <= 0);
return n;
}
int count_digits(int n) {
int count = 0;
if (n == 0) return 1;
if (n < 0) n = -n;
while (n > 0) {
n /= 10;
count++;
}
return count;
}
int sum_until_zero(void) {
int sum = 0;
int value;
printf("Enter values (0 to stop):\n");
while (1) {
scanf("%d", &value);
if (value == 0) break;
sum += value;
}
return sum;
}
void simple_menu(void) {
int option;
do {
printf("\nMenu:\n");
printf("1) Say hello\n");
printf("2) Show info\n");
printf("0) Exit\n");
printf("Option: ");
scanf("%d", &option);
if (option == 1) {
printf("Hello, still practicing C.\n");
} else if (option == 2) {
printf("Do while guarantees at least one execution.\n");
}
} while (option != 0);
}
int main(void) {
int positive = read_positive();
printf("Valid number: %d\n", positive);
printf("Digits of %d: %d\n", positive, count_digits(positive));
int sum = sum_until_zero();
printf("Total sum: %d\n", sum);
simple_menu();
return 0;
}Expected output
Enter a positive number: -3
Enter a positive number: 145
Valid number: 145
Digits of 145: 3
Enter values (0 to stop):
5
10
-2
0
Total sum: 13
Menu:
1) Say hello
2) Show info
0) Exit
...Common mistakes
- Using
whilewhen you need the block to run at least once. - Forgetting to update the loop control variable.
- Skipping input validation in console loops.
- Using
breakin the wrong place and breaking expected flow.
Practical use
while and do while are common in:
- console input validation,
- interactive menus,
- repeated reads until a sentinel value appears.
These structures are foundational in user-driven C programs.
Recommended next exercise
- For loop in C: solved exercises with accumulators and counters
- If else in C: solved exercises with nested conditions
- Arrays and vectors in C: solved exercises
- All C exercises
Guided practice and next step
If you want a complete path with progressive difficulty:
FAQ
When should I use while vs do while in C?
Use while when the condition may fail immediately. Use do while when you must execute at least once.
How do I avoid infinite loops?
Update control variables every iteration and make sure the exit condition is reachable.
Is menu practice with do while useful?
Yes. It combines control flow, user input, and validation, which are core C skills.