Write a program to input 20 numbers. Find and print the largtest and smallest numbers within the array.
Answers
Required Program :
import java.util.*;
class Greatest_Smallest
{
void main( )
{
Scanner sc=new Scanner(System.in);
int n[ ] = new int[20] , i, lar, sm;
System.out.println("Please enter 20 Numbers");
for(i = 0; i<10 ; i++)
n[i]=sc.nextInt();
lar=n[0];
sm=n[0];
for(i=1;i<10;i++)
{
if(n[i]>lar)
lar=n[i];
else if(n[i]<sm)
sm=n[i];
}
System.out.println("The Greatest Number entered by you Is "+lar);
System.out.println("The smallest number entered by you is "+sm);
}
}
Explaination :
- Line 1 : We have been using util package of java to begin the program.
- Line 3 : Start of class.
- Line 5 : Start of main method.
- Line 7 : Numbers are entered. Here i is index number, lar is the largest numbers and sm is the smallest numbers.
- Line 19 : Greatest numbers are displayed.
- Line 21 : Smallest numbers are displayed.
- Line 22 : End of main method.
- Line 23 : End of class.
Answer:
import java.util.Scanner; public class KboatSDAMinMaxSum { public static void main(String args[]) { Scanner in = new Scanner(System.in); int arr[] = new int[20]; System.out.println("Enter 20 numbers:"); for (int i = 0; i < 20; i++) { arr[i] = in.nextInt(); } int min = arr[0], max = arr[0], sum = 0; for (int i = 0; i < arr.length; i++) { if (arr[i] < min) min = arr[i]; if (arr[i] > max) max = arr[i]; sum += arr[i]; } System.out.println("Largest Number = " + max); System.out.println("Smallest Number = " + min); System.out.println("Sum = " + sum); } }