@agustfricke
C memory managmentBasics

Do While Loops

Do While Loops in C language

A do while loop in C is a control flow statement that allows code to be executed repeatedly based on a given boolean condition.

Unlike the while loop, the do while loop checks the condition after executing the loop body, so the loop body is always executed at least once.

Syntax

do {
    // Loop Body
} while (condition);

Parts of a do while Loop

Loop Body

  • The block of code that is executed before checking the condition, and then repeatedly as long as the condition is true.

Condition:

  • Checked after each iteration.
  • If true, execute the body again.
  • If false, terminate the loop

Examples

#include <stdio.h>

int main() {
    int i = 0;
    do {
        printf("i = %d\n", i);
        i++;
    } while (i < 5);
    return 0;
}
// Prints:
// i = 0
// i = 1
// i = 2
// i = 3
// i = 4
#include <stdio.h>

int main() {
    int i = 100;
    do {
        printf("i = %d\n", i);
        i++;
    } while (i < 5);
    return 0;
}
// Prints:
// i = 100

Key Points

The do while loop guarantees that the loop body is executed at least once, even if the condition is false initially.

The most common scenario you will see a do-while loop used is in C macros - they let you define a block of code and execute it exactly once in a way that is safe across different compilers, and ensures that the variables created/referenced within the macro do not leak to the surrounding environment.

Assignment

Run the code. Notice that it prints numbers from 5 to 1 in descending order. However, when the starting number is less than the ending number, it doesn't print anything because the condition of the while loop is never true. Modify the print_numbers_reverse function to use a do-while loop so that it always prints the starting number at least once, even if the condition is initially false.

#include <stdio.h>

void print_numbers_reverse(int start, int end) {
  while (start >= end) {
    printf("%d\n", start);
    start--;
  }
}

int main() {
  print_numbers_reverse(3, 4);
  return 0;
}

Solution

#include <stdio.h>

void print_numbers_reverse(int start, int end) {
  while (start >= end) {
    printf("%d\n", start);
    start--;
  }
  do {
    printf("%d\n", start);
    start--;
  } while (start >= end);
}

int main() {
  print_numbers_reverse(3, 4);
  return 0;
}