While Loop
The first type of loop we'll look at is the while loop. Imagine you want to print numbers 1-100. That would take us a long time manually. We can make it easier using a while loop:
int number = 1;
while (number <= 100) { // While number is less than or equal to 100
std::cout << number << std::endl; // Print number
number = number + 1; // Increase number by 1
}You can see that the while loop has a similar structure to the if statement.
It works as follows: after the word while comes a condition, and as long as it's true, the code block of the while loop will repeat. As a reminder, a code block is the code in curly braces {} after statements like if, else or while.
Our code will therefore perform the following steps:
- Set the value of variable
numberto 1. - Check if
numberis less than or equal to 100. - If yes, print the value of variable
number, increase its value by 1 and return to step 2. - If no, the program ends.
Note that if we forgot to increase number by 1 in our loop, then number would always be 1 and thus our loop would repeat infinitely. This would cause a program that doesn't respond and would probably terminate itself after a while. This is always undesirable and therefore as programmers we must be careful to avoid this error.
In C++, we can also use a shorthand notation for increasing a value by 1: number++ instead of number = number + 1.
Instructions
Create a variable number of type int with value 10.
Create a while loop that prints numbers from 10 to 20 inclusive using the variable number.
Don't forget to increase the variable number by 1.
Start programming for free
2/9