I've been trying to print the numeric pattern 4,5,9,18,34 through recursion but I'm getting java.lang.stackoverflowerror error. Here is my code for your reference. Any help would be highly appreciated. Thank You
public class pattern3 {
public static void main(String[] args) {
// TODO Auto-generated method stub
pattern(4,0,5);
}
static void pattern(int n,int pos,int z) {
if(pos==z) {
return;
}
int a=(int) Math.pow(pos,2);
int b=n+a;
pattern(b,pos++,z);
System.out.println(b);
}
}
By swapping the lines
pattern(b, pos++, z);
andSystem.out.println(b);
, you'll see that the value ofb
is always4
. The reason for this is that the argument forpos
is always0
. The postfix increment operator (e.g.,pos++
) increments the value but returns the old value. Since the first argument forpos
was0
, the old value forpos
will always be0
.You need to change:
To: