< Previous | Contents | Next >
The Counter program counts forward, backward, and by fives. It even counts out a grid with rows and columns. It accomplishes all of this through the use of for loops. Figure 3.1 shows the program in action.
Figure 3.1
for loops do all of the counting, while a pair of nested for loops displays the grid.
You can download the code for this program from the Course Technology website (www.courseptr.com/downloads). The program is in the Chapter 3 folder; the filename is counter.cpp.
Using for Loops 83
// Counter
// Demonstrates for loops #include <iostream> using namespace std;
int main()
{
cout << "Counting forward:\n"; for (int i = 0; i < 10; ++i)
{
cout << i << " ";
}
cout << "\n\nCounting backward:\n"; for (int i = 9; i >= 0; --i)
{
cout << i << " ";
}
cout << "\n\nCounting by fives:\n"; for (int i = 0; i <= 50; i += 5)
{
cout << i << " ";
}
cout << "\n\nCounting with null statements:\n"; int count = 0;
for ( ; count < 10; )
{
cout << count << " ";
++count;
}
cout << "\n\nCounting with nested for loops:\n"; const int ROWS = 5;
const int COLUMNS = 3;
for (int i = 0; i < ROWS; ++i)
{
84 Chapter 3 n For Loops, Strings, and Arrays: Word Jumble
for (int j = 0; j < COLUMNS; ++j)
{
cout << i << "," << j << " ";
}
cout << endl;
}
return 0;
}
If you’re using an older compiler that doesn’t fully implement the current C++ standard, when you try to compile this program, you might get an error that says something like: error: ’i’ : redefinition; multiple initialization.
If you must use your old compiler, you should declare any for loop counter variables just once for all for loops in a scope. I cover the topic of scopes in Chapter 5, “Functions: Mad Lib.”