while loops
Loops allow us to repeatedly execute a piece of code.
This is usefull when a program that requires repetition of tasks, which is a major reason for why programs are useful in the first place.
while (condition)
{
// Your code here.
}
The while statement has a similar syntax to the if statement.
Similar to the if statement, the attached scope will only execute if the condition is true. However, once the scope has run, the code execution jumps back and re-evaluate the condition . If the condition is still true, it will execute the attached code before jumping back yet again. This process continues until the condition becomes false, allowing code execution to continue.
If the condition in the while loop is false in the beginning the code inside will never execute.
You can use an integer to keep track of how many times the loop has run. To do this, you declare an integer before the loop and add 1 to it every time the loop runs.
You can use this to make a condition that makes the loop run a certain amount of times.
int i = 0;
// Loop will run 5 times
while (i < 5) {
std::cout << i << "\n";
i+=1;
}
0
1
2
3
4
This loop will execute until i reaches 5, which is the first time that i<5 is no longer true.
Infinite loops (intentional, and unintentional)
Programs that run indefinitely make use of a loop around the main process where the condition is always true.
Infinite loops generally look something like this.
while (true)
{
// Code that runs indefinitely
}
Not all infinite loops are intentional. Sometimes a loop becomes infinite due to a logic error.
int i = 0;
while (i < 5)
{
std::cout << i << "\n";
i--; // Decrements instead of incrementing
}
i will never hold a value above 5, leading to an inifinte loop.
An iteration loop like the one above would never end, because the condition will always be true.
Be wary of your loop designs so that you don't break the program.
Variables In loops
When you declare a variable inside a loop it is re-created every cycle of the loop. This means that any value it held in a previous cycle is lost. To keep track of things between loop cycles, you have to declare your variables before the loop.
#include <iostream>
int main()
{
int i = 0;
while (i < 10)
{
// Declared inside the loop
int factorial = 1;
factorial *= i + 1;
std::cout << "The factorial of " <<i+1 << " is " << factorial << "\n";
i++;
}
}
The factorial of 1 is 1
The factorial of 2 is 2
The factorial of 3 is 3
...
The factorial of 9 is 9
The factorial of 10 is 10
This code incorrectly calculates the factorial of each number.
The factorial variable is initialized as 1 for every cycle, so it always equals i + 1.
By moving the factorial declaration out of the loop we stop re-declaring the variable every loop.
#include <iostream>
int main()
{
int i = 0;
int factorial = 1;
while (i < 10)
{
factorial *= i + 1;
std::cout << "The factorial of " <<i+1 << " is " << factorial << "\n";
i++;
}
}
Do while loops
do
{
// Your code
}
while (condition);
Note the semicolon behind while (condition)
Do-while-loops are similar to while-loops.
However, the condition is at the end of the loop to show that the code executes before the evaluation.
The do-while loop runs the attatched code block before checking the condition to see if it should run again.
It will always execute once, even if the condition is literally false.
do-while loops are commonly used to gather information and validate it in the conditional statement.
This will loop the code and re-gather data until the data is valid.
Here's a calculator program that divides the first input by the second.
We ensure that the user's second input isn't 0 by asking for the input again if they input 0.
std::cout << "Please input the number you want to divide by\n";
int input2;
do
{
std::cin >> input2;
if (input2 == 0)
std::cout << "The divisor cannot be 0! Please input your number again.\n";
} while (input2 == 0);
for loops
This code is used to keep track of how many times a loop has run:
int i = 0; // tracking variable with starting value
while (i< 5) // conditional comparison with the tracking variable
{
// Your code
i+=1; // some transformation of the tracking variable
}
In addition to the while-loop; it consists of an initating statement (int i = 0;), a looping condition (i<5), and a counter incrementer (i+=1).
For-loops place all 3 of these statements in the same place, separated by semicolons.
for (int i = 0; i < 5; i+=1)
{
// Your code here
}
This code does the same as the while loop used above.
The first statement, int i = 0; is the initialization statement.
It will run once at the start of the loop. You declare a tracking variable here and give it a starting value.
The second statement, i < 5, is the conditional statement.
It determines if the loop should run or if code execution should continue after the loop.
The third statement, i+=1 is the update statement.
It runs each time the loop code executes. You change the tracking variable here in some way, generally by incrementing it.
The only functional difference between these two pieces of code is that i is placed inside the for-loop scope.
This means that you cannot access i outside the scope of the for-loop.
The statements inside a for-loop are not mandatory.
for (;;)
This is a valid for-loop.
Nothing happens at the start of the loop, and nothing happens at the end of each loop cycle.
The middle statement evaluates as true by default if left empty.
This means that the code for (;;) is an infinite loop.
However, using while (true) makes it more evident that the loop is intentional.
The modulus operator
The modulus operator % gets the remainder of an integer division. int(10)/int(3) gives us 3 because the decimals are ignored.
Once we remove all of the 3's from 10 (3*3=9), we are left with 1 (the remainder).
That means that 10%3 is 1.
There are 3 whole 3's and nothing remaining in 9, so 9%3 is 0.
8%4==0
11%4==3
If the left side is smaller than the right, like 3%5, it evaluates as the left number.
3%5 == 3
If we want a piece of code in a loop to execute once every 3 loops, we can use the modulus operator with an if-statement.
In the loop for (int i = 0; i < 10; i++) - i % 3 == 0 will be true once every 3 cycles.
i%2==1 checks if i is an odd number.
i%2==0 checks if i is an even number.
Both are true for every other loop when i increments by 1 each cycle.
Break & Continue
The break keyword in a switch statement exits the statement and continues code execution after the statement.
This behavior carries over to loops.
Using break; ends the loop and continues code execution after the loop.
The program below sums up user-input numbers and returns the total for every input.
We want the program to exit if the user inputs the value 0.
To do this, we include an if-statement to break out of the loop if the input is 0.
#include <iostream>
int main()
{
std::cout << "input the number you want to sum, 0 to exit";
int sum = 0;
while (true)
{
int input;
std::cin >> input;
if (input == 0)
break;
sum += input;
}
std::cout << "Your final sum was " << sum;
}
The continue keyword skips the rest of the loop code.
The code execution jumps straight to evaluating the loop condition again. You can use this to jump straight to the next cycle of a loop.
The update statement in a for-loop runs when you use continue. Using continue in a normal while loop will make it skip the update statement if it comes after.
This program loops numbers from 0-100, except the ones divisible by 4.
We use the modulus operator(%) to check if i is divisible by 4, the skip the cycle with continue;.
for (int i = 0; i < 100; i++)
{
if (i % 4 == 0)
continue;
// Here goes the code to handle the number.
std::cout << i << " - ";
}
1 - 2 - 3 - 5 - 6 - 7 - 9 - 10 - 11 - 13 ... 90 - 91 - 93 - 94 - 95 - 97 - 98 - 99 -
Nested loops
A nested loop is a loop within another loop.
This is used when a task needs multiple dimensions.
As an example; let's create a program that builds a pyramid based on user input in a console application using nested loops.
#
###
#####
#######
The pyramid has a height based on the user's input.
Each line consists of a specific number of spaces and hash symbols (#) as building blocks.
We can't go back to a previous line, so our output interface determines that we have to handle each line one at a time.
The first step will then be getting the height input from the user, and setting up the outer loop to cycle each line.
#include <iostream>
int main()
{
int pyramid_height;
std::cin >> pyramid_height;
for (int i = 0; i < pyramid_height; i+=1)
{
// Here goes the building blocks for each line
// Go to the next line
std::cout << '\n';
}
}
For each line, we want x amount of spaces before y amount of building blocks before we go to the next line.
We'll declare some variables and find the formula relative to the variable i since that is our tracking variable.
Based on the illustration of the pyramid above it's clear that the formula for blocks used is int block_count = 1+i*2;.
The formula for spaces is int space_count = pyramid_height - i - 1;.
Using these variables we can make loops to output space_count spaces and block_count blocks before going to the next line.
for (int i = 0; i < pyramid_height; i++)
{
int space_count = pyramid_height - i - 1;
for (int j = 0; j < space_count; j++)
std::cout << “ ”;
int block_count = 1+i*2;
for (int j = 0; j < block_count ; j++)
std::cout << “#”;
std::cout << “\n”;
}
When we run this function, it will first ask the user for input.
Let's say that the user inputs 5.
Then, it will start a for-loop with a counting variable i, which starts at 0.
On each loop, it will use i to calculate how many spaces there should be, and how many blocks there should be. Then it will use 2 for-loops to print the spaces and blocks however many times match the variables.
Calculator Upgrade
Let's use this new knowledge to upgrade the calculator.
Let's add the ability to do another calulation without having to restart the program.
We want to run the loop once before checking if the user wants to run the loop again, because of this the do-while loop is a good option.
We'll start by copying the things we have in place for our last program.
#include <iostream>
int main() {
std::cout << "Input the operation you want to use, then by the 2 numbers you want to use, seperated by spaces.\n "
<<"operations:\n" << "1: Addition\n" << "2: Subtraction \n" << "3: Multiplication \n" << "4: Division\n";
int operation;
float input1, input2;
switch (operation) {
case 1:
std::cout << input1 << " + " << input2 << " = " << input1 + input2 << "\n";
break;
case 2:
std::cout << input1 << " - " << input2 << " = " << input1 - input2 << "\n";
break;
case 3:
std::cout << input1 << " * " << input2 << " = " << input1 * input2 << "\n";
break;
case 4:
if (input2 == 0) {
std::cout << "Division by zero is not allowed.\n";
break;
}
std::cout << input1 << " / " << input2 << " = " << input1 / input2 << "\n";
break;
default:
std::cout << "Operation type is not supported";
break;
}
}
We can wrap a do-while loop around all of our code.
At the end of our code we can ask the user if they want to do another calculation.
The answer will be used in the do-while condition.
#include <iostream>
int main() {
int another_calculation;
do {
std::cout << "Input the operation you want to use, then by the 2 numbers you want to use, seperated by spaces.\n "
<< "operations:\n" << "1: Addition\n" << "2: Subtraction \n" << "3: Multiplication \n" << "4: Division\n";
int operation;
float input1, input2;
switch (operation) {
case 1:
std::cout << input1 << " + " << input2 << " = " << input1 + input2 << "\n";
break;
case 2:
std::cout << input1 << " - " << input2 << " = " << input1 - input2 << "\n";
break;
case 3:
std::cout << input1 << " * " << input2 << " = " << input1 * input2 << "\n";
break;
case 4:
if (input2 == 0) {
std::cout << "Division by zero is not allowed.\n";
break;
}
std::cout << input1 << " / " << input2 << " = " << input1 / input2 << "\n";
break;
default:
std::cout << "Operation type is not supported";
break;
}
std::cout << "Do you want to perform another calculation? (1=yes, 0=no): ";
std::cin >> another_calculation;
} while (another_calculation == 1);
}
Now the program will continue running if the user wishes to perform another calculation.
GOOD JOB!
You finished a chapter.
This would be a good time to practice what you've just learned.
Last ChapterPracticeNext Chapter