This example shows you how to find largest or maximum number in an array
Step 1:
Initialize array value
Step 2: (int max = a[0];)
Initialize max value as array’s first value
Step 3: (for int i = 1; i < a.length; i++ ) Iterate array using a for loop (exclude arrays first position 0, since it was assumed as max value) Step 4: if(a[i] > max)
Use if condition to compare array current value with max value, if current array value is greater than max then assign array current value as max (max = a[i];).
Step 5:
Continue the loop and resign the max value if array current value is greater than max program to find largest number in an array
class LargestNumber { public static void main(String args[]) { int[] a = new int[] { 20, 30, 50, 4, 71, 100}; int max = a[0]; for(int i = 1; i < a.length;i++) { if(a[i] > max) { max = a[i]; } }
Output
The Given Array Element is:
20
30
50
4
71
100
From The Array Element Largest Number is:100