Loop Patterns
Common patterns and use cases for loops
While Loop
In the previous lesson, we got acquainted with loops and learned what a for loop is and how to use it. Today you will look at another loop that is also quite frequently used, and it's called while.
The while loop is another way to repeat actions in a program. It allows you to execute certain commands or a block of code as long as the continuation condition remains true.
While Loop Syntax
Here is the syntax of the while loop:
In the while loop, we have one main component:
- Condition: determines the condition under which the loop will execute.
While Loop Example
Let's look at an example of a while loop that prints numbers from 1 to 5:
In this example, we declare variable i and set its initial value to 1. Then we use the while loop to check the condition i <= 5, and if it's true, we execute the code block inside the loop. Inside the loop, we output the value of i and increment it by 1 using the i++ operator.
Execution Result
If we run this code, it will output numbers from 1 to 5:
Important Note
Notice that unlike the for loop, here we need to control how our condition changes within the loop body. If, for example, we forget to write i++, then i will always equal 1, and our loop will run infinitely.
When to Use While
The while loop is useful when we don't know in advance how many times we need to perform certain actions.
For example, here's how we can use a while loop to input numbers until the user enters a negative number:
In this example, we use the while loop to continue asking the user for numbers until they enter a negative number. At each iteration, we ask the user to enter a number and read it using cin. And so we can continue entering numbers until we enter a negative number. As soon as the user enters a negative number, the loop condition will no longer be met, and the loop will terminate.
Comparison of for and while
Use for loop when:
- The exact number of iterations is known
- You need a counter with a specific step
- You need clear structure: initialization - condition - change
Use while loop when:
- The number of iterations is unknown in advance
- Loop exit depends on complex conditions
- Reading data until a certain condition