write a program to enter 20 elements in an array and display the maximum and minimum elements with their position in the array
Answers
nums = [x for x in range(1, 21)]
min_num, max_num = min(nums), max(nums)
print(f"min num is: {min_num} at index: {nums.index(min_num)}\nmax num is: {max_num} at index: {nums.index(max_num)}")
Question:-
➡ Write a program to enter 20 elements in an array and display the maximum and minimum elements with their position in the array.
Program:
This is written in Java.
import java.util.*;
class MaxMin
{
static void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter 20 elements...");
int a[]=new int[20];
for(int i=0;i<20;i++)
a[i]=sc.nextInt();
int max=a[0],min=a[0];
int a=0, b=0;
for(int i=1;i<20;i++)
{
if(a[i]>max)
{
max=a[i];
a=i;
}
if(a[i]<min)
{
min=a[i];
b=i;
}
}
System.out.println("Largest number is: "+max);
System.out.println("Its index is: "+a);
System.out.println("Smallest number is: "+min);
System.out.println("Its index is: "+b);
}
}