# Java Program for Finding the Smallest and largest element in an array

## Finding the Smallest and largest element in an array

We have already given two different articles on how to find the smallest and how to find the largest element in an array, in this article we’ll teach you how to write a Java Program for Finding both the Smallest and largest element in an array ### Algorithm for Finding the Smallest and largest element in an array

• Step 1 – Accept the length of the array from the user. We will be using the variable len, for that.
• Step 2 – Declare an array and accept the input from the user, using a for loop.
• Step 3 – Initialize two variable, large and small for storing the largest and the smallest element, and store the first element of the array in both those variables for now.
• Step 4 – Use a for loop again for traversing through all the elements of the array.
• Step 5 – Use an if condition for comparing all the elements with large and small, if the element is larger than the value stored in large, replace the value of large with that value, and do the vice-versa with small.
• Step 6 – End the loop, print large, which will now have the largest element of the array.
• Step 7 – Print small which will now have the smallest element of the array.

## Java Program for Finding the Smallest and largest element in an array

```import java.util.*;
public class first
{
public static void main(String[] args)
{
System.out.print("Enter the length of the array : ");
Scanner sc=new Scanner(System.in);
int len=sc.nextInt();
int[] arr=new int;
System.out.print("Enter the elements of the array : ");
for(int i=0;i < len;i++)
{
arr[i]=sc.nextInt();
}
int large = arr;
int small = arr;
for(int i=0;i<len;i++) { if(arr[i]>large)
{
large=arr[i];
}
else if(arr[i] < small)
{
small=arr[i];
}
}
System.out.println("The largest element of the array : "+large);
System.out.println("The Smallest element of the array : "+small);
}
}```
```Output

Enter the length of the array : 5
Enter the elements of the array : 45
548
125
456
125
The largest element of the array : 548
The Smallest element of the array : 45```

## Largest Number

Click on the below button to learn how to Write a Java Program to find the largest number in an array