C++: A Comprehensive Beginner’s Guide to Learn About the Realms of C++ From A-Z by Smith Benjamin

C++: A Comprehensive Beginner’s Guide to Learn About the Realms of C++ From A-Z by Smith Benjamin

Author:Smith, Benjamin [Smith, Benjamin]
Language: eng
Format: epub
Published: 2020-04-24T16:00:00+00:00


Recursion

The function factorial is widely used in combinatorial analysis (counting theory in mathematics), probability theory, and statistics. The factorial of n is most times expressed as n!. The factorial for nonnegative integers can be expressed as:

n! = n . (n – 1) . (n – 2) . (n – 3) . . . 2 . 1

Mathematically, the definition of factorial is recursive because the ! function is being defined, but ! is also used in the definition. In C++, a function can be defined recursively as well. Consider code 5.10, which includes a factorial function that exactly models the mathematical definition.

Code 5.10

#include <iostream>

// Factorial (n)

// Computes n!

// Return the factorial of n;

int factorial(int n) {

if (n == 0)

return 1;

else

return n * factorial(n - 1);

}

int main() {

// Try out the factorial function

std::cout << " 0! = " << factorial(0) << '\n';

std::cout << " 1! = " << factorial(1) << '\n';

std::cout << " 6! = " << factorial(6) << '\n';

std::cout << "10! = " << factorial(10) << '\n';

}

So, a simple correct recursive function definition is based on four key concepts:

The function must not be able to call itself within a definition optionally. This is also known as the base case.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.