Discover the answers you need at Westonci.ca, a dynamic Q&A platform where knowledge is shared freely by a community of experts. Our Q&A platform offers a seamless experience for finding reliable answers from experts in various disciplines. Get precise and detailed answers to your questions from a knowledgeable community of experts on our Q&A platform.

Write a Java program that has a static method named range that takes an array of integers as a parameter and returns the range of values contained in the array. The range of an array is defined to be one more than the difference between its largest and smallest element. For example, if the largest element in the array is 15 and the smallest is 4, the range is 12. If the largest and smallest values are the same, the range is 1.

Sagot :

Answer:

The program in Java is as follows:

import java.util.*;

import java.lang.Math;

public class Main{

public static int range(int low, int high){

    return Math.abs(high - low)+1;

}

public static void main(String[] args) {

 Scanner scnr = new Scanner(System.in);

 int num1 , num2;

 System.out.print("Enter two numbers: ");

 num1 = scnr.nextInt();

 num2 = scnr.nextInt();

 System.out.print(range(num1,num2));

}

}

Explanation:

This defines the range method

public static int range(int low, int high){

This calculates and returns the range of the two numbers

    return Math.abs(high - low)+1;

}

The main begins here

public static void main(String[] args) {

 Scanner scnr = new Scanner(System.in);

This declares 2 numbers as integer

 int num1 , num2;

This prompt the user for two numbers

 System.out.print("Enter two numbers: ");

The next two lines get input for the two numbers

 num1 = scnr.nextInt();

 num2 = scnr.nextInt();

This calls the range function and prints the returned value

 System.out.print(range(num1,num2));

}