FINDING THE LARGEST AND SMALLEST OF N NUMBERS
AIM: To write a program in Java to read N numbers
and find the largest and smallest of them.
ALGORITHM:
- Declare
variables n, Max and Min of type int in method main()
- Declare
an array of integer named a with 50 elements for storing n integers
- Create
an object of type DataInputStream and store its reference in din.
- Get
the value of n using methds readLine() of din, parseInt() of Integer wrapper class.
- Read
n integers using for loop and store them in the array a[] using index i
- Initialize
the variables Min and Max with a[0] (the first Integer
in the array)
- Do
the following n times using a for
loop:
- If a[0] > Max then assign it to Max
- If a[0] < Min then assign it to Min
- Print
the value of Min and Max as the smallest and largest of
given n numbers.
PROGRAM:
import
java.io.*;
public
class MinMax {
public static void main(String args[])
throws IOException
{
int n,Min, Max;
int a[] = new int[50];
DataInputStream din = new
DataInputStream(System.in);
Min = Max = 0;
System.out.print("Enter the value
of n (# inputs) : ");
n = Integer.parseInt(din.readLine());
for(int i=0; i<n; i++)
{
System.out.print("Enter the
Number " + (i+1) + " : ");
a[i] =
Integer.parseInt(din.readLine());
}
Min = Max = a[0];
for(int i=1; i<n; i++)
{
if (a[i] > Max)
Max = a[i];
if (a[i] < Min)
Min = a[i];
}
System.out.println("The Smallest
Number is : " + Min);
System.out.println("The Largest
Number is : " + Max);
}
}
Sample
Run: