Write a recursive method called writeSquares that accepts an integer parameter n and prints the first n squares separated by commas, with the odd squares in descending order followed by the even squares in ascending order. For example, writeSquares(8); prints the following output: 49, 25, 9, 1, 4, 16, 36, 64
A call of writeSquares(1); prints 1. The method should throw an IllegalArgumentException if it is passed a value less than 1.
package recursion;
public class WriteSquares {
public static void writeSquares(int value) {
if (value == 1) {
System.out.print(1);
return;
}
if (value < 1)
throw new IllegalArgumentException();
// if the value is odd number
if (value % 2 == 1) {
System.out.print(value * value + ", ");
writeSquares(value - 1);
// whether if the value is odd number
} else {
writeSquares(value - 1);
System.out.print(", " + value * value);
}
}
public static void main(String[] args) {
// call the method
int x = 8;
System.out.print("first " + x + " squares are: ");
writeSquares(x);
}
}
Output:
first 8 squares are: 49, 25, 9, 1, 4, 16, 36, 64