# Using recursion to print alternating squares?

• 03-09-2012, 06:59 AM
cheezncrackers
Using recursion to print alternating squares?
Hi, I'm trying to use recursion (no loops) to print out descending odd, then ascending even squares less than a certain number.
For examples, squares(5) would print out: 25, 9, 1, 4, 16.
I'm not sure how I would alternate between even/odd, and would really appreciate some help with that.

Right now, I have it so that all squares are printed in descending order. All input is greatly appreciated!

public static void squares(int n)
{
if (n < 1)
{
throw new IllegalArgumentException();
} else
{
System.out.print(n*n);
squares(n-1);
}
}
• 03-09-2012, 08:29 AM
sunde887
Re: Using recursion to print alternating squares?
It's probably easiest just to make one method for the odd squares and one for the even squares. You can also make 2 arrays, one for even, one for odd and at each step just fill the proper array and then make your recursive call.
• 03-09-2012, 10:26 AM
DarrylBurke
Re: Using recursion to print alternating squares?