Saturday 26 June 2021

Find Smallest and Largest elements in an Array - Java Program

Problem Statements:-  

You are given an array of numbers. You need to find smallest and largest numbers in the array.

Solutions:- 

  1. Initialize two variable largest and smallest with array[0] 
  2. Iterate over array If current element is greater than largest, then assign current element to largest. If current element is smaller than smallest, then assign current element to smallest. 
  3. You will get smallest and largest element in the end.

Java code to find Smallest and Largest Element in an Array :

package com.datastructure.Array;

public class LargestAndSmallestElementsInArray {

            public static void main(String[] args) {

             int arrays[] = { 2, 5, 3, 1, 6, 7, 8, 9, 2, 4, 5, 9 };

              findLargestAndSmallestElementsInArray(arrays);

}

   private static void findLargestAndSmallestElementsInArray(int[] arrays) {


int smallestElements = arrays[0];

int largestElements = arrays[0];


for (int i = 0; i < arrays.length; i++) {


if (arrays[i] > largestElements) {

largestElements = arrays[i];


} else if (arrays[i] < smallestElements) {

smallestElements = arrays[i];

}

}

                 System.out.println("Smallest elements in array is : " + smallestElements);

                 System.out.println("Largest elements in array is : " + largestElements);

}

}

Output:-

Smallest elements in array is : 1

Largest elements in array is : 9


Thank you

Happy Learning


No comments:

Post a Comment