# Thread: Recursion: returning an array of odd numbers

1. Senior Member
Join Date
Mar 2013
Posts
123
Rep Power
0

## Recursion: returning an array of odd numbers

Hi everyone. I have this method

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

Question: Can someone help me with the algorithm...no code please.. just some tips/advice Thanks in advance
Last edited by NoobieCode; 02-26-2014 at 08:27 PM.

2. ## 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

3. Senior Member
Join Date
Mar 2013
Posts
123
Rep Power
0

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

4. Señor Member
Join Date
Jan 2014
Posts
184
Rep Power
0

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

5. Just a guy
Join Date
Jun 2013
Location
Netherlands
Posts
5,114
Rep Power
9

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

6. Senior Member
Join Date
Jan 2013
Location
Northern Virginia, United States
Posts
5,654
Rep Power
9

## Re: Recursion: returning an array of odd numbers

Any particular reason you are making this method static?

Regards,
Jim

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•