Showing posts with label Average of Array and Passing. Show all posts
Showing posts with label Average of Array and Passing. Show all posts

Friday, October 22, 2021

Passing Array to Method and Average of Array Elements

 In this task, we complete the task Passing Array to Method and Average of Array Elements in java Using the Scanner.

Code:

import java.util.Scanner;
public class AvgArray{
  public static void main(String[] args){

       Scanner input = new Scanner(System.in);
       int size;

      // Size of Array
      System.out.print("Enter size of Array: ");
      System.out.println("\n\n");

      //Declaring and creating an array of specified size
      int[] numbers = new int[size];


      //Take Array elements from user
      for(int i=0; i<size; i++){
         System.out.print("Enter value for numbers[" + i + "] = ");
         numbers[i] = input.nextInt();
         System.out.println("\n\n");
      }

      // Calling method to find average of elements
      int avg = avgArray(numbers);  


      System.out.print("\nAverage of Array Elements: " + avg);  
   
  }//main

  public static int avgArray(int[] array){
      
      //Get the size of array
      int sum = 0, avg;

      //iterate over each element and print it
      for(int i = 0; i < array.length; ++i){
            sum = sum + array[i];
      }

     avg = sum / array.length;
    return avg;
  }
}//class

String Array and passing method in java

 In this task, we pass a method and also cover the passing String Array to the method. Code:   import java.util.Scanner; public class String...