12. Nested Loops


The printout of the multiplication table was quite unsightly at first, assuming the true shape of a table only after alignment was applied. Whenever a program has to print out some numbers in form of a table, alignment will make the output have a more orderly appearance. The same applies when outputting some numbers in a column below each other.

When writing out a number, like in

cout << 2134;

it will be written out with as many characters as necessary. In this case, four characters will be used: 2,1,3,4.


Manipulator setw sets the minimal number of characters to be used for writing out a succeeding output expression, for example:

cout << setw(6) << 2134;

In this statement the setw manipulator sets the number of characters to a minimum of 6. This will be applied to the succeeding output expression, which has only 4 characters to write out. To make up for the required minimal number of characters, two space characters will be added in the front for padding. The output will look like the one below, with the two space characters in front of the number:


We also say that two space characters have been prepended to the output, as opposed to being appended.

A note: whenever you are using the setw manipulator, you have to add this line to the beginning of the program:

#include <iomanip>

because, just as arrays need the vector library, so does setw need the iomanip library and so the names cin and cout need the iostream library.

Let us examine another example:

cout << setw(5) << 1.11;

It results in one space character for padding:


You might be wondering why there is only one space character when number 1.11 has three digits. The number 1.11 actually has four characters because a decimal point is a character, too. The setw manipulator can also be applied to a string. If you would like, you can test that by yourself.

Note: if an expression following the setw manipulator has to use more characters than the specified minimum, it will be written out in the usual way.

If using a for loop to output some numbers in separate rows with the intention of making the numbers form a column, then the setw manipulator will align the column to the right:

for (int i=1; i<=5; i++)
    cout << setw(3) << i*i << endl;

The output is:


Here is a more drastic example which uses the setw manipulator twice:

for (int i=0; i<11; i++)
    cout << setw(2) << i << " to the fourth power: " 
         << setw(5) << i*i*i*i << endl;

It outputs:

 5 to the fourth power:   625
 6 to the fourth power:  1296
 7 to the fourth power:  2401
 8 to the fourth power:  4096
 9 to the fourth power:  6561
10 to the fourth power: 10000
11 to the fourth power: 14641