In: Computer Science
Write a program, ArrayRange, that asks the user to input integers and that displays the difference between the largest and the smallest. You should ask the user the number of integers s/he would like to enter (this will allow you to set the length of the array). Allow the user to input all the numbers and then store them in the array. Search the array for the largest number, then search for the smallest, and finally compute the calculation. Display all the numbers given by the user, the max number, the min number, and the difference. Java Programming
Output
How many integers will you enter? 6
Enter 6 integers: 7 15 9 4 12 17
You entered: 7 15 9 4 12 17
Min: 4
Max: 17
Range: 13
Java code:
import java.util.Scanner;
public class ArrayRange{
public static void main(String[] args){
Scanner input=new
Scanner(System.in);
//asking for n
System.out.print("How many integers
will you enter? ");
//accepting it
int n=input.nextInt();
//asking for numbers
System.out.print("Enter "+n+"
integers: ");
//array of list of numbers
int[] numbers=new int[n];
//looping from 0 to n
for(int i=0;i<n;i++){
//accepting number
numbers[i]=input.nextInt();
}
//printing the numbers
System.out.print("You entered: ");
//assigning first number as min
int min=numbers[0];
//assigning first number as max
int max=numbers[0];
//looping from 0 to n
for(int i=0;i<n;i++){
//checking if numbers[i] is greater than max
if(numbers[i]>max)
//assigning numbers[i] to max
max=numbers[i];
//checking if numbers[i] is less than min
if(numbers[i]<min)
//assigning numbers[i] to min
min=numbers[i];
System.out.print(numbers[i]+" ");
}
//printing newline
System.out.println();
//printing min
System.out.println("Min: "+min);
//printing max
System.out.println("Max: "+max);
//printing min
System.out.println("Range: "+(max-min));
}
}
Screenshot:
Input and Output: