A While Loop is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. The While Loop can be thought of as a repeating if statement.
In the expression, we have to test the condition. If the condition evaluates to true, then we will execute the body of the loop and go to update the expression. After executing the loop body, this expression increments/decrements the loop variable by some value. Otherwise, we will exit from the While Loop.
How does While Loop execute?
- Control falls into the While Loop.
- The flow jumps to the condition
- The condition is tested.
- If it is true, the flow goes into the body.
- If it is false, the flow goes outside the loop
- The statements inside the body of the loop get executed.
- The update takes place.
- Control flows back to Step 2.
One more thing, which we have already read in the previous article about advanced conditional statements, is the break statement. It ends the loop immediately when it is encountered. The break statement is usually used with a conditional statement inside the loop.
Both While and For Loops repeat a block of code. We use For Loops when we preliminary know the number of iterations. If we don’t know when the exit condition will be met, we use While Loops.
- While Loops
- While or For Loop?
- Operator Break
- Infinite Loops
Watch the video and solve the problems. To better understand the material, do the coding exercises and implement the knowledge you acquired. Writing code is the only way to master the skill of code.
Submit your code in the SoftUni Judge System: