Saturday, 15 September 2012

java - print all binary numbers of size n using recursion -



java - print all binary numbers of size n using recursion -

i trying print size n binary numbers, illustration if size 3 , want print numbers 0 (2^3)-1 in binary form, below if code implementating, prints 000 , gives me error

"exception in thread "main" java.lang.stackoverflowerror @ java.lang.string.getchars(string.java:854) @ java.lang.abstractstringbuilder.append(abstractstringbuilder.java:391) @ java.lang.stringbuilder.append(stringbuilder.java:119) @ java.lang.stringbuilder.<init>(stringbuilder.java:93) @ nbinary.tobinary(nbinary.java:11) @ nbinary.tobinary(nbinary.java:12)". string temp = str+x; line 11 tobinary(temp, size); line 12

below code

public class nbinary { static int arr[] = {0,1}; static void tobinary(string str,int size){ if(str.length() == size){ system.out.println(str); } for(int x : arr){ string temp = str+x; tobinary(temp, size); } } public static void main(string[]args){ tobinary("", 3); } }

please help me find error. thanks

one problem not giving recursion termination condition. function recurses infinitely. no status there cease calling.

that why stack allocated function phone call runs out of space , stackoverflowerror.

see more here:

http://docs.oracle.com/javase/7/docs/api/java/lang/stackoverflowerror.html

what stack overflow error?

java recursion binary

No comments:

Post a Comment