Advertisement
thotfrnk

methods and arrays.java

Dec 8th, 2022
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.71 KB | None | 0 0
  1. //class work
  2. import java.util.Scanner; //importing scanner
  3. public class number5And6 { //program begins
  4.     public static void main(String[] args) { //main
  5.  
  6.         Scanner input = new Scanner (System.in); //scanner declaration
  7.  
  8.         int [] arr = new int [5]; //int array declaration
  9.  
  10.         for (int i=0; i<arr.length; i++) { //for loop to initialize the variables within the array
  11.  
  12.             System.out.println("Enter a number: ");
  13.             arr[i] = input.nextInt();
  14.  
  15.         } //for loop ends
  16.  
  17.         cubeArray(arr); //calls the method to change the data within array
  18.  
  19.         for(int i=0; i<arr.length; i++) { //for loop to print the updated values
  20.             System.out.printf("Cubed values: %d\n", arr[i]);
  21.         } //for loop ends
  22.        
  23.  
  24.         //output statement for the average of the array
  25.         System.out.println("The average of the array is: " +average(arr));
  26.  
  27.     } //main method
  28.  
  29.     //method called cubeArray, takes on an argument which is an array and changes the values within the array to its cubed equivalent
  30.     public static void cubeArray(int [] cube) {
  31.         for(int j=0; j<cube.length; j++) {
  32.             cube[j] = cube[j] * cube[j] * cube[j];
  33.         }
  34.     } //method cubeArray ends
  35.  
  36.          
  37.  
  38.     //method called average, adds all the values in the array and finds the average
  39.     public static int average(int [] array) {
  40.         int average = 0, sum = 0; //variable declaration
  41.  
  42.         for(int k=0; k<array.length; k++) {
  43.             //finding the sum of the array
  44.             sum+=array[k];
  45.         }
  46.         //finding the average of the array
  47.         average = sum / array.length;
  48.  
  49.         return average;
  50.     } //method average ends
  51. } //program ends
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement