Loops How to repeat code - for
Key Takeways
For
loops and while
loops perform virtually the same task. The main difference of which to use when really comes down to semantics. Anything you can do with a for
loop, you can do with a while
loop. Anything you can do with a while
loop, you can do with a for
loop. Typically, most people use a while
loop when you aren’t sure when to end the loop.
For Loops
The for
loop looks like the following:
for (int x = 0; x < 10; x+=1) {
// body
}
Take note of the semicolons that break down the 3 parts of the for loop.
int x = 0
: Loop initialization. Here, you define the variable used in the loop. Note, a variable defined here is only defined in the scope of thefor
loop. It’s not available after thefor
loop terminates.x < 10
: Terminal Condition. Like thewhile
andif
, this is the condition you want to stop thefor
loop at. This is checked everytime before the body is executed.x+=1
: Increment. At the bottom of awhile
loop you would increment the loop variable. Thefor
expression formalizes it as a part of the definition so you don’t accidentlly skip it.
The for
above is exactly the same as the while
code below:
int x = 0;
while(x < 10) {
// body
x++;
}
Notice, while both of those code segements are doing the same thing there is 1 major difference. The variable x
goes out of scope in the for
loop, but in the while
, it is available after the while
has terminated.
Using for vs while
One of the most common examples for using a while
loop is when the terminating condition is based on a user input. Take a look at this code:
int Guess() {
std::cout << "Enter a guess: ";
int number;
std::cin >> number;
return number;
}
int main() {
int magic_number = 15;
int guess = Guess();
while (guess != magic_number) {
std::cout << "Try again! ";
guess = Guess();
}
std::cout << "That's it!" << std::endl;
return 0;
}
What is the the maximum number of times the Guess function be called?
You can't actually know! What if the user always enters the exact same guess every single time?With for
loops, its good practice to use them when you know what the start and end conditions are and exactly how many times you will go through the loop.
void PrintBox(int size) {
for (int i=0; i < size; i++) {
char horizontal = ' ';
char vertical = '|';
if (i == 0 || i == size - 1) {
horizontal = '_';
}
if (i == 0) {
vertical = ' ';
}
std::cout << vertical;
for (int j=0; j < size; j++) {
std::cout << horizontal;
}
std::cout << vertical << std::endl;
}
}
Written with while
, the same code is:
void PrintBox(int size) {
int i = 0;
while (i < size) {
char horizontal = ' ';
char vertical = '|';
if (i == 0 || i == size - 1) {
horizontal = '_';
}
if (i == 0) {
vertical = ' ';
}
std::cout << vertical;
int j = 0;
while (j < size) {
std::cout << horizontal;
j++;
}
std::cout << vertical << std::endl;
i++;
}
}
Personally, I find the for
statement to be much better to read and it keeps the scope of both the i
and j
variable to only the for
loop! Do you agree?
Infinite For Loops
Remeber how the following code never terminates?
int counter = 0;
while(true) {
std::cout << counter << std::endl;
counter++;
}
We could write the same code in our for
loop:
for (int counter = 0; ; counter++) {
std::cout << counter << std::endl;
}
While this is valid code, this is NOT good code! If you don’t want a termination condition, consider using the while
code above. Similarly, you can remove any of the 3 parts of the for
loop and the code will still compile as long as you have the 2 semicolons.
Assignment
- Find the bug in the sample codes below and improve the code to the best of your ability.
- For each code assignment in lesson 09, transfrom all of your while loops to for loops. Which work better as for loops? Which work better as while loops? If you think its not possible to write the code as a for loop, explain why.
- Write a calculator which continuously asks the user for numbers and operators until the user finally enters the
=
operator. For example, your code should be able to produce the answer for both5 + 1 =
and also12 / 12 - 4 * 3 - 9 + 89 =
. Think carefully about if this is a for loop or while loop?
Code Samples
Sample 0
// Adds all numbers from low to high inclusively and returns the sum.
int SumOfNumbers(int low, int high) {
int sum;
for (int i = low i < high; i++) {
sum += i;
return sum;
}
}
int main() {
int bottom = 10; // Make this a user input.
int top = 13; // Make this a user input.
std::cout << "10 + 11 + 12 + 13 = " << SumOfnumbers(top, bottom) << std::endl;
}
Sample 1
// Adds all even numbers between low to high inclusively and returns the sum.
// Hint: Even means a number divides evenly by 2!
int SumOfEvenNumbers(int low, int high) {
int sum = 0;
for (int i = low; i > high; i++) {
sum += i;
return sum;
}
}
int main() {
int bottom = 10; // Make this a user input.
int top = 17; // Make this a user input.
std::cout << "10 + 12 + 14 + 16 = " << SumofEvenNumbers(bottom, top) << std::endl;
}
Sample 2
int Factorial(int value) {
int fact = 0;
for (int i = 0; i < value i++) {
fact = i;
}
return fact
}
int main() {
std::cout << "The factorial of 0 is " << Factorial(0) << std::endl;
std::cout << "The factorial of 1 is " << Factorial(1) << std::endl;
std::cout << "The factorial of 2 is " << Factorial(2) << std::endl;
std::cout << "The factorial of 3 is " << Factorial(3) << std::endl;
std::cout << "The factorial of 4 is " << Factorial(4) << std::endl;
std::cout << "The factorial of 5 is " << Factorial(5) << std::endl;
std::cout << "The factorial of 6 is " << Factorial(6) << std::endl;
std::cout << "The factorial of 7 is " << Factorial(7) << std::endl;
std::cout << "The factorial of 8 is " << Factorial(8) << std::endl;
std::cout << "The factorial of 9 is " << Factorial(9) << std::endl;
std::cout << "The factorial of 10 is " << Factorial(10) << std::endl;
std::cout << "The factorial of 11 is " << Factorial(11) << std::endl;
std::cout << "The factorial of 12 is " << Factorial(12) << std::endl;
std::cout << "The factorial of 13 is " << Factorial(13) << std::endl;
std::cout << "The factorial of 14 is " << Factorial(14) << std::endl;
std::cout << "The factorial of 15 is " << Factorial(15) << std::endl;
}
End of Assignment Checklist
- I finished all the assignments.
- I shared my assignments with others.
- I provided feedback for assignments of at least 2 others.
- I addressed the feedback from others and thanked them for the review.