1. Member
Join Date
Jul 2013
Location
india
Posts
15
Rep Power
0

## 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);
}
}
}

2. Senior Member
Join Date
Jan 2013
Location
Northern Virginia, United States
Posts
6,226
Rep Power
14

## 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

3. ## 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

4. Member
Join Date
Jul 2013
Location
india
Posts
15
Rep Power
0

## 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

5. Senior Member
Join Date
Jan 2013
Location
Northern Virginia, United States
Posts
6,226
Rep Power
14

## 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

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•