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.
How far have you gotten?
i'm still figuring out which loop to use
Use a for loop to wrap your computations.
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...
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.
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 ?
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.
Just to confuse the issue: while( num > 0 ) { sum += num * num; num--; }
Join our real-time social learning platform and learn together with your friends!