Java Program to Find Largest Element in an Array

This is a Java Program to Find the Largest Number in an Array.

Enter the elements of array as input. By comparing elements of array with each other we get the largest number of the array.

Here is the source code of the Java Program to Find the Largest Number in an Array. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

  1. import java.util.Scanner;
  2. public class Largest_Number 
  3. {
  4.     public static void main(String[] args) 
  5.     {
  6.         int n, max;
  7.         Scanner s = new Scanner(System.in);
  8.         System.out.print("Enter number of elements in the array:");
  9.         n = s.nextInt();
  10.         int a[] = new int[n];
  11.         System.out.println("Enter elements of array:");
  12.         for(int i = 0; i < n; i++)
  13.         {
  14.             a[i] = s.nextInt();
  15.         }
  16.         max = a[0];
  17.         for(int i = 0; i < n; i++)
  18.         {
  19.             if(max < a[i])
  20.             {
  21.                 max = a[i];
  22.             }
  23.         }
  24.         System.out.println("Maximum value:"+max);
  25.     }
  26. }

Output:

$ javac Largest_Number.java
$ java Largest_Number
 
Enter number of elements in the array:5
Enter elements of array:
4
2
3
6
1
Maximum value:6

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

advertisement

Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.

advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 20s–40s and exploring new directions in your career, I also offer mentoring. Learn more here.