Code highlights logo

Learn

Loops

Do...While Statements

The do...while statement is similar to the while loop, but with one key difference - the code block is executed first, and then the condition is checked. This means that the code block will always execute at least once, even if the condition is initially false.

Syntax of the do...while Statement

1do {
2 // code block to be executed
3} while (condition);

Key Features

  • The code block is executed before checking the condition.
  • The condition is evaluated after executing the code block.
  • If the condition is true, the code block will be executed again.
  • If the condition is false, the loop will terminate and the program will continue to the next section of code after the loop.

Example Usage

Let's consider an example where we want to prompt the user for a number and keep prompting them until they enter a positive number. We can use the do...while statement to achieve this:

1let num;
2do {
3 num = parseInt(prompt("Enter a positive number:"));
4} while (num <= 0);
5console.log("You entered: " + num);

In this example, the code block prompts the user for a number and assigns it to the variable num. The loop will continue executing and prompting the user until they enter a positive number (i.e. the condition num <= 0 becomes false).


Instructions

1.

Write a do...while loop that executes the following steps:

  • Increment i by 1.
  • Add i to sum.
  • Continue the loop as long as i is less than or equal to 10.

Sign up to start coding

Already have an account?

Sign In

Course content