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
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.
Hands-On GUI Application Development in Go by Andrew Williams(1545)
Unreal Engine 4 Virtual Reality Projects by Kevin Mack(1452)
Hands-On C++ Game Animation Programming by Gabor Szauer(1290)
Learn WebAssembly by Mike Rourke(1185)
Learn OpenCV 4 by Building Projects by David Millán Escrivá(1139)
Unreal Engine 4 Shaders and Effects Cookbook by Brais Brenlla Ramos(1122)
Hands-On Microservices with Rust by Denis Kolodin(1119)
C++ Concurrency in Action: Practical Multithreading by Anthony Williams(857)
C++ Data Structures and Algorithm Design Principles by John Carey Shreyans Doshi & Payas Rajan(786)
Advanced C++ by Gazihan Alankus Olena Lizina Rakesh Mane Vivek Nagarajan and Brian Price(775)
Beyond the C++ Standard Library: An Introduction to Boost by Björn Karlsson(762)
The C++ Standard Library: A Tutorial and Reference (2nd Edition) by Josuttis Nicolai M(705)
C++ All-In-One Desk Reference For Dummies by John Paul Mueller(653)
Make an Arduino-Controlled Robot by Michael Margolis(625)
C++ Crash Course by Josh Lospinoso(555)
Learning DCOM by Thai Thuan(531)
Data Structures and Algorithm Analysis in C (1st Edition) by Mark Allen Weiss(509)
UML 2.0 in a Nutshell by Dan Pilone & Neil Pitman(495)
Atmospheric Monitoring with Arduino by Patrick Di Justo & Emily Gertz(493)
