Sum of the maximum and the minimum element
Anjali gets n numbers in an array. Write a Java program to print the sum of the maximum and the minimum element in the array.If the size of an array is 0 or less print "Invalid Array Size".
Answers
Program:
import java.util.*;
public class MyClass
{
public static void main(String args[])
{
Scanner Sc = new Scanner(System.in);
int n;
System.out.print("Enter total number of elements in the array : ");
n = Sc.nextInt();
if(n <= 0)
{
System.out.print("Invalid Array Size");
}
else
{
System.out.println("Enter the elements in the array : ");
int A[] = new int[n];
for(int i = 0; i < n; i++)
{
A[i] = Sc.nextInt();
}
int Min = A[0], Max = A[0];
for(int i = 0; i < n; i++)
{
if(A[i] > Max)
{
Max = A[i];
}
if(A[i] < Min)
{
Min = A[i];
}
}
int sum = Min + Max;
System.out.println("The sum of the maximum and the minimum element in the array : " + sum);
}
}
}
Output 1:
Enter total number of elements in the array : 6
Enter the elements in the array :
56
47
73
29
27
45
The sum of the maximum and the minimum element in the array : 100
Output 2:
Enter total number of elements in the array : -3
Invalid Array Size