# Recursion: returning an array of odd numbers

• 02-26-2014, 08:24 PM
NoobieCode
Recursion: returning an array of odd numbers
Hi everyone. I have this method

Code:

```   public static int[] oddNums(int n){           }```
When a number is passed in, this method returns an array of odd numbers the amount of the number passed in.
So

Ex: Class.oddNums(5) would return [ 1, 3, 5, 7, 9 ]
Class.oddNums(2) would return [ 1, 3]

• 02-26-2014, 09:01 PM
sehudson
Re: Recursion: returning an array of odd numbers
How would you approach it? The basic steps could be:

//declare and initialize an int[]. You know how big it needs to be based on the number passed in.
//continue to generate odd numbers and add them to the array. Think about using a loop.
//return the array
• 02-26-2014, 09:25 PM
NoobieCode
Re: Recursion: returning an array of odd numbers
Thanks. I need to do this recursively.

Base case:
if the number passed in was 1, then return array [1]
else (recursive step)
...something

not sure what to do for recursive step
• 02-26-2014, 10:13 PM
AlexGraal
Re: Recursion: returning an array of odd numbers
While through asking for some advice and figuring out how to do this one problem, you may get a bit better, it is my firm belief that you should go about this from the bottom up - understanding the concepts of how recursion works, and then going from there.

To me, the way to solve this is perfectly clear - but that is because I know recursion.

I know that CodingBat has some VERY good recursion exercises. Once you go through Recursion 1, you'll understand how to do a bunch of basic recursion stuff - and hopefully how it works. After recursion 2, you should have a very complete understanding of the capabilities of recursion.

I strongly recommend that you go through the recursion stuff on there, even after you figure this out with some help from the forum.
• 02-26-2014, 10:35 PM
gimbal2
Re: Recursion: returning an array of odd numbers
I find a 'find files who's name start with xxx in this pile of directories and subdirectories' a good recursion exercise. And all you basically need to know is how to apply the File class. I like it because you can easily visualize what the code needs to do; you do exactly the same when you do the scan yourself.
• 02-27-2014, 03:07 AM
jim829
Re: Recursion: returning an array of odd numbers
Any particular reason you are making this method static?

Regards,
Jim