ACPP Exercise 4-2

Joined
Jul 2, 2008
Messages
1
Reaction score
0
I'm having trouble with Exercise 4-2 in Accelerated C++. The exercise
is "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."

Something similar is listed below, But the columns should be able to
line up no matter what the value of max is. The way it is now it goes
to around 30,000 to 40,000 then the columns lose their lining, so I
figured this obviously isn't the way to do it.

#include <iomanip>
#include <iostream>

int main()
{
int cwidth = 0;
int i2 = 0;
int max = 100;
for (int i = 0; i <= max; i++)
{
i2 = i*i
if (i2 < 10) {
cwidth = 9;
} else if (i2 >=10 && i2 < 1000) {
cwidth = 10;
} else if (i2 >= 1000) {
cwidth = 11;
}
std::cout << i << std::setw(cwidth) << i2 << std::endl;
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,813
Latest member
lawrwtwinkle111

Latest Threads

Top