So im stuck on this difficult question. I believe I have most of it done. Just seem to be having a hard time figuring out the sum and average part of the problem and was hoping to get a little help! Anyways here is the question...
"Write a C++ program that prompts the user for a number between 1 and 1776. Output the integers from one to that number. Output 10 numbers per line in columns. Also output the sum (int) and average (float) of the outputted numbers. Output the average to 1 decimal place Validate all input data"
And this is my code so far...
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
cout << setprecision(1)
<< setiosflags(ios::fixed)
<< setiosflags(ios::showpoint);
int N, ctr;
cout << "Input a Number between (1 & 1776): ";
cin >> N;
cout << "\n\n";
while ((N<1)||(N>1776))
{
cout << "\nError! Must be between (1 & 1776): ";
cin >> N;
}
cout << "\n";
for (ctr=1; ctr<=N; ctr++)
{
cout << setw(8) << ctr%1777;
}
cout << "\n\n";
// Sum and Average---------------------------------
system ("pause");
return 0;
}
Everything above the "Sum and Average------" I believe is correct. I just for the life of me cant figure out how to get the sum and average of this question. Any help would be greatly appreciated. Im a little slow with programming. Must have been sitting on this problem for 3 hours stuck on this part alone.
have an int called sum. initialise it to zero before the loop responsible to display each value.
each time to display a new value add this to your sum variable.
also in this loop keep a count of each the number of times the loop fires.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
int sum(0);
int numInts(0);
for( < looping logic for number of ints to display >)
{
// display the number (think you've called it 'ctr'
// add to sum
sum += ctr;
// increment number of ints
numInts++;
}
now, AFTER you loop has run you now have a full sum, and the total number of integers you have displayed, so now:
1 2 3 4 5
float average(0.0);
average = sum/static_cast<float>(numInts);
Don't forgot to apply your formatting when displaying.
just fyi... if and else arent loops. there are only 4 loops in c++: while, do-while, for(;;), and for(:). of course you can create your own "loops" but they still arent loops. for example, emulating a do-while loop:
while ((M>N)||(M<N))
{
cout << "\nError! Must be the same as above! ";
cin >> M;
}
while (ctr < N)
{
cout << N;
sum +=N;
ctr++;
}
while (ctr < N)
{
cout << "Please input the above number again " << ctr + 1<<" ";
cin >> N;
sum +=N;
ctr++;
}
avg = float(sum)/ctr;
i'm not really sure what you're doing anymore, i'm confused.
you only need one loop. and you need to ask your question before that loop, keep displaying and summing inside that loop, and calculate the average after that loop.
Well thank you again for the help mutexe. I didnt realize you said ONE loop haha. I thought I needed two for loops. But that solved it! I was getting confused with your for(< >) up above thought I needed another one.