Is this a proper use of recursion? - java

I made what I think is an example of recursion. Is this acceptable? It's not for a project or anything, my professor is just awful so I try to teach myself.
public void theCat() {
int i;
for (i = 0; i <= 50; i++) {
System.out.println(i);
if (i == 10) {
theCat();
}
}
}

Yes, that is recursion. However, it will be infinite since you never stop it.
What you should do is to have a base case where you check if it is time to stop the recursion. You would also have a reduction step, that will converge the parameter towards the base case, like so:
public int theCat(int i) {
if (i => 50)
return i;
else
return theCat(i + 1);
}
To show the effectiveness of this, have a look at a recursive factorial method:
private long factorial(int n) {
if (n == 1)
return 1;
else
return n * factorial(n-1);
}
Here, the base case checks if we are trying to calculate 1! and in that case returns 1. This is the case where we no longer need to recursively call the method. Instead, we walk backwards along all of the method calls we have made to calculate the final answer:
factorial(5)
factorial(4)
factorial(3)
factorial(2)
factorial(1)
return 1
return 2*1 = 2
return 3*2 = 6
return 4*6 = 24
return 5*24 = 120

This will cause overflow. All recursion should have some kind of base case for exiting so that it does not go infinitely.
Additionally all recursive functions usually receive some kind of an int or some value so that they can use that value in the base case and exit. So for your example I would send int i as an argument into cat and stop when i == 50

Yes and no. Technically this is an example of recursion. But this will never terminate. Normally there is some parameter passed into a recursive method so that it can recognize a "base case" which will not recurse.

Yes, but you must have flag that determine exit from your method, otherwise you catch StackOverFlowError

That will cause a stack overflow as the recursive call is infinite.
We can define recursion in this way:
1. we start with a method that has a specific state
2. inside this method the method itself is called, but the call changes the state of the method
3. the method has a base case (a case where if a method reaches this state it no longer calls itself recursively).

Related

recursive function called with different values

I have a recursive function like this:
public static int h(int n) {
if (n == 0) {
return 0;
}
if (n == 1) {
return 1;
} else {
//variable value is a fixed one.
i = value % 2;
return h(n - h(i) - 1) + h(n - 2);
}
}
Suppose the value of variable value is even at this time.Then if I call the function with h(12) I want to know how the function works?
In this case what I want to happen is evaluate
h(12)=h[12-h(0)-1]+h(10)
=h(11)+h(10)
={h(11-h(0)-1)+h(9)}+{h(10-h(0)-1)+h(8)}
={h(10)+h(9)}+{h(9)+h(8)}
Here when evaluating h(11)+h(10) does the function first finish h(11) and get a value for that before starting with h(n-2) which is this case h(10).
If it first finish h(11) then finally it has to reach n==0 or n==1 case.Then by the time it reaches wouldn't h(n-2) be h(-2) or h(-1).
How can I store the initial function call value of 12 and when it reaches h(n-2) to call as h(10) and then make that part to evaluate as h(8),h(6)..
Each function call stores its own copy of arguments. So, call to h(11) won't change n in the first call (h(12)).
Expressions in Java are evaluated from left to right. This means that the call h(11) would finish before h(10) is called from h(12). However, in this case this is not important, since the result would be the same either way.

How to understand the concept of recursion in java?

