logo Practice-It logo

writeSquares

Language/Type: Java recursion recursive programming
Author: Stuart Reges (on 2014/02/13)

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 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

You must exactly reproduce the format of these examples. Your method should throw an IllegalArgumentException if passed a value less than 1. You may NOT use a while loop, for loop or do/while loop to solve this problem; you must use recursion.

Write your solution to writeSquares below.

Type your solution here:


This is a method problem. Write a Java method as described. Do not write a complete program or class; just the method(s) above.

You must log in before you can solve this problem.


Log In

If you do not understand how to solve a problem or why your solution doesn't work, please contact your TA or instructor.
If something seems wrong with the site (errors, slow performance, incorrect problems/tests, etc.), please

Is there a problem? Contact a site administrator.