Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner; //importing scanner
- public class number2 { //program begins
- public static void main(String[] args) { //main method
- /* 2.
- *Write a method sumCubes() which accepts a single parameter num and displays the cube of all the numbers between
- * 1 and num inclusive and calculates their sum. Your method must finally return the sum of all these values
- */
- Scanner input = new Scanner (System.in); //scanner declaration
- int num; //variable declaration
- //input statement for user to enter any number
- System.out.println("Enter any number: ");
- num = input.nextInt();
- //output statement displaying the sum of all the cubed numbers from 1 - [number user entered]
- System.out.println("The sum of all the cubed numbers are: " +sumCubes(num));
- } //main method ends
- //method called sumCubes, ...
- public static int sumCubes(int number) {
- int cube, sum = 0; //variable declaration
- //for loop used to calculate the cube for ech number between 1 to [number user entered] and its total sum
- for(int i=1; i<=number; i++) {
- //finding the cubed value
- cube = i * i * i;
- //finding the sum
- sum+=cube;
- } //for loop ends
- return sum;
- } //method sumCubes ends
- } //program ends
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement