Given an int variable n that has been initialized to a positive value and, in addition, int variables k and total that have already been declared, use a while loop to compute the sum of the cubes of the first n counting numbers, and store this value in total. Thus if n equals 4, your code should put 1*1*1 2*2*2 3*3*3 4*4*4 into total. Use no variables other than n, k, and total. Do NOT modify n.

Respuesta :

Answer:

The c++ program to implement the while loop is given below.

#include <iostream>

using namespace std;

int main() {

  // declaration of integer variables

   int k, n, total;

   // initialization of integer variables

   k=1, n=4, total=0;

//  loop executed till value of k becomes equal to value of n

   while( k <= n ){

       // cube of every integer is added to the variable total

       total = total + ( k * k * k );

       // value of k is incremented to go to the next number

k = k + 1 ;

   }  

   return 0;

}  

Explanation:

The program begins with the declaration of integer variables.  

int k, n, total;

This is followed by initialization of these variables.

k=1, n=4, total=0;

The while loop runs over the variable k which is initialized to 1. The loop runs till value of k reaches the value of integer n.

First, cube of k is computed and added to the variable total.

After first execution of the loop, total is initialized to the cube of 1.

Next, value of variable k is incremented by 1 so that k is initialized to next integer.

After first execution of the loop, k is incremented from 1 to 2.

while( k <= n )

{

total = total + ( k * k * k );

k = k + 1 ;

   }

When the value of k reaches the value of integer n, the cube of n is calculated and added to the variable, total.

When k is incremented, it becomes more than n and hence, loop gets terminated.

As the return type of main is int, the program terminates with the statement shown below.

return 0;

No output is displayed as it is not mentioned in the question.

No user input is taken as it is mentioned that integer variables are already initialized.