Lesson 12 - Loops
Loops - Overview
There are two main types of loops in C++, while loops and for loops. Loops run all the code in the loop from top to bottom repeatedly for the specifications of the loop.
While Loops
While loops will continue to loop through the code inside the brackets from top to bottom while as long as the condition in the parentheses is true. For example,
Since the loop’s condition is always “true”, this loop would continue to run the code on the inside of the brackets. In other words, x will continuously add by 1 and y will continuously be equal to the previous value of y plus x.
Now, suppose we change the condition aka the contents inside the parentheses to the following:
The while loop will only occur whenever x < 10. Since every time the loop runs, x increases by one, the loop would repeat 10 times because x would be less than 10 for 10 iterations of the loop.
Let’s walk through each iteration of the while loop.
_______________________________
X starts as 0 and y = 2.
Iteration 1:
X = 0 + 1 = 1.
Y = 1 + 2 = 3.
Iteration 2:
X = 1 + 1 = 2
Y = 3 + 2 = 5
Iteration 3:
X = 2 + 1 = 3
Y = 5 + 3 = 8
Iteration 4:
X = 3 + 1 = 4
Y = 8 + 4 = 12
…
Until Iteration 10:
X = 10
Y = 57
_______________________________
This scenario of continuously looping the function a certain number of times can also be done using a for loop.
For Loops
A for loop is structured like the following:
This loop would run 10 times and would result with count having a final value of 10. Now, each section of the for loop declaration will be broken down.
For Loops - Breakdown of Declaration
The purple section declares the counter and its initial value. The standard is to declare the for loop counter as “i”.
The second section, the italicized i < 10, sets the condition that needs to be true for the loop to repeat. That is to say, once i reaches 10, the loops will stop repeating and it will continue down the program to any code you have after it.
The final section, which is yellow, explains what the code should do at the end of a repetition of each iteration of the loop. In this case it’s saying add 1 to i at the end of every iteration of the loop, that is to say, after it adds one to count, it adds 1 to i.