Menu
Coddy logo textTech

Do While Loop

Part of the Fundamentals section of Coddy's C journey — lesson 39 of 63.

The do-while loop is similar to the while loop, but with one important difference: the code block is executed at least once, and then the condition is checked.

Create a do-while loop:

do {
    // Code to be executed
} while (condition);

Let's create a program that asks the user to enter a positive number:

int number;

do {
    printf("Please enter a positive number: ");
    scanf("%d", &number);
} while (number <= 0);

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

In this example:

  1. The code inside the do block runs first, asking for input
  2. After getting the input, the condition number <= 0 is checked
  1. If the condition is true (the number is not positive), the loop repeats
  2. If the condition is false (the number is positive), the loop stops

The do-while loop is perfect for situations where you need to execute the code at least once, regardless of the condition.

challenge icon

Challenge

Easy

Write a program that uses a do-while loop to do the following:

  1. Initialize a variable sum to 0.
  2. Initialize a variable number to 1.
  3. In each iteration, add number to sum.
  4. Increment number by 2 in each iteration (i.e., 1, 3, 5, ...).
  5. print number and sum:
    Sum is: [The sum value]
    Num is: [The number value]
  6. Continue the loop as long as number is less than or equal to 50.
  7. Print the final value of sum after the loop finishes: Final Sum: [The final sum value]

Cheat sheet

The do-while loop executes code at least once, then checks the condition:

do {
    // Code to be executed
} while (condition);

Example asking for positive input:

int number;

do {
    printf("Please enter a positive number: ");
    scanf("%d", &number);
} while (number <= 0);

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

The do-while loop is ideal when you need to execute code at least once before checking the condition.

Try it yourself

#include <stdio.h>

int main() {
    // Initialize variables
    int sum = 0;
    int number = 1;

    // Your code here
    

    // Print the final sum
    printf("Final Sum: %d\n", sum);
    return 0;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals