- The smallest possible output. But it's ugly with unaligned columns.
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
- To make the multiplication table look nice, the I/O manipulator
setw()
can be used to set the minimum width of the converted form of the number.
#include <iomanip>
. . .
cout << setw(4) << n;
This will right-align the value of n
in a field of four spaces.
The output would look like this.
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
- Add column and row headers as well as separating lines to make it look like the following.
Several additional loops are required to print the column header and horizontal
separating lines. Don't try to make all of these additions at once.
For example, first add the row header and vertical bars. Get that running
then print the separating lines. Lastly add the column header. The order of
these additions isn't important in this case, but to work on small increments
in the program makes development to more easily.
1 2 3 4 5
+-----+-----+-----+-----+-----+
1 | 1 | 2 | 3 | 4 | 5 |
+-----+-----+-----+-----+-----+
2 | 2 | 4 | 6 | 8 | 10 |
+-----+-----+-----+-----+-----+
3 | 3 | 6 | 9 | 12 | 15 |
+-----+-----+-----+-----+-----+
4 | 4 | 8 | 12 | 16 | 20 |
+-----+-----+-----+-----+-----+
5 | 5 | 10 | 15 | 20 | 25 |
+-----+-----+-----+-----+-----+