+ 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); }
3 Answers
+ 13
You forgot the case n==1, which is 1.
+ 2
if (n==0 || n==1) return 1;
+ 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