Factorial through recursion

1217 views c++
4

It's a program of finding factorial using recursion & I don't know why this program is giving wrong output.

#include<iostream>
#include<conio.h>
using namespace std;
class factorial
{
    public:
    int fact(int n)
    {
        if (n==0)
        {
        cout<<"1";
        }
        else
        return n * fact(n-1);       
    }
};
int main()
{
    factorial s;
    s.fact(5);
    getch();
    return 0;
}

answered question

Hint: what is your fact function returning?

Your development environment likely comes with a debugging tool, and if it does not, get one that does. You can use a debugger to control the execution of your program, running it instruction by instruction if you have to, and inspect the the variables affected as you step. When you see the program do something it shouldn't have, you have found a bug.

Even when your program compiles, check the output for warnings. Errors prevent compilation, but warnings let you know that even though the program is grammatically correct, the logic probably isn't. Warnings are the first line of defense against simple logic errors like typos, ignored parameters, and forgotten return statements.

And besides the return problem mentioned above, what are you printing? This problem could be easily solved with a little rubber duck debugging.

Your recent edit is better, but a function must have a return statement (or throw an exception) on all paths that exit the function. Once the result is returned, print the result.

-Wall -Werror if you're using gcc. Your function doesn't return an int if n==0, and luckily the compiler can tell you this automatically. Base cases are necessary for recursion to work.

1 Answer

0

The most obvious problem that is your program is ill-formed: the int fact(int n) function doesn't return a value if n == 0.

posted this

Have an answer?

JD

Please login first before posting an answer.