While and do while in C: solved exercises

  3 minutes

If you are looking for while and do while exercises in C, this post gives solved examples with practical loop scenarios.

Core difference:

  • while checks the condition before running,
  • do while runs at least once and then checks the condition.

Solve these 4 mini exercises:

  1. read a positive number using do while,
  2. count digits of a number using while,
  3. sum values until 0 is entered using while,
  4. build a simple menu loop using do while.
#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;
}
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
...
  • Using while when you need the block to run at least once.
  • Forgetting to update the loop control variable.
  • Skipping input validation in console loops.
  • Using break in the wrong place and breaking expected flow.

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.

If you want a complete path with progressive difficulty:

Use while when the condition may fail immediately. Use do while when you must execute at least once.

Update control variables every iteration and make sure the exit condition is reachable.

Yes. It combines control flow, user input, and validation, which are core C skills.