English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

example..
enter a number: 5

factorial of 5 is::::
1
2
6
24
120

but this codes only displays 120... what is mistake here??

import java.io.*;
public class Factorial
{
// Evaluate n!
public static long factorial( int n )
{
if( n <= 1 ) // base case
return 1;
else
return n * factorial( n - 1 );
}

// Simple test program
public static void main( String [ ] args )throws Exception
{
int num=0;

BufferedReader keith=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a number:");
num=Integer.parseInt(keith.readLine());
System.out.println(factorial(num));

}
}

2007-03-09 13:17:18 · 4 answers · asked by forest 1 in Computers & Internet Programming & Design

4 answers

You need to put a print statement inside of your factorial function if you want to print intermediate values. This will require a little thought, and some modification of the code.

Play with it for a while, and you'll see what's going on.

2007-03-09 13:22:13 · answer #1 · answered by arbeit 4 · 0 1

The problem is that you have just one print statement 'System.out.printin(...)'.

What happens here is that when you call the function 'factorial(n)' This recursive procedure is called and the recursion continues till the function returns a value to the 'main()' function. As you can see, in between there are no print statements. Hence, only the last answer.

To get the desired output just replace the function 'factorial with the following

public static long factorial( int n )
{
int temp;

if( n <= 1 ) // base case
{
System.out.println(n);
return 1;
}
else
{
temp = n * factorial( n - 1 );
System.out.println(temp);
return temp;
}
}

Also, this will give 120 twice. So just make a call in the main function, ie, 'factorial(n);' instead of 'System.out.println(factorial(n));'

This will solve your problem

2007-03-09 14:37:04 · answer #2 · answered by Sahil 2 · 0 0

Your code is getting cut off, but you're only printing the total.

If you want to print the intermediate results, add a println to the factorial function.

2007-03-09 13:29:38 · answer #3 · answered by Vegan 7 · 0 0

The code of conduct....lol

2007-03-09 13:20:59 · answer #4 · answered by Anonymous · 0 1

fedest.com, questions and answers