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

Where am I going wrong? I am trying to solve this using Java. O PREV NEXT O Work

ID: 3909290 • Letter: W

Question

Where am I going wrong? I am trying to solve this using Java.

O PREV NEXT O Workbench Exercise 20681 x WORK AREA RESULTS 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 whole numbers, and store this value in total. Use no variables other than n, k, and total and do not modify the value of n. 7 of 7: Tue Jun 26 2018 12:26:30 GMT-0400 (Eastern Daylight Time) SUBMIT total0 k) while (n 5 6 4 >= total total (n*n*n) k++i

Explanation / Answer

You are computing directly the n cube everytime in the loop, but you need to calculate cube of each value and add it to total. For example n=3, the out put will be 1^3 + 2^3 + 3^3 =36 (1 cube + 2 cube + 3 cube) whic was sum of cubes of first n whole numbers. So replace n with k when computing n cube and add it to total and increment k for each ietration.

Code:

public class Cubes {

public static void main(String[] args) {

// TODO Auto-generated method stub

int k=1, total=0;

int n=3;

while(n>=k)

{

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

k++;

}

System.out.println("The value of n cube is "+total);

}

}

Output :

The value of n cube is 36

Loop 1: k =1 , n=3, total =0+1^3 =1

Loop 2: k=2 , n=3, total =1+ 2^3 =9

Loop 3: k=3 , n=3 total =9+3^3= 36

now k=4 which is greater than n , so the loop breaks

Please upvote if you like the answer and comment if you need further information in this regard.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote