Hi, guys:) in this article let’s see how to find the largest and smallest number from an array which is taken as input from the user.T o know more about arrays in java click here.
Algorithm:
1)Start
2)Take the input size of an array and elements in an array from the user.
3)Assign the first element of an array as a smallest and largest.
4)Go the comparing each element with the largest and smallest.
5)If the current comparing element is larger than the assigned element then assign the current elemnt to the largest variable.
6)If the current comparing element is smaller than the assigned element then assign the current elemnt to the smallest variable.
7)Repeat the steps 4,5 and 6 till the comparision goes until the last element.
8)Stop.
Code goes here:
import java.util.*; class search { public static void main(String args[]) { int[] array; int N,largest,smallest; Scanner scan= new Scanner(System.in); System.out.println("Enter the size of the array"); N=scan.nextInt(); array=new int[N]; System.out.println("Enter the elements in an array"); for(int i=0;i<array.length;i++) array[i]=scan.nextInt(); //To input the elements in an array largest=smallest=array[0]; for(int data:array) { if(data>largest) //Comparing if the current element is largest largest=data;//assigning if the found element is largest if(data<smallest)//Comparing if the current element is largest smallest=data;//assigning if the found element is largest } System.out.println("The largest element of an array is:"+largest); System.out.println("The smallest element of an array is:"+smallest); } }