Write a method called writeSequence that accepts an integer n as a parameter and
ID: 3557259 • Letter: W
Question
Write a method called writeSequence that accepts an integer n as a parameter and prints to the
console a symmetric sequence of n numbers composed of descending integers that ends in 1, followed
by a sequence of ascending integers that begins with 1. The following table indicates the output that
should be produced for various values of n:
Method call Output produced
-----------------------------------------
writeSequence(1); 1
writeSequence(2); 1 1
writeSequence(3); 2 1 2
writeSequence(4); 2 1 1 2
writeSequence(5); 3 2 1 2 3
writeSequence(6); 3 2 1 1 2 3
writeSequence(7); 4 3 2 1 2 3 4
writeSequence(8); 4 3 2 1 1 2 3 4
writeSequence(9); 5 4 3 2 1 2 3 4 5
writeSequence(10); 5 4 3 2 1 1 2 3 4 5
Notice that when n is odd the sequence has a single 1 in the middle, whereas for even values it has two
1s in the middle. Your method should throw an IllegalArgumentException if it is passed a value less
than 1. Write a main program to test 1, 5, 6, 9 and 10.
Explanation / Answer
public class NumberSequence
{
public static void main(String[] args)
{
writeSequence(1);
System.out.println();
writeSequence(5);
System.out.println();
writeSequence(6);
System.out.println();
writeSequence(9);
System.out.println();
writeSequence(10);
System.out.println();
writeSequence(-9);
System.out.println();
}
public static void writeSequence(int num)
{
if (num < 0)
throw new IllegalArgumentException("Error: score is negative.");
else
{
if(num%2==0)
{
for(int i=num/2; i>=1; i--)
System.out.print(i + " ");
for(int i=1; i<=(num/2); i++)
System.out.print(i + " ");
}
else
{
for(int i=(num+1)/2; i>0; i--)
System.out.print(i + " ");
for(int i=2; i<=((num+1)/2); i++)
System.out.print(i + " ");
}
}
}
}
Output:
1
3 2 1 2 3
3 2 1 1 2 3
5 4 3 2 1 2 3 4 5
5 4 3 2 1 1 2 3 4 5
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.