Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

must compile this program requires reading an integer n which defines the number

ID: 3635747 • Letter: M

Question

must compile
this program requires reading an integer n which defines the number of iterations of a loop. The effect of the loop is to count from 1 to n, adding up the sum of the numbers from 1 to n, the sum of the squares of the numbers and the sum of the cubes of the numbers.

loop variant

int i, n, i_squared, i_cubed, sum_i, sum_i_squared, sum_i_cubed;

cin >> n;
assert ( n > 0 && n <= 100 );

sum_i = 0;
// sum_i is the sum of the first 0 values for i

sum_i_squared = 0;
// sum_i_squared is the sum of the first 0 values for i*i


sum_i_cubed = 0;
// sum_i_cubed is the sum of the first 0 values for i*i*i

// The first iteration of the loop will use value 1 for i
// The last iteration of the loop will use value n for i
for ( i = 1; i <= n; i++ ) {
...
// i_squared = i * i
// i_cubed = i * i * i

// sum_i = sum of 1 + 2 + ... + i
// sum_i_squared = sum of 1 + 4 + 9 + ... + i*i
// sum_i_cubed = sum of 1 + 8 + 27 + ... + i*i*i

// Print the values of i, i_squared, i_cubed, sum_i, sum_i_squared and sum_i_cubed
}

// sum_i = sum of 1 + 2 + ... + n
// sum_i_squared = sum of 1 + 4 + 9 + ... + n*n
// sum_i_cubed = sum of 1 + 8 + 27 + ... + n*n*n

Explanation / Answer

#include <iostream>
#include <cstdlib>
#include <cassert>
using namespace std;

int main()
{
int i, n, i_squared, i_cubed, sum_i, sum_i_squared, sum_i_cubed;

cin >> n;
assert ( n > 0 && n <= 100 );

sum_i = 0;
// sum_i is the sum of the first 0 values for i

sum_i_squared = 0;
// sum_i_squared is the sum of the first 0 values for i*i


sum_i_cubed = 0;
// sum_i_cubed is the sum of the first 0 values for i*i*i

// The first iteration of the loop will use value 1 for i
// The last iteration of the loop will use value n for i
for ( i = 1; i <= n; i++ ) {
i_squared = i * i;
i_cubed = i * i * i;

sum_i = sum_i + i;
sum_i_squared = sum_i_squared + i_squared;
sum_i_cubed = sum_i_cubed + i_cubed;
}

cout<<"Sum of the numbers from 1 to n is "<<sum_i<<endl;
cout<<"Sum of the square of the numbers from 1 to n is "<<sum_i_squared<<endl;
cout<<"Sum of the cube of the numbers from 1 to n is "<<sum_i_cubed<<endl;

return 0;


}