+ 2

Help to Correct this code to print factorial of a number "n" without using loop( i.e use recursion method).

import java.util.Scanner; public class Factorial { public static void main(String[] args) { Scanner scn=new Scanner(System.in); System.out.println("Enter a number to find its Factorial "); int n=scn.nextInt(); } static int fact(int n){ if(n==0) return 1; return n*fact(n-1); } System.out.println(fact); }

11th Apr 2017, 7:15 PM
Manmohan
Manmohan - avatar
3 Answers
+ 13
You forgot the case n==1, which is 1.
11th Apr 2017, 7:26 PM
Karl T.
Karl T. - avatar
+ 2
if (n==0 || n==1) return 1;
11th Apr 2017, 8:15 PM
Zaur Kandokhov
Zaur Kandokhov - avatar
+ 1
import java.util.Scanner; public class Factorial { public static void main(String[] args) { Scanner scn=new Scanner(System.in); //System.out.println("Enter a number to //find its Factorial "); int n=scn.nextInt(); fact(n); System.out.println(p); } static int p=0; static int fact(int n){ if(n==0) return 1; return p=n*fact(n-1); } //System.out.println(fact); } // above correction done. //Edited by - bakkesh
12th Apr 2017, 2:49 AM
Manmohan
Manmohan - avatar