Sams Teach Yourself C++ in 21 Days

(singke) #1
More on Program Flow 195

7


The important idea here is that by using a nested loop, the inner loop is executed for
each iteration of the outer loop. Thus, the character is printed columnstimes for
each row.

As an aside, many C++ programmers use the letters iand jas counting vari-
ables. This tradition goes all the way back to FORTRAN, in which the letters
i, j, k, l, m, and nwere the only counting variables.
Although this might seem innocuous, readers of your program can become
confused by the purpose of the counter, and might use it improperly. You
can even become confused in a complex program with nested loops. It is
better to indicate the use of the index variable in its name—for instance,
CustomerIndexor InputCounter.

NOTE


Scoping in forLoops ....................................................................................


In the past, variables declared in the forloop were scoped to the outer block. The
American National Standards Institute (ANSI) standard changes this to scope these vari-
ables only to the block of the forloop itself; however, not every compiler supports this
change. You can test your compiler with the following code:
#include <iostream>
int main()
{
// i scoped to the for loop?
for (int i = 0; i<5; i++)
{
std::cout << “i: “ << i << std::endl;
}

i = 7; // should not be in scope!
return 0;
}
If this compiles without complaint, your compiler does not yet support this aspect of the
ANSI standard.
If your compiler complains that iis not yet defined (in the line i=7), your compiler does
support the new standard. You can write code that will compile on either compiler by
declaring ioutside of the loop, as shown here:
#include <iostream>
int main()
{
Free download pdf