Showing posts with label Java Programming Array Largest Element Passing method. Show all posts
Showing posts with label Java Programming Array Largest Element Passing method. Show all posts

Saturday, October 23, 2021

Finding Largest Element in Array and Passing Array to Method In Java

In this, we complete a task on finding the largest element in Array and passing Array to Method In Java. We Find the largest element in the given Array through the Scanner.

Code: 

import java.util.Scanner;
public class LargestElement{
  public static void main(String[] args){
       Scanner input = new Scanner(System.in);
       int size;
      // Size of Array
      System.out.print("Enter size of Array: ");
      size = input.nextInt();
      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 largest element
      int index = findLargestElemIndex(numbers);  
      System.out.print("\nLargest Element in Array: " + numbers[index]);  
  }//main
  public static int findLargestElemIndex(int[] array){
      //Get the size of array
      int index = 0;
      //iterate over each element and print it
      for(int i = 1; i < array.length; ++i){
           if(array[index] < array[i]){
                index = i;
           } }
    return index;
  }}//class

OutPut:

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