java - Recursion Driver Methods -
public class findsum { private static int sum(int n) { if (n==1) return 1; else return n + sum (n-1); } public static int getsum(int n) { if (n>0) return sum(n); else { throw new illegalargumentexception ("error: n must positive"); } } }
according book, tests n>0 before execution. don't understand why case if test "if (n>0)" comes after algorithm. shouldn't 2 methods flipped in order accomplish test?
the order they're written in doesn't matter, rather order of execution critical.
since getsum
explicitly calls sum
if check successful, there's no worry check getting missed, long call getsum
.
Comments
Post a Comment