I'm supposed to write a program that uses one variable int n (which should be positive) and use a for or whileloop 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.
#include <iostream>
#include <math.h>
#include <iomanip>
usingnamespace 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;
}
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:
S_{3 }= 1^{3} +2^{3}+3^{3}+...+n^{3} = n ^{2} * (n + 1)^{2} / 4
Succes!
EDIT: In the meantime when I wrote my reply you have modified that line!:)
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 ;