Hello, I am new here.. I came here looking for help with some ACPP questions and found a couple. So now, hopefully, I can give back a little, but with a question!
Here is my solution for ACPP Exercises 4-2 through 4-4 (sort of, I havent switched it to use doubles yet).
Anyways, for anyone curious, here are the questions..
4-2. 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 (described above) to manage the output so that the values line up in columns.
4-3. What happens if we rewrite the previous program to allow values up to but not including 1000 but neglect to change the arguments to setw? Rewrite the program to be more robust in the face of changes that allow i to grow without adjusting the setw arguments.
4-4. Now change your squares program to use double values instead of ints. Use manipulators to manage the output so that the values line up in columns.
So, what I eventually did was make the question ask for the max integer to create squares of up to, and the max square to display (4-3?).
My question is, was it overkill to add the checking if the sqrt of 'cutoff' is larger than 'max' than to make 'cutoff' = 'max'.
The reason I decided to do this was to not makiea vector that may be too large, specifically if it wasnt going to be displayed.. make sense?
Anyways, i was stuck on this problem for a while and this is what I finally came up with.. any advice or tips on how I could improve this?? Am i wrong in my assumption of trying to save cycles by not writing to the vector if its not necessary??
Thanks!
#include <iostream>
#include <vector>
#include <iomanip>
#include <math.h>
using namespace std;
int main()
{
int x, max, sqWidth, iWidth, cutoff = 0;
vector<int> squares;
while (cutoff <= 0 ) {
cout << "Enter cutoff square to output: ";
cin >> cutoff;
}
while (max <= 0 ) {
cout << "Enter max number to calcate squares up to: ";
cin >> max;
}
if (sqrt(cutoff) < max) {
max = sqrt(cutoff);
}
for (int i=0; i != max; i++) {
x = (i+1) * (i+1);
squares.push_back(x);
}
iWidth = log10(max)+1;
sqWidth = log10(squares[max-1])+1;
x = 0;
while (squares[x] < cutoff && x != max) {
cout << setw(iWidth) << x+1 << " " << setw(sqWidth) << squares[x] << endl;
x++;
}
for (int i = 0; i < max; i++) {
cout << setw(iWidth) << i+1 << " " << setw(sqWidth) << squares[i] << endl;
i++;
}
}