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:
Conditional Execution
Exercise:
Exercises
Question:5 | ISBN:9780136091813 | Edition: 2

Question

Write a method called printRange that accepts two integers as arguments and prints the sequence of numbers between the two arguments, enclosed in square brackets. Print an increasing sequence if the first argument is smaller than the second; otherwise, print a decreasing sequence. If the two numbers are the same, that number should be printed between square brackets. Here are some sample calls to printRange:
printRange(2, 7);
printRange(19, 11);
printRange(5, 5);

The output produced from these calls should be the following sequences of numbers:
[2, 3, 4, 5, 6, 7]
[19, 18, 17, 16, 15, 14, 13, 12, 11]
[5]

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Program:

public class Ch04Ex05
{
	public static void main(String[] args)
	{
		printRange(2, 7);
		printRange(19, 11);
		printRange(5, 5);
	}

	public static void printRange(int first, int second)
	{
		System.out.print("[");
		if (first < second)
		{
			for (int i = first; i <= second; i++)
			{
				System.out.print(i);

				if (i < second)
					System.out.print(", ");
			}
		}
		else // if (first >= second)
		{
			for (int i = first; i >= second; i--)
			{
				System.out.print(i);

				if (i > second)
					System.out.print(", ");
			}
		}
		System.out.println("]");
	}
}

Output:

[2, 3, 4, 5, 6, 7]
[19, 18, 17, 16, 15, 14, 13, 12, 11]
[5]

 

0 0

Discussions

Post the discussion to improve the above solution.