Java - Recursion -
the following adaptation of ap computer science question. book says should print 00100123 think should print 0010012 code below prints 3132123
what going on? not appear have stop condition?!
public class mystery { public static void main(string[] args) { int n; n = 3; mystery(n); } public static void mystery(int n) { int k; (k = 0; k < n; k++) { mystery(k); system.out.print(n); } } }
the actual question reads: consider following method.
public void mystery (int n) { int k; (k=0 ; k < n ; k++) { mystery(k); system.out.print(n); } }
what value returned call mystery (3)?
i understand loop forms stop condition , think understand jhamon's comment "last instruction print n. n 3, there no way prints '0010012'" don't understand why book says should print 00100123.
as batsheba says have tried watching variables while debugging book says should print 00100123. thanks jhamon corrected code, can see book wrong?
that program cannot print "0". prints n
, , if n
0 never reach system.out.print(n)
line. line inside for
statment k<n
.
as others have pointed out in comments, condition in for
loop stop condition. mystery
recursively call n
times. however, in each of these calls, parameter smaller.
(for fun, try changing condition k <= n
. not terminate, because parameter smaller or equal).
if change line print(k)
, intended, indeed print "0010012". here ideone link show that.
Comments
Post a Comment