SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Arrays
Exercise:
Exercises
Question:2 | ISBN:9780136091813 | Edition: 2

Question

Write a method called range that returns the range of values in an array of integers. The range is defined as 1 more than the difference between the maximum and minimum values in the array. For example, if an array called list

contains the values {36, 12, 25, 19, 46, 31, 22}, the call of range(list) should return 35 (46 - 12 + 1). You may assume that the array has at least one element.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Implementation of range method:

	public static int range(int[] list)
	{
		int maximum = list[0];
		int minimum = list[0];
		
		for(int i = 1; i < list.length; i++)
		{
			if(list[i] > maximum)
				maximum = list[i];
			
			if(list[i] < minimum)
				minimum = list[i];
		}
		
		return (maximum - minimum + 1);
	}
0 0

Discussions

Post the discussion to improve the above solution.