# factorial using recursion

• 08-12-2013, 07:47 PM
rajeev
factorial using recursion
this is a very easy program ......... i know but i have doubt in control flow plz explain. what i know is first we give input n,then through factorial method it is passing to static factorial method which is defined out side main method ,there it is checking if n equals to 1 return 1 otherwise it is entering to else block........from there i dont know how it is working plz..explain.i read recursion ...... i understood it but it is not working....

import java.util.Scanner;

public class Test11 {
public static void main(String[] args) {

System.out.print("enter no:");
Scanner sc=new Scanner(System.in);
int n =sc.nextInt();

int f=factorial(n);
System.out.println(f);
}

static int factorial(int n){
if (n==0) {
return 1;
}
else{
return n*factorial(n-1);
}
}
}
• 08-12-2013, 08:09 PM
jim829
Re: factorial using recursion
The best way to figure this out is to simply write down the values on paper and see how they change. Just remember that upon each return you need to calculate n * whatever factorial(n-1) returned.

Regards,
Jim
• 08-12-2013, 09:33 PM
DarrylBurke
Re: factorial using recursion
You didn't bother to read the responses on your earlier thread and you expect to get help this time round?

db
• 08-13-2013, 03:43 AM
rajeev
Re: factorial using recursion
thanks jim829

i modified the program and in the middle written print i got output like this but still i am not understanding how it is returning and calculating.help me........

import java.util.Scanner;

public class Test11 {
public static void main(String[] args) {

System.out.print("enter no:");
Scanner sc=new Scanner(System.in);
int n =sc.nextInt();

int f=factorial(n);
System.out.println(f);
}

static int factorial(int n){
if (n==0) {
return 1;
}
else{
System.out.println(n*factorial(n-1));
return n*factorial(n-1);
}
}
}

output
==========

enter no:5
1
2
1
6
1
2
1
24
1
2
1
6
1
2
1
120
1
2
1
6
1
2
1
24
1
2
1
6
1
2
1
120
• 08-13-2013, 04:27 AM
jim829
Re: factorial using recursion
Assume 4!
You call it with 4
internally it calls itself with
4-1 or 3
then 3-1 or 2
then 2-1 or 1
then 1-1 or 0

then it returns 1
then it returns 1 * 1 or 1
then it returns 2 * 1 or 2
then it returns 3 * 2 or 6
then it returns 4 * 6 or 24

Done!

Regards,
Jim