C++ Function Recursive factorial function

Description

C++ Function Recursive factorial function

#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;

int factorial(int n) throw (string){
    if (n < 0){
        throw string("Argument for factorial negative");
    }// w  w  w. ja v a2s.co m

    int accum = 1;
    
    while(n > 0){
        accum *= n;
        n--;
    }
    return accum;
}

int main(int nNumberofArgs, char* pszArgs[])
{
    try
    {
        cout << "Factorial of 3 is " << factorial(3) << endl;

        // this will generate an exception
        cout << "Factorial of -1 is " << factorial(-1) << endl;

    }catch(string error){
        cout << "Error occurred: " << error << endl;
    }
    catch(...)
    {
        cout << "Default catch " << endl;
    }
    return 0;
}



PreviousNext

Related