Monday, May 2, 2022

Question 10 : Write java Program to Find Smallest and Largest Element in an Array

You are given an integer array containing 1 to n but one of the numbers from 1 to n in the array is missing. You need to provide an optimum solution to find the missing number. 

The number can not be repeated in the array.
For example
int[] arr1={7,5,6,1,4,2}; Missing numner : 3 int[] arr2={5,3,1,2}; Missing numner : 4


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


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

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

/* Java program to Find Largest and Smallest Number in an Array */ public class FindLargestSmallestNumberMain { public static void main(String[] args) { //array of 10 numbers int arr[] = new int[]{12,56,76,89,100,343,21,234}; //assign first element of an array to largest and smallest int smallest = arr[0]; int largest = arr[0]; for(int i=1; i< arr.length; i++) { if(arr[i] > largest) largest = arr[i]; else if (arr[i] < smallest) smallest = arr[i]; } System.out.println("Smallest Number is : " + smallest); System.out.println("Largest Number is : " + largest); } }

When you run the above program, you will get the below output:
Largest Number is : 343 Smallest Number is : 12
Don't miss the next article! 
Be the first to be notified when a new article or Kubernetes experiment is published.                            

   Share This

You may also like

Kubernetes Microservices
Python AI/ML
Spring Framework Spring Boot
Core Java Java Coding Question
Maven AWS