Advertisement
thotfrnk

more methods q2.java

Dec 9th, 2022
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.38 KB | None | 0 0
  1. import java.util.Scanner; //importing scanner
  2. public class number2 { //program begins
  3.     public static void main(String[] args) { //main method
  4.        
  5.         /* 2.
  6.         *Write a method sumCubes() which accepts a single parameter num and displays the cube of all the numbers between
  7.         * 1 and num inclusive and calculates their sum. Your method must finally return the sum of all these values
  8.          */
  9.  
  10.         Scanner input = new Scanner (System.in); //scanner declaration
  11.  
  12.         int num; //variable declaration
  13.  
  14.         //input statement for user to enter any number
  15.         System.out.println("Enter any number: ");
  16.         num = input.nextInt();
  17.  
  18.         //output statement displaying the sum of all the cubed numbers from 1 - [number user entered]
  19.         System.out.println("The sum of all the cubed numbers are: " +sumCubes(num));
  20.     } //main method ends
  21.  
  22.     //method called sumCubes, ...
  23.     public static int sumCubes(int number) {
  24.         int cube, sum = 0; //variable declaration
  25.  
  26.         //for loop used to calculate the cube for ech number between 1 to [number user entered] and its total sum
  27.         for(int i=1; i<=number; i++) {
  28.             //finding the cubed value
  29.             cube = i * i * i;
  30.  
  31.             //finding the sum
  32.             sum+=cube;
  33.         } //for loop ends
  34.  
  35.         return sum;
  36.     } //method sumCubes ends
  37. } //program ends
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement