Menu
CoddyTech

Do While Loop

Part of the Fundamentals section of Coddy's Java journey. Lesson 44 of 73.

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 {
    System.out.println("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 Java 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. At the end of each iteration, after adding and incrementing, print sum and then number:
    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. The line below your code prints the final value of sum after the loop: Final Sum: [The final sum value]

Try it yourself

        // Initialize variables
        int sum = 0;
        int number = 1;

        // Your code here
        

quiz iconTest yourself

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

All lessons in Fundamentals

Practice on your own: Online Java compiler