I'm new to java programming, and our teacher taught us the concept of recursion and I found it to be a bit complicated. All I understood that it works like a loop(like the factorial of 4) but I still don't quite get it why it works like that. Can I get a detailed explanation on this topic? Here is the piece of code and a picture my teacher used to explain.
package javaapplication1;
public class JavaApplication1 {
static int factorial(int n){
int t;
if(n == 0){
return 1;
} else {
t = factorial(n - 1);
return n * t;
}
}
public static void main(String[] args) {
System.out.println(factorial(5));
}
}
In the following image, the blue color represents stack winding, and the green is stack unwinding, and again I don't know what stack winding and unwinding is.
http://i.stack.imgur.com/pjqJy.png
A recursive function is a function that calls itself until it reaches a return statement, that stops it from recalling itself. Take your example, the Factorial function.
Factorial is a mathematical function that returns the number multiplied by itself - 1 multiplied by itself - 2, ... multiplied by 1, example: factorial of 5 = 5! = 5x4x3x2x1 = 120.
it is also equal to itself multiplied by the factorial of itself -1, which is: 5! = 5x4!
Take into consideration that 0! = 1.
to represent this in a Java code, you need a loop that multiplies the numbers starting from 1, and going till the number you are calculating its factorial.
Further more, explaining your code, let us calculate Factorial(5):
Factorial() returns an integer.
Initial Call from main(): 5 != 0, then skip the condition (n == 0); t
= Factorial(5-1) = Factorial(4);
Second call from Factorial(4): 4 != 0, then skip the condition (n ==
0); t = Factorial(4-1) = Factorial(3);
Third call from Factorial(3): 3 != 0, then skip the condition (n ==
0); t = Factorial(3-1) = Factorial(2);
Fourth call from Factorial(2): 2 != 0, then skip the condition (n ==
0); t = Factorial(2-1) = Factorial(1);
Fifth call from Factorial(1): 1 != 0, then skip the condition (n ==
0); t = Factorial(1-1) = Factorial(0);
Sixth call from Factorial(0): 0 == 0, then return value 1;
First return, 1, to Fifth call (Factorial(1)): return n*t = return 1*1
= return value 1;
Second return, 1, to Fourth call (Factorial(2)): return n*t = return
2*1 = return value 2;
Third return, 2, to third call (Factorial(3)): return n*t = return 3*2
= return value 6;
Second return, 6, to second call (Factorial(4)): return n*t = return
4*6 = return value 24;
Second return, 24, to First call (Factorial(5)): return n*t = return
5*24 = return value 120;
Second return, 120, to Initial call (from main()): print(120);
Hope this helps you understand recursion.
When a call is made to another method, a stack frame is created to hold the state of the current method and it is pushed onto the stack. This is regardless of a method calling itself or another method.
When the call returns, the stack frame is popped of the stack, the state of the method is restored and execution continues in the calling method.
Recursion is when a method (directly or indirectly) calls itself. The general form of a recursive method is:
If a parameter meets a terminating condition, return (usually a result)
Else adjust parameters for the next iteration and call self
The code your teacher wrote has some style issues. It would be clearer if written like this:
static int factorial(int n) {
if (n == 0) {
return 1;
}
return n * factorial(n - 1);
}
Eradicating the unnecessary variable t and redundant else (there is no "else" when the "if" returns - there is merely continuation of execution)
I would write it like this, eliminating the if altogether:
static int factorial(int n) {
return n == 0 ? 1 : n * factorial(n - 1);
}
When one knows that a task can be broken into similar smaller tasks ,then we use recursion or calling the same method(until we met a certain condition).Recursion not only helps in execution of a problem without having to define or invoke another method,it also helps in visualizing a pattern by which the task is getting executed
Personally, I do not like the factorial problem. I find it hard to understand and I do not think it explains recursion in a clear way. So lets look at a different example. Lets say that we want to print numbers from 1-100. This is a very simple task with a for loop and a counter, but it can also be done with recursion. For example:
public static void main(String[] args) {
numbersAscending(1);
numbersDescending(1);
}
//Prints 1 2 3 ... 100
public void numbersAscending(int x){
System.out.println(x);
if(x < 100){
numbersAscending(x+1);
}
}
//Prints 100 99 98 ... 1
public void numbersDescending(int x){
if(x < 100){
numbersDescending(x+1);
}
System.out.println(x);
}
When a function is called, that call goes on top of the stack. Think of this like a stack of cards. Each one has a number on it (1-100). When a function calls itself, a new card gets added to the stack. When the function finishes, it is taken off of the stack.
So for the example above, every time numbersAscending is called, it prints out the current value for x before calling that function again. This results in the numbers being printed in order from 1-100. As soon as 100 is reached, it stops calling itself and pops each function off of the stack.
On the other hand, every time numbersDescending is called, it calls itself again before printing out the number. In this way, x doesn't start printing until it reaches 100. It then moves back down the stack, printing each number as it goes back to the main method.
/*This program in java will help you to understand all the basics of
recursion:
->how control flows in recursion
->how return is executed in the recursive functions
->how and when the statements after recursive function area executed.*/
public class Understanding_Rec{
public static int rec(int x)
{
if(x<5)
{
System.out.println("-->Smaller than 5");
rec(x+1);
System.out.println("<--After recursion inside x<5");
return x;
}
else if(x<7)
{
System.out.println("-->Smaller than 7");
rec(x+1);
System.out.println("<--After recursion inside x<7");
}
System.out.println("<--No Condition Statement");
return x;
}
public static void main(String[] args)
{
int x=1;
rec(x);
System.out.print(x+"Inside main");
}
}
I am not sure if it explains, but if you had a precalculus class then you should know that factorial can be defined in two waqys.
n!=1*2*...*n
of we define
1!=1
and
n!=n*(n-1)!
Try to see yourself that those definitions are equivalent. Pick let us say, 5!
according to second definition
5!=5*4!
but 4!=4*3! so 5!=5*4*3!
but 3!=3*2! so 5!=5*4*3*2!
and so on. Keep doing it until you hit 1!. But 1!=1 so you stop.
Recursion in programming is the same thing.
TomW

