Reputation: 25
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);
}
}
Upvotes: 1
Views: 246
Reputation: 1
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.
Upvotes: 0
Reputation: 54148
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
Upvotes: 2
Reputation: 15842
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.
Upvotes: 1
Reputation: 393851
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);
Upvotes: 6