Saturday, October 23, 2021

Finding Smallest Element in Array And Passing Array to Method in Java

 In this code, we cover the Finding Smallest Element in Array And Passing Array to Method through Java. we cover through use the Scanner object.

Code:

import java.util.Scanner;
public class SmallestElement{
  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 smallest value
      int index = findSmallestElemIndex(numbers);  
      System.out.print("\nSmallest Element in Array: " + numbers[index]);  
  }//main
  public static int findSmallestElemIndex(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: 

No comments:

Post a Comment

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