Write a function factorial which gives the factorial of the given number using tail recursion.

```
object Result {
/*
* Complete the 'factorial' function below.
*
* The function accepts INTEGER input1 as parameter.
*/
def factorial(n: Int) =
{
// Put your code here
def iter(n:Int,accum:Int):Int =
if(n==0) accum else iter(n-1,n*accum)
iter(n,1)
}
}
```

```
Input (stdin)
5
Your Output (stdout)
~ no response on stdout ~
Expected Output
120
```

Hello @pavan1043

Your function is correct in its logic. The issue seems to be that thisâ€¦ homework? you are doing requires interacting with standard input and output for grading. So itâ€™s hard to say anything else without seeing the rest of the code, or the assignment instructions. Do they want you to print the result to standard output? It says â€śThe function accepts INTEGER input1 as parameter.â€ť Where in the code is it read from standard input? Are you submitting this homework to a website for grading? Or are you running it on your own PC?

1 Like

def iter(n:Int,accum:Int):Int =

if( n < 0 )

throw RuntimeException(â€śIllegal Parameter: must be >= 0â€ť)

else // Handle the base cases first

if( (n == 0) || (n == 1))

return 1

else

if( n==2 )

return 2

else

if( n = 3 )

return 6

else

return n*factorial(n-1)

Yes running in my own PC.

The output has to be printed to the stdout,

and the main function is already given by them.

Im not getting how to print the result to the stdout,

I am still confused about the instructions, but letâ€™s give it a try.

Keep your `iter`

function as it is, but instead of `iter(n, 1)`

at the end, use `println(iter(input1, 1))`

instead.

You are absolutely correct.

I got the desired output.

Can you please explain it?

As I said before, you need to understand the instructions of the assignment. This has nothing to do with Scala.

Honestly I was just guessing.

It says â€śThe function accepts INTEGER input1 as parameter.â€ť So the grading system supplies the input number, which is stored in a variable named `input1`

which is then accessible to your function. That is the number you need to call your function with.

Then, using `println`

will put your result to standard output.