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

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

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 in java programming language. ## Methods Discussed

• Method 1 : Using Iteration
• Method 2 : Using Recursion (Top-Down Approach)
• Method 3 : Using Bottom-up recursive approach

## Method 1 :

In this method we will use loop to find maximum and minimum element of the given input array. You can check out the following pages to find the smallest and largest element of the array : ### Method 1 : Code in Java

```import java.util.Scanner;

public class Main
{
public static void main(String args[])
{

int arr[] = {12, 13, 1, 10, 34, 10};

int largest = arr, smallest=arr;

for(int i=0; i<arr.length; i++)
{
if(smallest > arr[i])
smallest = arr[i];
if(largest < arr[i])
largest = arr[i];

}

System.out.println(smallest);
System.out.println(largest);
}
}```

`134`

## Method 2 :

In this method we will use recursive approach (top-down ) to find maximum and minimum element of the given input array. You can check out the following pages to find the smallest and largest element of the array :

### Method 2 : Code in Java

```import java.util.Scanner;

public class Main
{
static int getmin(int arr[], int n){
if(n==1)
return arr;

return Math.min(arr[n-1], getmin(arr, n-1));
}
static int getmax(int arr[], int n){
if(n==1)
return arr;

return Math.max(arr[n-1], getmax(arr, n-1));
}
public static void main(String args[])
{

int arr[] = {12, 13, 1, 10, 34, 10};
int n = arr.length;
System.out.println(getmin(arr, n));
System.out.println(getmax(arr, n));
}
}```

`134`

## Method 3 :

In this method we will use recursive approach (bottom-up ) to find maximum and minimum element of the given input array. You can check out the following pages to find the smallest and largest element of the array :

### Method 3 : Code in Java

```import java.util.Scanner;

public class Main
{
static int minimum(int arr[], int i, int end)
{
int min;

if(i == end-1)
return (arr[i] < arr[i + 1]) ? arr[i] : arr[i + 1];

min = minimum(arr, i + 1, end);

return (arr[i] < min) ? arr[i] : min;
}
static int maximum(int arr[], int i, int end)
{
int max;

// when we reach 2nd last array element
// return the larger b/w last & 2nd last elements
if(i == end-1)
return (arr[i] > arr[i + 1]) ? arr[i] : arr[i + 1];

max = maximum(arr, i + 1, end);

return (arr[i] > max) ? arr[i] : max;
}
public static void main(String args[])
{

int arr[] = {12, 13, 1, 10, 34, 10};
int n = arr.length;
System.out.println(minimum(arr, 0, n-1));
System.out.println(maximum(arr, 0, n-1));
}
}```

`134`