Write a method called printRange that accepts two integers as arguments and prin
ID: 3556579 • Letter: W
Question
Write a method called printRange that accepts two integers as arguments and prints the sequence of numbers between the two arguments, separated by spaces. 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 by itself. 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
Test the method using the following main program:
import java.util.*; // for Scanner
public class Lab4Q2 {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int num1 = console.nextInt();
System.out.print(" Enter a second positive integer: ");
int num2 = console.nextInt();
System.out.println();
printRange(num1, num2);
}
Explanation / Answer
import java.util.*; // for Scanner
public class Lab4Q2 {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int num1 = console.nextInt();
System.out.print(" Enter a second positive integer: ");
int num2 = console.nextInt();
System.out.println();
printRange(num1, num2);
}
public static void printRange(int i, int j) {
while (true) {
System.out.print(i + " ");
if (i < j) {
i = i + 1;
} else if (i > j) {
i = i - 1;
} else if (i == j) {
break;
}
}
}
}
Test Case : 1
Enter a positive integer: 2
Enter a second positive integer: 7
2 3 4 5 6 7
Test Case : 2
Enter a positive integer: 19
Enter a second positive integer: 11
19 18 17 16 15 14 13 12 11
Test Case : 3
Enter a positive integer: 5
Enter a second positive integer: 5
5
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.