Smallest and largest element in array using java

Smallest and largest element in array using java

 

In this section, we find the smallest and largest number from the array using java.

to find the smallest number and largest number, we need to compare each element with every other element in the array. 

For comparing the element, we need to store the first index value in the temporary variable and then compare it with every other element. for each iteration of comparison, we need to store the present index value in the temporary variable.

Working

Step 1. Initialize an array.

Step 2. Declare the scanner class for taking input.

Step 3. take array size from the user.

Step 4. Take element of array from the user.

Step 5. Print smaller value from calling smaller function.

Step 6. Print larger value from calling larger function.

Larger(int a[],int size)

Step 1. Store first element of array in the large variable.

Step 2. Initialize the loop from 0 to size of the array.

Step 3. Compare the all element to the large variable. if the number is greater than the larger variable so store it in the large.

Step 4. Return large.

Smaller(int a[],int size)

Step 1. Store first element of array in the small variable.

Step 2. Initialize the loop from 0 to size of the array.

Step 3. Compare the all element to the small variable. if the number is smaller than the small variable so store it in the small.

Java program to find the smallest and largest number in the array

import java.util.Scanner;
public class Main
{
public static int larger(int[] arr,int size)
{
int large=arr[0];
for(int i=0;i<size;i++)
{
if(arr[i]>large)
large=arr[i];
}
return large;
}

public static int smaller
(int[] arr,int size)
{
int small=arr[0];
for(int i=0;i<size;i++)
{
if(arr[i]<small)
small=arr[i];
}
return small;
}

public static void main(String[] args)
{
int[] a = new int[50];
Scanner sc=new Scanner(System.in);
System.out.print("enter size ");
int size=sc.nextInt();
System.out.println("enter Element");
for(int i=0;i<size;i++)
a[i]=sc.nextInt();
System.out.println("smaller: "+smaller(a,size));
System.out.println("largest: "+larger(a,size));
}
}

Output

enter size 5 
enter Element
1
7
3
9
2
smaller: 1
largest: 9