My codes give an exception while using recursive function - java

i am trying to print numbers from 1 to 10 without using loops in java. When n+1 is passed to recursivefun method call in line 6,it works fine. But when n++ is passed,the code throws an error :/
public class PrintWithoutUsingLoops {
public static void recursivefun(int n) {
if (n <= 10) {
System.out.println(n);
recursivefun(n++);//an exception is thrown at this line.
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
recursivefun(1);
}
}

recursivefun(n++);
passes the original value of n to the recursive call (since you are using the post-increment operator), making this recursion infinite (since each recursive call gets the same value of n, which never reaches 11) and leading to StackOverflowError.
Change it to
recursivefun(n+1);
or
recursivefun(++n);

recursivefun(n++);
is a call with post-increment. Post increment is a mechanism which enlarges the value after it is read. In this case, you always pass 1.
You can use pre-increment which is ++n which first: increments and then passes the value.
The exception you get is StackOverflowError which means, that the stack is full and JVM cannot store more calls on stack, so it won't be able to revert.

recursivefun(n++);
This line means : call recursivefun(n); and then increment n by 1 so you'll always call your fuction with n=1 and caused a stackOverflow sure
So you need to increment n BEFORE all the function, you have some options :
recursivefun(n+1);
//-----------------------------
n++;
recursivefun(n);
//-----------------------------
recursivefun(++n); //pre-cincrement

Indeed both post and pre increment operators increments the value of a variable. Their behavior changes based on the context of the usage. Assume the following code:
For loop 1:
for (i=0; i<10; i++)
...
For loop 2:
for (i=0; i<10; ++i)
...
In both of the above statements, the for loop iterates 10 times irrespective of the increment style used. However consider the following code:
int x = 10;
int y = 20;
int z = x++ + ++y; // z = 10 + 21
System.out.println("x = " + x); // prints 11
System.out.println("y = " + y); // prints 21
System.out.println("z = " + z); // prints 31
Hence from your code it is evident that
recursivefun(n++);
calls recursivefun with argument 1 infinitely. To avoid StackOverFlow error use either ++n or n+1.

Related

Can some one explain me the following Java snippet for recursion?

public class GetElementWithoutPop {
public static void main(String args[]) {
Stack<Integer> stack = new Stack<Integer>();
stack.push(10);
stack.push(20);
stack.push(30);
stack.push(40);
stack.push(50);
stack.push(60);
System.out.println("value is: " + GetElementWithoutPop.getStackElement(stack, 3));
System.out.println("stack is " + stack);
// Using Java
int position = 3;
Integer result = stack.get(position);
System.out.println(result);
}
public static <T> T getStackElement(Stack<T> stack, int index) {
if (index == 0) {
return stack.peek();
}
T x = stack.pop();
try {
return getStackElement(stack, index - 1);
} finally {
stack.push(x);
}
}
}
Till the index becomes 0 from 3 it's all good and simple, but after that the code goes back to try block and then again to finally block and the index starts to increase on its own all the way back to 3 and stack.push(x) brings the stack back to its original state.
How is this happening?
Fairly new to recursions & I need to understand this!
This happens because each function call has its own unique context for the same function so the variable x stores the popped variable and calls recursively to pop further value but that value is stored in x of the next function call, while returning the finally block runs and each unique value of x in each function call is again pushed
T x = stack.pop(); // this value remains stored in the function call stack
try {
return getStackElement(stack, index - 1); // same function runs for further case (n-1) th and stores the value in its own x variable in its context
} finally {
stack.push(x); // after the control returns, this copy of function has its unique x variable and that is pushed again
}
You mention that "index starts to increase on its own all the way back to 3 .." that's because each function call has its own set of variables including index
Some Steps
1) Function call instance with index 3 calls function with index 2
2) Function call instance with index 2 calls function with index 1
3) Function call instance with index 1 calls function with index 0
4) Control returns
5) Now the control is back to instance with index value 1
6) Control returns from even that instance and now is back to instance with index 2
This is like winding and then unwinding,, while solving problems with recursion we have to often decide whether we want to do some work at call for n and then call for n-1 OR call for n-1 , let the control return and then do some work

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

how to break the for loop with respect to other for loop

