Java program to find largest number in an array


    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

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

Related example

        Java program to find largest number in an array
        Java program to find second largest number in an array
        Java program to find largest and smallest number in an array
        Java program to find largest and second largest number in an array
        Java program to find second smallest number in an array
        Java program to find index of max value in array java
        Java program to find index of smallest element in array java


Related Post

Comments


©candidjava.com