Write a method writeSequence that accepts an integer n as a

Write a method writeSequence that accepts an integer n as a parameter and prints a symmetric sequence of n numbers with descending integers ending in 1 followed by ascending integers beginning with 1, as in the table below:

Call Output

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 for odd numbers the sequence has a single 1 in the middle while for even values it has two 1s in the middle. A client using this method would have to call println to print the line of output

Solution

import java.util.*;

public class writeSequence {

public static void main(String[] args) {
// Prints to the terminal window.
/* if you want to use command line args
       you can change this to command line args
       */
       System.out.print(\"writeSequence(1);\");
       writeSequence(1);
       System.out.print(\"\ writeSequence(2);\");
       writeSequence(2);
       System.out.print(\"\ writeSequence(3);\");
       writeSequence(3);
       System.out.print(\"\ writeSequence(4);\");
       writeSequence(4);
       System.out.print(\"\ writeSequence(5);\");
       writeSequence(5);
       System.out.print(\"\ writeSequence(6);\");
       writeSequence(6);
       System.out.print(\"\ writeSequence(7);\");
       writeSequence(7);
       System.out.print(\"\ writeSequence(8);\");
       writeSequence(8);
       System.out.print(\"\ writeSequence(9);\");
       writeSequence(9);
       System.out.print(\"\ writeSequence(10);\");
       writeSequence(10);
      
}

public static void writeSequence(int n) {

if( n < 1 )
throw new IllegalArgumentException(); // if less than 1 throws illigal expression

if( n == 1 ) {// if 1 prints 1
System.out.print(\"1\");

} else if( n == 2 ) {// if 2 prints 1 1
System.out.print(\"1 1\");

} else if( n % 2 == 0 ){// for even number
System.out.print((n / 2) + \" \" );
writeSequence(n - 2); // recursive calling
System.out.print(\" \" + (n / 2));

} else if( n % 2 == 1 ) { // for odd number
System.out.print(((n + 1) / 2) + \" \");
writeSequence((n - 2)); recursive calling
System.out.print(\" \" + ((n + 1) / 2));
}   
}
}

Write a method writeSequence that accepts an integer n as a parameter and prints a symmetric sequence of n numbers with descending integers ending in 1 followed
Write a method writeSequence that accepts an integer n as a parameter and prints a symmetric sequence of n numbers with descending integers ending in 1 followed

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site