Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

# Thread: problem with understanding this recursion

1. ## problem with understanding this recursion

```public static boolean goo(int n){
If(n<10){
Return n;
}
Int k=goo((n/100)*10+(n%10));
Return (k*10 +(n%100)/10);

}```
I am still a beginner to rec concept.
We need to check for n=529.
Why k is 95?  Reply With Quote

3. ## Re: problem with understanding this recursion

Hey eyalfish,

I'm guessing the code should look like this:

```	public static int goo(int n){
if(n < 10){
return n;
}
int k = goo((n/100)*10+(n%10));
return (k*10 +(n%100)/10);
}```

When I run the code, where n = 529, I get the value 952.

So, when you are doing these recursion problems or any problems, it nice sometimes to add print statements. It's not that efficient, but it will do the job.

If we change the code to this:

```	public static int goo(int n){
System.out.println("n == " + n);
// Base Case
if(n < 10){
System.out.print("Returning: ");
System.out.println("n == " + n);
return n;
}
//Inductive Case
int k = goo((n/100)*10+(n%10));
System.out.println("k == " + k);
int returnValue = (k*10 +(n%100)/10);
System.out.println("returnValue == "+ returnValue);
return returnValue;
}```

This is our output:
n == 529
n == 59
n == 9
Returning: n == 9
k == 9
returnValue == 95
k == 95
returnValue == 952
952

We can see here that the first output is n == 529. Next we can see the second output is "n == 59". Since the second output is "n == 59", it must be the case that the line:

int k = goo((n/100)*10+(n%10));

must have ran. You should be able to figure out the rest by reading the output. Just go through the code and the output one line at a time.  Reply With Quote

4. ## The Following User Says Thank You to fireredlink5000 For This Useful Post:

GregBrannon (May 22nd, 2014)

5. ## Re: problem with understanding this recursion

Thanks! Btw i didnt write the code i ordered to analayzed it.the value is indeed 952  Reply With Quote

6. ## Re: problem with understanding this recursion

i didnt write the code i ordered to analayzed it
Now fireredlink5000 has shown you a way to do the analysis on your on. If you want to learn to program, play with it until it makes sense as demonstrated above.  Reply With Quote