Java Program To Find Largest And Smallest Number In An Array

Sharing is healthy !!

In today’s post let us learn java program to find largest and smallest number in an array. Here, i’m gonna show you java program with using Scanner class and without using Scanner class. Let’s see code implementation,

Java Program To Find Largest And Smallest Number In An Array
Largest And Smallest

JAVA PROGRAM TO FIND LARGEST AND SMALLEST NUMBER IN AN ARRAY WITHOUT USING SCANNER CLASS:

Also Read – Convert Decimal to Octal Java Program

public class Largest_Smallest {

public static void main(String[] args) {

// assigning array of 10 numbers to numerals

int numerals[] = new int[]{32,43,53,54,32,65,63,98,43,23};

// assigning first numeral of an array to largest and smallest

int largest = numerals[0];
int smallest = numerals[0];

for(int x = 1;x < numerals.length;x++){
if(numerals[x] > largest)
largest = numerals[x];
else if(numerals[x] < smallest)
smallest = numerals[x];
}
System.out.println("Largest Number is: " + largest);
System.out.println("Smallest Number is: " + smallest);
}
}

Output:

Largest Number is: 98
Smallest Number is: 23


JAVA PROGRAM TO FIND LARGEST AND SMALLEST NUMBER IN AN ARRAY USING SCANNER CLASS:

Also Read – Java Program To Find Even Or Odd

import java.util.Scanner;

public class Largest_Smallest {

public static void main(String[] args) {

// assigning array of 10 numbers to numerals

int a;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of elements to find largest and smallest number: ");
a = sc.nextInt();
int numerals[] = new int[a];
System.out.println("Enter " + a + " integers.");
for(int b = 0;b < a;b++)
numerals[b] = sc.nextInt();

// assigning first numeral of an array to largest and smallest

int largest = numerals[0];
int smallest = numerals[0];

for(int x = 1;x < numerals.length;x++){
if(numerals[x] > largest)
largest = numerals[x];
else if(numerals[x] < smallest)
smallest = numerals[x];
}
System.out.println("Largest Number is: " + largest);
System.out.println("Smallest Number is: " + smallest);
}
}

Output:

Enter number of elements to find largest and smallest number: 10
Enter 10 integers. 23 34 90 34 31 67 89 12 40 87
Largest Number is: 90
Smallest Number is: 12

Sharing is healthy !!

Leave a Reply

Your email address will not be published.