JAVA program to find largest of n numbers in a given array
This JAVA program is to find the largest element from a given array.
For example, if an array a consists of elements a={17,58,2,39} and if we want to find the largest element then the largest element would be 58.
Logic
We start to iterate and then compare all the elements with each other and store the largest element in the variable named ‘large’ and then keep comparing till we find the largest element.
Dry Run of the Program
Take input array ‘a’ and no of elements(n) as 4
Let us take elements for array a={7,8,12,3}.
large=a[0] i.e. large=7
1st iteration for(i=1;i<n;i++) i.e. for(i=1;1<4;i++)
if(large<a[i]) i.e. if(7<a[1]) i.e. if(7<8) true
large=a[i] i.e. large=a[1] i.e. large=8
2nd iteration for(i=2;i<n;i++) i.e. for(i=2;2<4;i++)
if(large<a[i]) i.e. if(8<a[2]) i.e. if(8<12) true
large=a[i] i.e. large=a[2] i.e. large=12
3rd iteration for(i=3;i<n;i++) i.e. for(i=3;3<4;i++)
if(large<a[i]) i.e. if(12<a[3]) i.e. if(12<3) false
Now we come out of the for loop as i(4) is not less than n(4)
Hence, the largest element we found in the array is 12
Program
import java.util.*; class arr6 { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int i,n,large; System.out.println("Enter the number of elements:") ; n = sc.nextInt(); int[] a = new int[n]; System.out.println("Enter the elements") ; for(i=0;i<n;i++) { a[i] = sc.nextInt(); } large = a[0]; for(i=1;i<n;i++) { if(large<a[i]) { large = a[i]; } } System.out.println("Largest of "+n+" elements in an array = "+large); } }