SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Recursion
Exercise:
Exercises
Question:6 | ISBN:9780136091813 | Edition: 2

Question

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.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

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

 

0 0

Discussions

Post the discussion to improve the above solution.