while loop is used to repeatedly execute a block of code as long as a specified condition is true. It is used when the number of iterations is not known beforehand. The basic syntax of the
while loop is:
condition is evaluated before each iteration. If the condition is true, the code block inside the loop will execute. If the condition becomes false, the program will exit the loop and continue to the next section of code.
In the example above, the loop will execute as long as
i is less than 5. The code block inside the loop will print the value of
i and then increment
i by 1. This will repeat until
i becomes equal to or greater than 5.
It's important to ensure that the condition inside the
while loop will eventually become false to avoid infinite loops. An infinite loop is a loop that never exits, causing the program to hang or crash. To prevent this, make sure the condition is properly defined and will eventually evaluate to false.
Write a while loop that runs as long as
count is less than 5. Inside the loop, increment the value of
count by 1.
Sign up to start coding
Already have an account?