Question

java : Given an int variable n that has been initialized to a positive value and,...

java :

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 do...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.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

SumOfCubes.java:

public class SumOfCubes {
    public static void main(String args[]) {
       int n=10;//n is value for which we need sum of cubes upto
       int k=1,total=0;//k is used for iteration and total to store the sum
       do
       {
          total = total + k*k*k;//calculating cube of number and adding it to total
          k++;
       }
       while(k<=n);
       System.out.println(total);//print value of total
    }
}

Output:

SumOfCubes.java:( value of n entered during run-time)

import java.util.*;

public class SumOfCubes {
    public static void main(String args[]) {

      Scanner in = new Scanner(System.in);
       int n=0;//n is value for which we need sum of cubes upto
       int k=1,total=0;//k is used for iteration and total to store the sum

       System.out.println("Enter value of n:");//input given during run-time
       n = in.nextInt();
       do
       {
          total = total + k*k*k;//calculating cube of number and adding it to total
          k++;
       }
       while(k<=n);
       System.out.println(total);//print value of total
    }
}

Output:

Add a comment
Know the answer?
Add Answer to:
java : Given an int variable n that has been initialized to a positive value and,...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT