on Leave a Comment

Java Program to Find Largest Number in an Array

This java program finds the largest number in an array. First, enter the size of array, then enter the elements of array. Now, store the first array element into a variable, then compare this variable with each array element, if variable is smaller than any array elements, then store that array element into variable. 

Java Program to Find Largest Number in an Array

/* Java Program to Find Largest Element in Array */

import java.util.Scanner;

public class LargestNumber
{
   public static void main(String args[])
   {
       int size, largest, i;
       Scanner read = new Scanner(System.in);
     
       System.out.print("Enter the Size of Array : ");
       size = read.nextInt();
       int arr[] = new int[size];
          
       System.out.print("Enter Array Elements : ");
       for(i=0; i<size; i++)
       {
           arr[i] = read.nextInt();
       }
    
       /* Searching for the Largest Number*/
    
       largest = arr[0];
    
       for(i=0; i<size; i++)
       {
           if(largest < arr[i])
           {
               largest = arr[i];
           }
           
       }
    
       System.out.print("Largest Element in Array is " +largest); 
   }
}

Output:

Enter the Size of Array : 5
Enter Array Elements : 89
56
87
65
90
Largest Element in Array is 90

0 comments:

Post a Comment