I am still a beginner to rec concept.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); }
We need to check for n=529.
Why k is 95?
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
Members have full access to the forums. Advertisements are removed for registered users.
I am still a beginner to rec concept.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); }
We need to check for n=529.
Why k is 95?
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.
GregBrannon (May 22nd, 2014)
Thanks! Btw i didnt write the code i ordered to analayzed it.the value is indeed 952
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.i didnt write the code i ordered to analayzed it