C Do/While Loop

Welcome to The Coding College, where you can master the fundamentals of programming! In this tutorial, we’ll explore the do/while loop in C, a powerful tool for executing tasks at least once before checking conditions.

What is a do/while Loop?

The do/while loop in C ensures that the code block runs at least once, regardless of the condition. This is because the condition is checked after the code execution.

Syntax

do {
    // Code to execute
} while (condition);

Key Points:

  1. Guaranteed Execution: The code block executes at least once.
  2. Condition Check: The loop continues only if the condition evaluates to true.
  3. Semicolon: A semicolon (;) is required at the end of the while statement.

Example 1: Basic do/while Loop

#include <stdio.h>

int main() {
    int i = 1;

    do {
        printf("%d\n", i);
        i++;
    } while (i <= 5);

    return 0;
}

Output:

1  
2  
3  
4  
5  

Example 2: Taking User Input

#include <stdio.h>

int main() {
    int num;

    do {
        printf("Enter a number greater than 0: ");
        scanf("%d", &num);
    } while (num <= 0);

    printf("You entered: %d\n", num);

    return 0;
}

Output:

Enter a number greater than 0: -3  
Enter a number greater than 0: 0  
Enter a number greater than 0: 5  
You entered: 5  

Example 3: Sum of Digits

#include <stdio.h>

int main() {
    int num, sum = 0;

    printf("Enter a number: ");
    scanf("%d", &num);

    do {
        sum += num % 10;  // Add the last digit
        num /= 10;        // Remove the last digit
    } while (num > 0);

    printf("Sum of digits is: %d\n", sum);

    return 0;
}

Output:

Enter a number: 1234  
Sum of digits is: 10  

Use Cases for do/while Loops

  1. Menus: Display options to the user until they choose to exit.
  2. Data Validation: Repeatedly ask for valid input.
  3. Processing Data: Perform an operation at least once before checking conditions.

Difference Between while and do/while

Aspectwhile Loopdo/while Loop
Condition CheckCondition is checked before execution.Condition is checked after execution.
Minimum ExecutionExecutes 0 or more times.Executes at least once.
Use CaseWhen initial condition matters.When at least one execution is required.

Infinite do/while Loops

An infinite loop can occur if the condition never becomes false. Here’s an example:

#include <stdio.h>

int main() {
    int i = 1;

    do {
        printf("%d\n", i);
        // Uncomment the next line to stop the infinite loop
        // i++;
    } while (1);

    return 0;
}

Solution: Ensure the condition or variable changes within the loop.

Advanced Example: Simple Calculator

#include <stdio.h>

int main() {
    int choice, a, b;

    do {
        printf("\nMenu:\n");
        printf("1. Add\n");
        printf("2. Subtract\n");
        printf("3. Multiply\n");
        printf("4. Divide\n");
        printf("5. Exit\n");
        printf("Enter your choice: ");
        scanf("%d", &choice);

        if (choice >= 1 && choice <= 4) {
            printf("Enter two numbers: ");
            scanf("%d %d", &a, &b);
        }

        switch (choice) {
            case 1:
                printf("Result: %d\n", a + b);
                break;
            case 2:
                printf("Result: %d\n", a - b);
                break;
            case 3:
                printf("Result: %d\n", a * b);
                break;
            case 4:
                if (b != 0) {
                    printf("Result: %.2f\n", (float)a / b);
                } else {
                    printf("Division by zero is not allowed.\n");
                }
                break;
            case 5:
                printf("Exiting program.\n");
                break;
            default:
                printf("Invalid choice. Try again.\n");
        }
    } while (choice != 5);

    return 0;
}

Output:

Menu:  
1. Add  
2. Subtract  
3. Multiply  
4. Divide  
5. Exit  
Enter your choice: 1  
Enter two numbers: 5 3  
Result: 8  

Best Practices

  1. Always Validate Input: Use the do/while loop to ensure valid user input.
  2. Avoid Complex Logic: Keep the code block within the loop simple and readable.
  3. Terminate Gracefully: Provide a clear exit condition to prevent infinite loops.

Conclusion

The do/while loop is a valuable construct in C programming when you need to guarantee that a code block executes at least once. By mastering it, you’ll enhance your ability to write dynamic and interactive programs.

Leave a Comment