Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a method writeSquares that takes an integer n as a parameter and that writ

ID: 3542738 • Letter: W

Question

Write a method writeSquares that takes an integer n as a parameter and that writes the first n squares to System.out separated by commas with the odd squares in descending order followed by the even squares in ascending order.  For example, the call:

writeSquares(5);

should produce the following output:

25, 9, 1, 4, 16

The odd squares (25, 9, and 1) appear first in descending order followed by the even squares (4 and 16) in ascending order.  Notice that commas are used to separate consecutive values in the list.  Your method should send its output to System.out.print and should not call println.  For example, the following calls:

writeSquares(5);

System.out.println();  // to complete the line of output

writeSquares(1);

System.out.println();  // to complete the line of output

writeSquares(8);

System.out.println();  // to complete the line of output

should produce exactly three lines of output:

25, 9, 1, 4, 16

1

49, 25, 9, 1, 4, 16, 36, 64

Use throw an IllegalArgumentException if passed a value less than 1.  May  not use a while loop, for loop or do/while loop to solve this problem.

Explanation / Answer

writeSquares( int n ) {
if (n <= 0) throw new IllegalArgumentException();

if (n % 2 == 0) { // n is even
writeSquares(n-1);
System.out.print(", " + (n*n));
} else { // n is odd
System.out.print( (n*n) );
if (n > 1) { // no comma or recursion when n=1
System.out.print( ", " );
writeSquares(n-1);
}
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote