java - Need explaination on two different approach to find factorial -
i beginner.i learned c. java seeming difficult me. in c programming approach simple , when looked @ book's programs simple task such factorial, given complex programs below -
class factorial { // recursive method int fact(int n) { int result; if(n==1) return 1; result = fact(n-1) * n; return result; } } class recursion { public static void main(string args[]) { factorial f = new factorial(); system.out.println("factorial of 3 " + f.fact(3)); system.out.println("factorial of 4 " + f.fact(4)); system.out.println("factorial of 5 " + f.fact(5)); } }
instead, when made own program (given below) keeping simple , worked , easy. can tell me what's difference between 2 ?
public class simplefacto { public static void main(string[] args) { int n = 7; int result = 1; (int = 1; <= n; i++) { result = result * i; } system.out.println("the factorial of 7 " + result); } }
also can tell me java ee , java se ?
the first approach of recursion. not fast , easy. (and leads stackoverflowerror, if not careful). second approach of normal loop. interstingly, both approaches valid in "c".
i think should not compare java programs c programs. both languages designed different reasons.
Comments
Post a Comment