Write a program to accept 20 different numbers in a single dimensional array a [20]. Display the array, the greatest and the smallest numbers of the array.
You can also find maximum number and minimum number using following code below ( max is already initialised with a[0])
for(int i=0;i<20;i++) {
if(max<a[i])
max=a[i];
if(min>a[i])
min=a[i];
}
max and min both are initialised to a[0] because if suppose we initialised min=0 or any number but situation can arise where all numbers in array is greater than min and number stored in min's value is not present in the array so that will become the shortest number which will not give the desired output.
Same applies for max.
Thus, to be on safer side, initialise max and min to value of first element in the array.
Answers & Comments
Topic:-
Answer :-
//The following program has been done in Java.
import java.util.*;
class Arr{
public static void main (String args[]){
Scanner sc=new Scanner(System.in);
int a[]=new int[20];
for (int i=0;i<20;i++){
System.out.print("Enter value of a["+i+"] >> ");
a[i]=sc.nextInt();
}
int min=a[0],max=a[0];
for(int i=0;i<20;i++){
min=Math.min(min,a[i]);
max=Math.max(max,a[i]);
}
System.out.println("\n\n Array:-");
for(int i=0;i<20;i++){
System.out.print(a[i]+" ");
}
System.out.println("\nMaximum number >> "+max);
System.out.println("Minimum number >> "+min);
}
}
Logic :-
Note:-
for(int i=0;i<20;i++) {
if(max<a[i])
max=a[i];
if(min>a[i])
min=a[i];
}