In: Computer Science
Java Program
Please Read all directions carefully
Write a method named smallToLarge that asks the user to enter numbers, then prints the smallest and largest of all the numbers typed in by the user and the average (rounded to 2 decimal places). You may assume the user enters a valid integer number for the number of numbers to read. Here is an example dialogue:
/* initialize smallest and largest variables with the 1st user input for Number */
How many numbers do you want to enter? 3 Number 1: 7 Number 2: 11 Number 3: -2 Smallest = -2 Largest = 11 Average = 5.33
Java code:
import java.util.Scanner;
public class Main
{
//defining smallToLarge function
static void smallToLarge(){
Scanner input=new
Scanner(System.in);
//asking for count of
numbers
System.out.print("How
many numbers do you want to enter? ");
//initializing
min,max,count and sum of numbers
int
max,min,count=0,sum=0;
//accepting total number
of numbers
int
no=input.nextInt();
//checking if total
number of numbers is 0 or less
if(no<=0)
//exiting
return;
//printing Number
1
System.out.print("Number
1: ");
//accepting it
int
num=input.nextInt();
//setting it as
max
max=num;
//setting it as
min
min=num;
//incrementing
count
count++;
//setting it as
sum
sum=num;
//looping from 2 to
number
for(int
i=2;i<=no;i++){
//asking for Number
System.out.print("Number "+i+": ");
//accepting it
num=input.nextInt();
//adding it to sum
sum+=num;
//incrementing count
count++;
//checking if current number is max
if(num>max)
//setting max as num
max=num;
//checking if current number is min
if(num<min)
//setting min as num
min=num;
}
//printing
Smallest
System.out.println("\nSmallest = "+min);
//printing Largest
System.out.println("Largest = "+max);
//printing Average
System.out.printf("\nAverage = %.2f",((float)(sum)/count));
}
public static void main(String[] args){
//calling smallToLarge
function
smallToLarge();
}
}
Screenshot:
Input and Output: