Demonstrating the recursive function factorial - C++ Data Structure

C++ examples for Data Structure:Algorithm

Description

Demonstrating the recursive function factorial

Demo Code

#include <iomanip>
#include <iostream>

unsigned long factorial(unsigned long);

int main(int argc, const char *argv[]) {
    // calculate factorials of 0 through 10
    for (int counter = 0; counter <= 10; ++counter) {
        std::cout << std::setw(2) << counter << "! = " << factorial(counter)
                  << std::endl;//www.ja v a 2 s .  c  o m
    }
    return 0;
}

unsigned long factorial(unsigned long number) {
    // base case
    if (number <= 1)
        return 1;
    else
        return number * factorial(number - 1);
}

Result


Related Tutorials