Menu
Coddy logo textTech

Do While Loop

Part of the Fundamentals section of Coddy's C# journey — lesson 43 of 69.

The do-while loop is similar to the while loop, but with one key difference: the code block is executed at least once before the condition is checked. This means that the loop's body will always run the first time, regardless of whether the condition is true or false.

Here's the basic structure of a do-while loop:

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

The do keyword marks the beginning of the loop, followed by the code block in curly braces. After the code block, the while keyword introduces the condition. The loop will continue to execute as long as the condition is true.

Here's an example:

int count = 0;
do {
    Console.WriteLine("Count: " + count);
    count++;
} while (count < 5);

In this example, the code inside the do block will execute first, printing "Count: 0" and incrementing count to 1. Then, the condition count < 5 is checked. Since it's true, the loop continues.

This process repeats until count becomes 5, at which point the condition becomes false and the loop terminates.

The output of this code will be:

Count: 0
Count: 1
Count: 2
Count: 3
Count: 4
challenge icon

Challenge

Beginner

Write a C# 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 the code block at least once before checking the condition:

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

Example:

int count = 0;
do {
    Console.WriteLine("Count: " + count);
    count++;
} while (count < 5);

The loop body runs first, then the condition is checked. The loop continues as long as the condition is true.

Try it yourself

using System;

public class Program {
    public static void Main(string[] args) {
        // Initialize variables
        int sum = 0;
        int number = 1;

        // Your code here
        

        // Print the final sum
        Console.WriteLine("Final Sum: " + sum);
    }
}
quiz iconTest yourself

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

All lessons in Fundamentals