Dr. Roger Ianjamasimanana

C do-while loop practical guide with examples

By Dr. Roger Ianjamasimanana

In this lesson, we’ll learn the do-while loop in C. It is a simple control-flow structure that ensures the loop body executes at least once, no matter what. We’ll cover its syntax, how it differs from other loops, and then explore some fun examples—both simple and more complex. At the end of the lesson, we’ll apply our knowledge to a cases in Astronomy.

1. What is a do-while loop?

The do-while loop is a variation of the while loop. The main difference is that a while loop checks its condition before running any code inside the loop, while a do-while loop checks its condition after executing the loop body at least once.

2. Do-while loop syntax

Below is the basic syntax of a do-while loop in C.
do {
    // statements to be executed
} while (condition);

Notice that the condition is checked at the end. That final semicolon (;) is required and easy to forget!

C do-while loop examples

Printing numbers

Let's say we want to print numbers from 1 to 5. With a normal while loop, we need to check a condition before running the body of the code. However, with a do-while loop, the code runs at least once, and then we check if we want to continue.

#include <stdio.h>

int main() {
    int i = 1;

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

    return 0;
}

Even if i started at something greater than 5, say 10, the code inside the do block would still run once before checking the condition. Understand the code below for more details.

#include <stdio.h>

int x = 10;
// C while loop
while (x <= 5) {
    printf("In while\\n"); // This won't run at all since x is not <= 5
}

// do while loop

do {
    printf("In do-while\\n"); // Will run once even if x > 5
} while (x <= 5);

Prompting the users until a condition is met

You might use a do-while loop when you want to prompt a user at least once, and then decide if you should repeat that prompt, i.e., prompting until the user chooses to quit:

Run the code below and see what happens.
#include <stdio.h>

int main() {
    char response;
    do {
        printf("Do you want to continue (y/n)? ");
        scanf(" %c", &response);
    } while (response == 'y' || response == 'Y');
    return 0;
}

Working with arrays

Sometimes we want to iterate through an array. Typically a for loop is best for arrays, but let’s do it with a do-while loop to show that it’s possible:

#include <stdio.h>

int main() {
    int numbers[] = {10, 20, 30, 40, 50};
    int length = sizeof(numbers)/sizeof(numbers[0]);
    int index = 0;

    do {
        printf("Number: %d\\n", numbers[index]);
        index++;
    } while (index < length);

    return 0;
}

This code prints all elements of the array. We ensure the loop runs at least once, so even if the array were empty, the code inside would run once before failing the condition (in practice, you'd want to guard against that).

Edge cases:
  • Empty arrays: if you have an empty array, the do-while will run once. This might print garbage or do something unexpected if not handled. Always validate lengths before using do-while if that’s a concern.
  • Off-by-one errors: it's easy to let the loop run one time too many since the condition is checked at the end. Be careful with your conditions.

Number guessing game

Let’s consider a scenario where we need the user to guess a secret number. We’ll run the loop at least once (ask for a guess), then continue asking until they guess correctly.

#include <stdio.h>

int main() {
    int secret = 42;
    int guess;

    do {
        printf("Guess the secret number: ");
        scanf("%d", &guess);

        if (guess != secret) {
            printf("Nope, try again!\\n");
        }
    } while (guess != secret);

    printf("You got it!\\n");
    return 0;
}

We keep asking until the user finally gets the answer right, and we never miss the initial prompt since the code inside runs at least once.

Practical examples in Astronomy

Using parallax to calculate the distance of stars

In Astronomy, parallax is the apparent shift in the position of a nearby star when observed from two different locations, e.g., the positions of the Earth as it orbits the Sun. Just as your thumb appears to move against a distant background when viewed alternately with each eye, a nearby star appears to shift relative to more distant stars when viewed at different times of the year. This shift, or parallax angle, provides a direct geometric method of determining the star’s distance: the closer the star, the larger its parallax angle. The amount of this shift is measured in arcseconds (where 1 arcsecond is 1/3600 of a degree). The smaller the parallax, the further away the star is.

The distance \( d \) in parsecs is related to the parallax \( p \) in arcseconds by the formula:

\[ d = \frac{1}{p} \]

Once we have the distance in parsecs, we can convert parsecs to light-years. Since 1 parsec ≈ 3.26156 light-years, therefore:

\[ d_{\text{ly}} = d_{\text{pc}} \times 3.26156 \]

Now, let’s use a do-while loop to calculate the distance of many stars using their parallax measurement. Let's say we have a small list of stars with known parallaxes, and we want to calculate their distances in light-years. We’ll do this iteratively, at least once, and after each calculation, we’ll ask if we want to process another star. If the user wants to quit, they can say “n” and we’ll stop.

Sirius is one of the brightest stars in the sky. It has a parallax of about 0.37921 arcseconds, the corresponding distance is:

\[ \begin{align*} d_{\text{pc}} &= \frac{1}{0.37921} \approx 2.6386\ \text{parsecs}\\[6pt] d_{\text{ly}} &= 2.6386 \times 3.26156 \approx 8.6\ \text{light-years} \end{align*} \]

We’ll write a program that uses a do-while loop to process the parallax of multiple stars, compute their distances, and then ask the users if they’d like to continue or not:


#include <stdio.h>

int main() {
    double angleparallax;
    char cont;

    do {
        printf("Enter the star's parallax in arcseconds: ");
        scanf("%lf", \&angleparallax);

        // distance in parsecs
        double d_pc = 1.0 / parallax; 
        // distance in light-years
        double d_ly = d_pc * 3.26156;

        printf("Distance: %.4f parsecs (%.4f light-years)\\n", d_pc, d_ly);

        printf("Do you want to enter another parallax (y/n)? ");
        scanf(" %c", &cont);

    } while (cont == 'y' || cont == 'Y');

    return 0;
}

With Sirius’ parallax of 0.37921 arcseconds, this should give a result close to 8.6 light-years. You can then input other known parallaxes for stars like Procyon or Alpha Centauri, or any star with a known parallax, to calculate their distances.

feature-top
Readers’ comment
feature-top
Log in to add a comment