1 Replies - 239 Views - Last Post: 15 November 2012 - 12:15 PM Rate Topic: -----

#1 max-archy  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 19
  • Joined: 07-February 12

Recursion

Posted 14 November 2012 - 05:43 PM

Hello.
I have a small question. I'm working with recursion. I need to write a method with one positive integer parameter called n. The method will write 2 n -1 integers.

and it's working, except i'm missing pattern that i need.

that's my code:
 
public static String printExpo(int n) {
		if(n == 1)
		return "3";
		else {
		String str = printExpo(n-1);
		return str +" "+ (n+3) +" "+ str ;
		   }
		}


It's working. and that's my output
enter :1
3
enter : 2
3 5 3
but when i'm input number 3 and so on..
enter :3
3 5 3 6 3 5 3
what i'm missing ?

That's the output i wish to have.
n=1: Output is: 3
n=2: Output is: 3 5 3
n=3: Output is: 3 5 3 7 3 5 3
n=4: Output is: 3 5 3 7 3 5 3 9 3 5 3 7 3 5 3
Could anyone give any hint? Thanks in advance

Is This A Good Question/Topic? 0
  • +

Replies To: Recursion

#2 Martyr2  Icon User is offline

  • Programming Theoretician
  • member icon

Reputation: 4399
  • View blog
  • Posts: 12,255
  • Joined: 18-April 07

Re: Recursion

Posted 15 November 2012 - 12:15 PM

I think you mean you need to do 2n + 1. Not minus 1. ;

Notice the center value is 2n + 1, the recursion of course subtracts 1 each time it makes a call to printExpo. So instead of n+3 in the middle replace it with 2n + 1.

This post has been edited by Martyr2: 15 November 2012 - 12:17 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1