In this tutorial you will learn about the Java Program to print largest element in an array and its application with practical example.
In this tutorial, we will learn to create a Java Program to print largest element in an array using java programming.
Prerequisites
Before starting with this tutorial, we assume that you are best aware of the following Java programming concepts:
- Java Operators.
- Basic Input and Output function in Java.
- Class and Object in Java.
- Basic Java programming.
- If-else statements in Java.
- For loop in Java.
Java Program to print largest element in an array
In this program we will find smallest element in an array using nested for loop. We would first declared and initialized the required variables. Next, we will find smallest number in an array. Lets have a look at the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
//java program to find greatest among the array.. import java.io.*; public class Largest_in_An_Array { public static void main(String args[]){ // declaring variables and initializing values int temp, l; int arr[] = {10, 20, 25, 30, 12, 5};// assign values to array l = arr.length; for(int i = 0; i<l; i++ ){// finding length of an array for(int j = i+1; j<l; j++){ if(arr[i]<arr[j]){ temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } //Printing the result.. System.out.println("largest element in an array is "+arr[0]); } } |
Output
Largest in an array
In the above program, we have first declared and initialized a set variables required in the program.
- arr[]= it will hold array values
- l= it will hold length of an array.
- i and j for iteration
- temp = it will hold temporary value of an array.
After declaring variables we initiate values in an array[]
with the help of length function we will find the length of an array .
after that with the help or nested for loop we will find smallest element in array as shown in image below
Largest in an array
- Here first we assign first value of an array to variable temp.
- Compare the first two elements of the array.
- If the value of first element is smaller than the second exchange them.
- Then, compare 2 value and 3 value elements if the second element value is smaller than the 3 value swap them.
- Repeat this till the end of the array[].
- and finally print largest in an array.