//Write a program to calculate the squares of int
values up to 100. The program should write two columns: The first lists the value; the second contains the square of that value. Use setw
to manage the output so that the values line up in columns.
Hint
Determine the widest outputs for both columns.
Solution
The widest number that is being squared is 100, which is three digits. 100 squared is 10000, which is 5 digits, so the solution belows sets a width of 4 prior to sending the base to output and set a width of 6 prior to sending the result to output. Setting the widths one larger than the values contained will preserve at least one space to the left of each value.
#include <iomanip>
#include <iostream>
using std::cout;
using std::endl;
using std::setw;
int main()
{
for (int i = 1; i < 101; ++i)
{
cout << setw(4) << i << setw(6) << (i * i) << endl;
}
}