Recursive Exponent Method stack overflow

I already searched everywhere for a solution for my problem, but didn't get one. So what I'm trying to do ist use recursion to find out whats a passed integer variable's base to the power of the passed exponent. So for example 3² is 9. My solution really looks like what I found in these forums, but it constantly gives me a stack overflow error. Here is what I have so far.(To make it easier, I tried it with the ints directly not using scanner to test my recursion) Any idea?
public class Power {
public static int exp(int x,int n) {
n = 3;
x = 2;
if (x == 0) {
return 1;
}
else {
return n * exp(n,x-1);
}
}
public static void main(String[] args) {
System.out.println(exp(2,3));
}
}
Well, you've got three problems.
First, inside of the method, you're reassigning x and n. So, regardless of what you pass in, x is always 2, and n is always 3. This is the main cause of your infinite recursion - as far as the method is concerned, those values never update. Remove those assignments from your code.
Next, your base case is incorrect - you want to stop when n == 0. Change your if statement to reflect that.
Third, your recursive step is wrong. You want to call your next method with a reduction to n, not to x. It should read return x * exp(x, n-1); instead.

Understanding basic recursion function in Java to calculate positive integers in array

I am trying to learn recursion in Java and have an array that takes in continuous input until the Scanner reads in a 0.
From there I have a method that (attempts) to calculate the number of positive integers in the array using recursion. This is the first recursive function I have ever written and I keep getting a stackoverflow error.
I have read tutorials and I still can't wrap my head around the basic understanding of recursion.
public class reuncF {
private static int start = 0;
private static int end = 98;
public static void main(String[] args) {
input = input.nextDouble();
list[i] = numInput;
computeSumPositive(numList, count);
}
}
return positives += solve(numbers, count++);
}
}
You forgot to stop your recursion!
There has to be some case where computeSumPositive returns without calling itself again. Otherwise it'll just keep going forever, never getting back to you.
If you did it with a loop, the loop would look like this:
int positives = 0;
for (int i = 0; i < numList.length; ++i) {
if (numList[i] > 0) {
positives++;
}
}
To do that recursively, you just find out what are the variables used in the loop. They are i, numList and positives.
computeSumPositive(int i, double[] numList, int positives)
Then we take a look at what the loop does. First, it checks whether we went too far,
so our recursive function should do that too. It'll have to return instead of just falling through like the loop does. And obviously, it must return the result:
{
if (! (i < numList.length))
return positives;
The loop then does the test and maybe increments positives, so the recursive function should also do that:
if (numList[i] > 0) {
positives++;
}
At the end of the loop, i is updated:
i++;
The loop just starts over, but the recursive function will have to call itself. Of course, we want it to use the new value of i and positives, but fortunately we updated those, so now we can just do:
return computeSumPositives (i, numList, positives);
}
The tricky bit is that the values i, numList, and are local to each call. Each invocation of computeSumPositives can see only the arguments it were given. If it changes them, none of the other invocation can see that change.
EDIT: So if we, for reasons we can only speculate about, wanted desperately for computeSumPositive to take only 2 parameters, we would have to "split up" positives across each invocation. Each invocation knows whether or not its number was positive or not; all we have to do is add them. Then it looks like this:
computeSumPositive(int i, double[] numList)
{
if (! (i < numList.length))
return 0; // I didn't find any at index i
if (numList[i] > 0) {
// Theres one I found + however many my later
// invocations will find.
return 1 + computeSumPositive (i+1, numList);
} else {
// I didn't find any, but my later invocations might.
return computeSumPositive (i+1, numList);
}
}
I find it helpful, when dealing with recursion, to figure out the termination case first.
It looks like you are treating 'count' as an index. So you could check if your at the last index in the array, if so and if the value is positive return a 1, if the value is non-positive return a 0 - dont recurse anymore.
If your not at the last index, and the value is positive return a 1 + the recursive function call, or if the value is non-positive just continue to recurse.
This will still cause a stack overflow for large arrays.
The value of count++ is the same as the value of count; the program uses the value and then increments it. But the result is that computeSumPositive keeps calling itself with the same value of count, which leads to infinite recursion. Note that each time computeSumPositive calls another computeSumPositive, each call has its own copy of the parameters (like count) and the local variables; so incrementing one computeSumPositive's copy of count has no effect on the value of count used by other recursive calls.
Change count++ to count + 1, and also add a way to halt the recursion. (At some point, you will be calling computeSumPositive to look at zero integers, and at that point, it should just return 0 and not call itself. You need to think about: how do you test whether you've reached that point?)

What is wrong with this recursive method? (java)

The method is for a calculator and is supposed to return log2(n). All of the methods used (monus which is minus spelled wrong) power, ect) are written correctly. s(n) just adds one to n and p(n) subtracts one.
when I call the method in the main it gets the remainder right, but always returns 0 for the answer. this confuses me. I am sure it has to do with the fact that i am reinitializing answer to 0 each time the method is called but shouldn't that not matter because it is always going to get set to x before it returns anything?
x is a private static variable that has been set to 0 outside of the method.
public static long v(long n)
{
long answer =0;
if (power(2,x) > n)
{
x = p(x);
setRemainder(monus(n,power(2,x)));
answer = x;
}
else if(power(2,x) ==n)
{
setRemainder(0);
answer = x;
}
else
{
x = s(x);
v(n);
}
x=0;// reset x so it can be used again.
return answer;
}
can anyone help me?
You should change the line:
v(n);
to:
answer = v(n);
Right now, if the last else block is executed, the answer variable is not changed - so it's still 0.
As stated in the comments you make the recursive call in the else statement but don't assign this to anything when the recursive call returns.
Consider this:
On your first call: x = 0 so probably going to the else statement and enter the recursion. At some point of recursion one of your conditional statements will be true and in this case answer is returned but not assigned in the way back down the stack of recursive calls.
So would look like this:
1: v(n) // this calls v(n) again
2: v(n) returns answer = x // this returns an answer
1: returns answer = 0 // now the return falls down a level to where the recursive
// call was and the answer is lost as was not assigned

Categories