Do while loop
Posted by Superadmin on October 26 2024 03:49:39

Do while loop

The do while loop is a post-condition loop. It guarantees to execute its body at least once, regardless of the loop condition. The reason for this is that in a post-condition loop the condition is checked after the body of the loop.


post-condition do while loop flow chart

The do while loop in C

The syntax of the do while loop in C is:

    do
    {
        ...
        Statements in the loop body
        ...
    }while(condition);

    For beginners it is a common mistake to forget the semicolon after the condition.

The loop will repeat the execution of the body while the condition is true. Once it becomes false, no more iterations are done and the program continues with the next statement, following the loop.

Examples

Calculating n! (n factorial)

Factorial is the product of all integer numbers from 1 to n, where n is the factorial we want to calculate. In mathematics it is written with an exclamation mark – n!
So..  4! = 1*2*3*4 = 24

Here is the code to calculate 5! using a do while loop:

#include <stdio.h>
int main()
{
    int factorial = 1;
    int number = 5;
    do
    {
        factorial *= number;
        number--;
    }while(number > 0);
    printf("%d\n", factorial);
}

Organizing a menu

Another common example is a menu. We can print a menu and take different actions, depending on the user input. Here is a typical implementation:

int main()
{
    int menuChoice = 0;
    do
    {
        printMenu();
        scanf("%d", &menuChoice);
        handleMenuChoice(menuChoice);
    }while(menuChoice != 0);

    return 0;
}

void printMenu()
{
    printf("========== MENU ==========\n");
    printf("Input a number to take action:\n");
    printf("1. Input a number to calculate its factorial\n");
    printf("0. Exit\n");
    printf("========== MENU ==========\n");
    printf("Menu choice = ");
}

void handleMenuChoice(int menuChoice)
{
    int number;
    unsigned long factorial;
    if(menuChoice == 1)
    {
        printf("number = ");
        scanf("%d", &number);
        factorial = calculateFactorial(number);
        printf("%d! = %lu \n", number, factorial);
    }
}

The demo shows a menu and calculates n!
Here is how it works:

In this example I wanted to keep the code short. For that reason you see only 2 options in the menu. Also, normally you will handle the user choice with a switch, rather than an if.

Now you can implement the functions printMenu() and handleMenuChoice() the way you like. For instance you can ask the user to input a sequence of numbers and find the greatest of them.

Examples download

The source code for the above examples is available for download from GitHub and as a direct download as a zip file: do-while-loop.zip