Write a method called printRange that accepts two integers as arguments and prin
ID: 3632494 • Letter: W
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 should be the following:
[2, 3, 4, 5, 6, 7]
[19, 18, 17, 16, 15, 14, 13, 12, 11]
[5]
Explanation / Answer
public class Range
{
public static void main(String[] args)
{
printRange(2,7);
printRange(19, 11);
printRange(5, 5);
}
public static void printRange(int start, int end){
if(start == end){
System.out.printf("[%d] ",start);
} else if (start < end){
System.out.print("[");
for(int i = start; i< end; i++){
System.out.printf("%d, ",i);
}
System.out.printf("%d] ",end);
} else{
System.out.print("[");
for(int i = start; i > end; i --){
System.out.printf("%d, ",i);
}
System.out.printf("%d] ",end);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.