Ask your own question, for FREE!
Computer Science 21 Online
OpenStudy (anonymous):

Write a program in C++ that accepts an integer and adds the square of all integers from 1 to the number entered. Make sure to use a loop… For instance if 4 is entered, your program should compute 1 + 2*2 + 3*3 + 4*4 = 30.

OpenStudy (espex):

How far have you gotten?

OpenStudy (anonymous):

i'm still figuring out which loop to use

OpenStudy (espex):

Use a for loop to wrap your computations.

OpenStudy (anonymous):

Thank you, int main() { int num; int sum; int i; sum = 0; cout << "Please enter an integer: " << endl; cin >> num; for (i = 1; i < num; ++i) { sum = sum + i; cout << i << "+"; } cout << num << "=" << sum + num << endl;- return 0; } This is what i've got so far. I'm still stuck on computing the squares...

OpenStudy (espex):

for (i = 1; i <= num; i++) { sum = sum + i*i; } The problem said to add square of all numbers from 1 to the number entered. I would take that to include the number.

OpenStudy (anonymous):

hmm when I enter 4, the result comes out to be 34. That means it adds an extra 4 at the end. How do i get rid of that ?

OpenStudy (espex):

It is because of your last line, cout << num << "=" << sum + num << endl; You are printing "num" plus "sum" after the loop, if you were to cout << sum << endl; you would have the correct answer output to the screen.

OpenStudy (rsmith6559):

Just to confuse the issue: while( num > 0 ) { sum += num * num; num--; }

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!