Search This Blog

Wednesday, 19 November 2014

Java Program to find the Largest and Smallest of N Integers

0 comments

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:
  1. Declare variables n, Max and Min of type int in method main()
  2. Declare an array of integer named a with 50 elements for storing n integers
  3. Create an object of type DataInputStream and store its reference in din.
  4. Get the value of n using methds readLine() of din, parseInt() of Integer wrapper class.
  5. Read n  integers using for loop and store them in the array a[] using index i
  6. Initialize the variables Min and Max with a[0]  (the first Integer in the array)
  7. Do the following n times using a for loop:
    1. If a[0] > Max then assign it to Max 
    2. If a[0] < Min then assign it to Min 
  8. 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:


Leave a Reply