DMarlon Studio

Lesson 8 · 8 of 20

while and do-while loops · C

Repeat code in C while a condition holds with while, and with do-while when the block must run at least once.

C · while and do-while loops in DMarlon Studio: the example's code and its output in the terminal

`while` repeats its block as long as the condition is true. The coffee starts at 90 degrees and loses 10% every turn (coffee *= 0.9); once it drops below 60, coffee > 60.0 no longer holds and the loop ends. minute counts the turns.

Something inside the loop must change so that the condition eventually becomes false. In the countdown it is seconds--; forget it and the loop never ends (an infinite loop).

`do-while` checks the condition at the end, so the block always runs at least once. To count the digits of 2026, each turn adds one digit and divides the number by 10 (integer division): 202, 20, 2 and 0. With do-while, the number 0 also counts as one digit; a plain while would give zero digits.

Notice the semicolon that closes } while (number > 0);: in do-while it is required.

Code · main.c

#include <stdio.h>int main(void) {    // while repeats its block as long as the condition is true.    double coffee = 90.0;    int minute = 0;    while (coffee > 60.0) {        minute++;        coffee *= 0.9;  // it loses 10% of its heat every minute        printf("Minute %d: %.1f degrees\n", minute, coffee);    }    printf("Ready to drink after %d minutes.\n", minute);    // A countdown.    int seconds = 5;    while (seconds > 0) {        printf("%d... ", seconds);        seconds--;    }    printf("Lift-off!\n");    // do-while checks at the end, so the block runs at least once.    // Counting digits: even 0 has one digit.    int number = 2026, digits = 0;    do {        digits++;        number /= 10;    } while (number > 0);    printf("2026 has %d digits.\n", digits);    return 0;}

Output · cc main.c -o main && ./main

Minute 1: 81.0 degrees
Minute 2: 72.9 degrees
Minute 3: 65.6 degrees
Minute 4: 59.0 degrees
Ready to drink after 4 minutes.
5... 4... 3... 2... 1... Lift-off!
2026 has 4 digits.

Key points

  • while (condition) checks before every turn.
  • Something in the loop must move it towards the end.
  • do { ... } while (condition); runs at least once.
  • do-while ends with a semicolon.

Exercise

Change number to 0 and check that the result is one digit. Then use a while loop to find how many years it takes 1000 euros at 5% a year to go above 1500.