Search code examples
c++recursionfibonaccifactorial

Fibonacci series in C++ : Control reaches end of non-void function


while practicing recursive functions, I have written this code for fibonacci series and (factorial) the program does not run and shows the error "Control reaches end of non-void function" i suspect this is about the last iteration reaching zero and not knowing what to do into minus integers. I have tried return 0, return 1, but no good. any suggestions?

#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <ctime>
using namespace std;

int fib(int n) {
    int x;
        if(n<=1) {
            cout << "zero reached \n";
            x= 1;
        } else {
            x= fib(n-1)+fib(n-2);
            return x;
        }
    }




int factorial(int n){
    int x;
    if (n==0){
        x=1;
       }
    else {
            x=(n*factorial(n-1));
            return x;
        }

    }

Solution

  • Presumably the factorial function should be returning n * factorial(n-1) for n > 0.

    x=(factorial(n)*factorial(n-1)) should read x = n * factorial(n-1)