help fixing for loop factorial code

I'm supposed to write a program that uses one variable int n (which should be positive) and use a for or while loop to compute the following sum :
1^3 + 2^3 + 3^3 + ... + n^3

And then I have to store the sum into int sum and print its value but for some reason, when I test out the code, it just freezes after I enter a value for n.

Any help is appreciated. Thanks!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <math.h>
#include <iomanip>
using namespace std;

int main () {

char c;
int n, i, sum;
while (1) {
cout << "Press q to quit or anything else to continue ";
cin >> c;
cin.ignore ( 256, '\n' );
if (c == 'q' or c == 'Q' ) {
cout << "\n\nUser quits the program.\n\n";
break;
}

cout << "Enter a postive integer n = ";
cin >> n;
sum = 0;
for ( i = 1; 1 <= n; i++ )
sum += pow ( i, 3);
cout << "The sum is" << setprecision(20) << sum << endl;

}

return 0;
}
Last edited on
Line 23: here you make the sum of the second power of n! Change to 3, I suppose, as you said in your introduction! And you can check your output with the correct value from the formula:
S3 = 13 +23+33+...+n3 = n 2 * (n + 1)2 / 4

Succes!

EDIT: In the meantime when I wrote my reply you have modified that line!:)
Last edited on
Hello, thank you for your reply. Yes I did modify that line but it still doesn't work!
Last edited on
Of course it still doesn't work: see line 22: it must be for(i = 1; i <= n; ++i)
Try this...:)
Thank you so much! It worked!
Note: sum is an integer because you add only integers (integer powers of integers) so you don't need of pow and math.h: in this case is simply sum += i * i * i ;
Last edited on
Topic archived. No new replies allowed.