i saw how to break the loop (using label and break the label) .. but i want to break the first for loop depends on the second for loop :
for example :
public class HelloWorld {
static private int i;
public static void main(String[] args) {
int y = 20;
for (; y <= 30; y += 2)
{
System.out.printf("value of increamented y Value is %d\n", y);
increamentiValue();
}
}
private static void increamentiValue()
{
i = 0;
for (; i <= 5; i += 2) {
System.out.printf("value of i is %d\n", i);
}
}
}
for instance here i want to break the "y" loop depends on the number of iteration in "i" loop ..
for ex:
i want to break "y" for loop if the number iteriation in "i" loop is equal to 0 .. because in my program "i" checks the error ... in my ysytem error may occur any "i" .. if two times i dosnt have error (i==0) i want to break the "y" loop.
EX :
if
At y= 22 , i ==0; (no error occurs)
at y= 23 , i ==0; (no error occurs)
i dont want to proceed till 30. i want to break y loop .
Have increamenti_Value return a value that main uses to terminate the loop.
Separately, though, using an instance variable (i) in the for loop in increamenti_Value is a very suspect thing to do. It's also quite odd to use a for loop, leave out the initializer clause, and yet set the initial condition on the line above.
Have the incrementi_Value return the value of i and check that value in your y loop.
incrementi_Value == 0 ? break : continue;
Change private static void incrementi_Value -> private static int incrementi_Value
then place a return i; when you want to return the current value of i.
Instead of increamenti_Value() being void, make it return boolean - true if the caller should break, false otherwise:
private static boolean increamenti_Value() {
// return true if you want the caller to break
}
And instead of calling it like you are, call it like this:
if (increamenti_Value())
break;
Note that a called method having knowledge of when the caller should do something doesn't seem like a good design. You may want to reconsider your logic.

I do not understand this HeadFirst Java exercise [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 months ago.
Improve this question
I'm reading Head First Java and an exercise is confusing me a little bit. The Original instructions of the exercise are irrelevant, however, the point is to be able to solve it with out just compiling the code and running it, which would just spit out the answer. I am quite confused and am trying to play the debugger and go step by step each line of code and see what is happening. I have added my comments to the code to make sure I am understanding it. Just need help understanding for example what the count is at a specific point and such. Here is the original code, with one line added myself, which i've noted. Some of the lines I will note which I don't understand the best.
**Update: So I gave the best understanding on my code. Questions I have about certain lines are in the comments. If anyone can maybe do a step by step approach of what happens would make it a lot more understandable. Thank you all for your help in advance. I am new to StackOverFlow so hopefully this was the correct way of asking a question.
public class Mix4
{
int counter = 0; //This is setting the variable counter to 0.
public static void main (String[] args)
{
int count = 0; //This is setting the variable count to 0.
Mix4[] m4a = new Mix4[20];//This is initializing an array of 20 m4a objects to null.
int x = 0; //This is setting the variable x to 0;
while ( x < 9 )
{
m4a[x] = new Mix4(); //This actually creates the m4a object at array index 0.
m4a[x].counter = m4a[x].counter + 1;
//This line is very confusing. How can you use a dot operator on a variable?
//I am saying variable because as stated above there is a int counter = 0;
count = count + 1; //This increments the variable count. Why do this though?
count = count + m4a[x].maybeNew(x);
//The count variable again is being implemented but this time it calls the
// maybeNew method and it is passing a 0 as as the argument? Why do this?
x = x + 1; // x is being incremented.
System.out.println(count + " " + m4a[1].counter);
//What is this printing and when does this print?
}
public int maybeNew(int index)
{
if (index < 5)
{
Mix4 m4 = new Mix4(); //Creating a new object called m4.
m4.counter = m4.counter + 1;
//Same question about this from the code of line stated above using dot
//operators on variables.
return 1; //Where does 1 be returned to? I thought you can only have one
//return statement per method?
}
return 0; // I thought only 1 return statement? I have no idea what these return
// statements are doing
}
}
}
m4a[0].counter = m4a[x].counter + 1;
//This line is very confusing. How can you use a dot operator on a variable?
//I am saying variable because as stated above there is a int counter = 0;
m4a is an array of Mix4 objects. You can call object methods or properties(variables) using the . operator
count = count + m4a[x].maybeNew(x);
//The count variable again is being implemented but this time it calls the
// maybeNew method and it is passing a 0 as as the argument? Why do this?
maybeNew() return an int. You are trying to increase the count by whatever number maybeNew(x) returns. x is the value of m4a[0], if x = 0.
System.out.println(count + " " + m4a[1].counter);
//What is this printing and when does this print?
This prints at end of your program. It prints the counter value for the Mix4 object at index 1 in the m4a array
return 1; //Where does 1 be returned to? I thought you can only have one
//return statement per method?
}
return 0; // I thought only 1 return statement? I have no idea what these return
// statements are doing
First of all, a method may or may not return a value. In you method, you want it to return an int. So when you call it here count = count + m4a[x].maybeNew(x);, it like saying, whatever number maybeNew(x) returns, add that to count.
Your first return 1 is inside of a conditional statement. If the condition is satisfied, return 1, else return 0
int x = 0; //This is setting the variable x to 0;
You got this part right
Now inside while loop in the 1st iteration x = 0;
Mix4[] m4a = new Mix4[20];
This again as you correctly guesses is just defining of an array. Simply putting it is a group of 20 reference of type Mix which woould point to the actuall Object of type Mix. Now you have to assign these objects to the references which is what we are doing in the while loop.
m4a[x] = new Mix4();
Here in 1st iretartion we are doing m4a[0] = new Mix4(); so the element at index 0 is initialized.
m4a[0].counter = m4a[x].counter
Here we are simply accessing the counter of the actual object and assigning value to it.
How can you use a dot operator on a variable?
First if all m4a[0] has been initialized. Next thing you need to know is acess modifieer. If you look at the statement
int counter = 0;
No access modifer is specified which means it has default access modifier. Now for default access modifier visibilty of a variable is in the same class and same package(No need of getter/setter methods).
Also note that counter is an instance variable(not local variable) and instance variables are assigned default values(for int it is 0, for String it is null and so on...)
Try to debug the code step by step with this basic understanding.
Where does 1 be returned to? I thought you can only have one
return statement per method?
You may have have one return statement for one branch in your function, its not restricting to have one one return statement per function, its should be only one return statement for one logic path. Like :
public int DoStuff(Foo foo) {
if (foo == null) return 0;
...
return 1; // any thing
}
m4a[0].counter = m4a[x].counter + 1;
//This line is very confusing. How can you use a dot operator on a variable?
//I am saying variable because as stated above there is a int counter = 0;
m4a is an array ofMix4Class objects. You can call object methods or properties using the . operator.
From Using Objects
Code that is outside the object's class must use an object reference or expression, followed by the dot (.) operator, followed by a simple field name, as in:
objectReference.fieldName
System.out.println(count + " " + m4a1.counter);  
//What is this printing and when does this print?
From System.out.println()
Prints an Object and then terminate the line. This method calls at first String.valueOf(x) to get the printed object's string value, then behaves as though it invokes print(String) and then println().
It will print the count value, and counter value for the Mix4 object at index 1 in the m4a array.
Your code as you have shown above will not compile for two reasons:
You have the System.out.printlninside the while loop; this will result in a NullPointerException as when the compiler gets to m4a[1].counter the m4a[1] object has not been created. Only m4a[0] has been created. Alternatively you can leave this line where it is but change it to m4a[0].counter
You have the maybeNew(int index) method declaration inside main; this is mostly likely just a mistake with your curly brackets but just so you know you can't declare a method inside another method; main is a method and so you must declare maybeNewoutside it but call it from within main
public class Mix4 {
int counter = 0;
public static void main (String[] args) {
int count = 0;
Mix4[] m4a = new Mix4[20];
int x = 0;
while (x < 9) {
m4a[x] = new Mix4();
m4a[x].counter = m4a[x].counter + 1;
count = count + 1;
count = count + m4a[x].maybeNew(x);
x = x + 1;
// System.out.println(count + " " + m4a[0].counter);
}
System.out.println(count + " " + m4a[1].counter);
}
public int maybeNew(int index)
{
if (index < 5)
{
Mix4 m4 = new Mix4();
m4.counter = m4.counter + 1;
return 1;
}
return 0;
}
}

