Java program to find largest number in an array

Category : Java | Sub Category : Java Programs from Coding Interviews | By Prasad Bonam Last updated: 2021-01-02 14:36:30 Viewed : 468


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

  1. class LargestNumber
  2. {
  3. public static void main(String args[])
  4. {
  5. int[] a = new int[] { 20, 30, 50, 4, 71, 100};
  6. int max = a[0];
  7. for(int i = 1; i < a.length;i++)
  8. {
  9. if(a[i] > max)
  10. {
  11. max = a[i];
  12. }
  13. }
  14. System.out.println("The Given Array Element is:");
  15. for(int i = 0; i < a.length;i++)
  16. {
  17. System.out.println(a[i]);
  18. }
  19. System.out.println("From The Array Element Largest Number is:" + max);
  20. }
  21. }


Output

The Given Array Element is:
20
30
50
4
71
100
From The Array Element Largest Number is:100

Search
Related Articles

Leave a Comment: