Showing posts with label Java program to find maximum; reading console input in Java; BufferedReader class in Java. Show all posts
Showing posts with label Java program to find maximum; reading console input in Java; BufferedReader class in Java. Show all posts

Sunday 13 September 2020

Java program to find the maximum in an array of integers.

In this program, the input is given as console input. Hence the readLine() function defined in the InputStreamReader class is used to get the input. The readLine() reads the input as a string which is to be converted into an integer using the Integer.parseInt() function. The BufferedReader class is used to read a stream of character from a given source ie either from a file or standard input device. Here in this program since the input is read from a standard input device (keyboard), the InputStreamReader object is initialized with System.in. All the InputStream classes are defined in the java.io package. Hence, the first line of the program must be import java.io.*; to access the classes defined in the java.io package.


Program

import java.io.*;
class Maximum
{
    public static void main(String arg[]) throws IOException
    {
        double sum=0,avg;
        int number[]=new int[20];
        int max_position=-1;
       
        BufferedReader x=new BufferedReader(new InputStreamReader(System.in));
        
        System.out.println("Enter the number of elements");
        int n=Integer.parseInt(x.readLine());
        System.out.println("Enter "+n+" numbers");
        for(int i=0;i<n;i++)
            number[i]=Integer.parseInt(x.readLine());
        
        int max=number[0];
        for(int i=0;i<n;i++)
            if (number[i]>max)
            {
                max=number[i];
                max_position=i+1;
            }
        System.out.println("The given array");
        for(int i=0;i<n;i++)
            System.out.print(number[i]+"\t");
            
        System.out.println("\nThe maximum number in the array = "+ max +" found at                                                         position = "+ max_position);
        
    }
}      

OUTPUT

>java Maximum
Enter the number of elements
5
Enter 5 numbers
4
3
9
8
1
The given array
4       3       9       8       1
The maximum number in the array = 9 found at position = 3