Java post-increment (++) not behaving as expected when passed as a parameter

I came across the following issue:
private void doStuff(int i) {
if(i>10) {
return;
}
doStuff(i++);
}
public void publicMethod() {
doStuff(i);
}
I would expect this to run doStuff 10 times and then return.
However i++ does not get executed before the doStuff is called again with 0.
Result is an infinite loop. I know how to fix it but I am wondering if this behaviour is correct or a bug.
Now I would expect this to run doStuff 10 times and then return, however i++ does not get execute before the doStuff is called again with 0.
Yes, the result of the post-increment operator is the original value... and then inside the next call to the method you've a new i. So in other words, this call:
doStuff(i++);
is equivalent to:
int original = i;
i = original + 1;
doStuff(original);
From JLS section 15.14.2:
The value of the postfix increment expression is the value of the variable before the new value is stored.
Given that you don't use i again afterwards (and thus any side-effect on it is pointless), why not just simplify your life?
doStuff(i + 1);
(As with all parameters in Java, you're seeing pass-by-value - changing the value of i in the method does not change the value of the caller's argument.)
It behaves as expected it should, you probably want to replace i++ with ++i.
Check the oracle documentation on how to use the prefix/postfix unary increment operator:
class PrePostDemo {
public static void main(String[] args){
int i = 3;
i++;
// prints 4
System.out.println(i);
++i;
// prints 5
System.out.println(i);
// prints 6
System.out.println(++i);
// prints 6
System.out.println(i++);
// prints 7
System.out.println(i);
}
}
(excerpt from the linked page)
The ++ operator works just as expected. it first returns the value of the variable, and then increases the variable, hence you always pass 0.
This:
doStuff(i++);
is like:
int x = i;
i += 1;
doStuff(x);
i++ means that: "use value of i and then increment it". It will always be zero when passed down. It is a value type, not a reference type. If that would be an object, that would be no problem because it would be handled as reference.

Categories