Category : Java | Sub Category : Java Programs from Coding Interviews | By Prasad Bonam Last updated: 2021-01-02 14:36:30 Viewed : 732
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 arrays 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
- 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];
- }
- }
- System.out.println("The Given Array Element is:");
- for(int i = 0; i < a.length;i++)
- {
- System.out.println(a[i]);
- }
- System.out.println("From The Array Element Largest Number is:" + max);
- }
- }
Output
The Given Array Element is:
20
30
50
4
71
100
From The Array Element Largest Number is:100