Introduction
In the previous tutorial, we learned how to make decisions based on the data that the user typed in and we wrote a guess my number game. The code for the game was very repetitive and could greatly be reduced and generalized by using loops. In this tutorial, we will rewrite the game using for loops to make the code much more concise.
Code
A for loop takes three pieces of information: the value that you wish to start at, a comparison to decide how long to keep going, and a statement to execute between each loop. So, let’s start out with an example, here’s how to print all of the numbers between 1 and 10:
for (int num = 1; num <= 10; num++)
{
cout << num << endl;
}
The first part of the for loop (int num = 1) declares a new variable and sets its value to 1, which is the first number that we want to print. At this point, the computer checks the value of num against the comparison to decide whether or not to continue (num <= 10). Since num is one, which is less than ten, the statement within the loop executes, so the value is printed to the screen. When all of the statements in the curly braces have executed, then the last part of the for loop is executed (num++). This adds one to the value of num. This produces the same result as num = num + 1, but since this operation is so common there is a short hand version of it. After this, then we are back to seeing whether or not to continue running the loop (num <= 10). Since num is two, which is less than ten, we continue executing the statements in the loop. Then we add one to num again, perform the check again, and then execute the statements in the loop, until the check fails and then we are done with the for loop.
At this point, you might be thinking, why do I need a for loop, I could print out the numbers between 1 and 10 doing something like this:
cout << 1 << endl;
cout << 2 << endl;
cout << 3 << endl;
cout << 4 << endl;
cout << 5 << endl;
cout << 6 << endl;
cout << 7 << endl;
cout << 8 << endl;
cout << 9 << endl;
cout << 10 << endl;
While this would work, it isn’t very flexible. What if you wanted to prompt the user for a value and then count from 1 up to the given value? The previous example would have to look something like this:
int max = 0;
cin >> max;
if (1 <= max) { cout << 1 << endl; }
if (2 <= max) { cout << 2 << endl; }
if (3 <= max) { cout << 3 << endl; }
if (4 <= max) { cout << 4 << endl; }
…
This would continue on for a long time, since the user could type in a large number like 1,234,567. However, with a for loop, the following code could handle numbers as large as an integer can store:
int max = 0;
cin >> max;
for (int num = 1; num <= max; num++)
{
cout << num << endl;
}
So, you could either write a million plus lines of repetitive code to handle the user input or you could use a for loop and only write a handful.
So, let’s rewrite the guess my number game using a for loop. Here’s the code:
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
int main()
{
// Randomly generate a secret number
srand((unsigned int) time(NULL));
int num = (rand() % 10) + 1;
int num_guesses = 3;
// Print out number first (used for debugging purposes, no cheating!)
//cout << num << endl;
// Game intro
cout << "I'm thinking of a secret number, can you guess it?" << endl;
int guess = 0;
for (int i = 0; i < num_guesses; i++)
{
// Read in guess
cout << "Guess? ";
cin >> guess;
// Guess logic
if (guess == num)
{
// Tell the user that they guessed correctly
// and then exit the program
cout << "Correct, my secret number was " << num << endl;
return 0;
}
else
{
if (num < guess)
{
cout << "My secret number is less than " << guess << endl;
}
else
{
cout << "The secret number is greater than " << guess << endl;
}
}
}
// If the loop ends, that means that the user is out of guesses
// and never guessed the correct number
cout << "Sorry, the correct number was " << num << endl;
return 0;
}
See how the use of the for loop replaces the repetitive logic from the previous tutorial? Before we had to do 3 different checks to see if the guess matched the secret number. Here, we only write the code once and loop over it multiple times.
Loops are very, very powerful tools and I encourage you to play around with them because their effective usage is critical to writing good code. Trust me, I can’t over emphasize their importance. An exercise that really helped me learn looping was to try to prompt the user for a number and create a triangle of asterisks based on it that looked like this, if the user typed in 3:
*
**
***
A slightly more advanced exercise is to create a pyramid that looks something like this, if the user typed in 3:
*
***
*****
Give those a try and see what you come up with. One possible solution is attached below.
Summary
In this tutorial, we learned how to make our code more concise and general through the use of for loops. We rewrote our guess my number game from the previous tutorial using for loops to remove the repetitive code.
Did you ever try typing in a number larger than 10 or less than 1? How about typing in fractional number or even a letter? In the next tutorial, we will improve the game to make it more robust in handling user input by introducing while loops.
If you have any questions or comments about what was covered here, post them to the comments. I watch them closely and will respond and try to help you out.