Someone help me in writing this code. Not getting the required output

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)





Input (stdin)
Your Output (stdout)
~ no response on stdout ~

Expected Output

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


if( n==2 )

return 2


if( n = 3 )

return 6


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.

Thanks Got It

1 Like