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
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:
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
Write a do...while loop that executes the following steps:
- Increment
iby 1. - Add
itosum. - Continue the loop as long as
iis less than or equal to 10.
Sign up to start coding
Already have an account?
Sign In
