![]() |
C/C++, KDEVELOP |
|---|
BasicsProgram FlowFunctionsClasses and ObjectsX WindowKDevelop----------------- © Alfred Nussbaumer Updated: 09 December 2021 ----------------- |
Recursive Functions"Recursion occurs when a function calls itself" - you know that famous sentence ;-). For example, we calculate the factorial of the number 4: 4 = 4*3*2*1. Here we can do the multiplication recursively: Multiply the number 4 with the result of the factorial of 3; to get the factorial of 3 multiply 3 with the factorial of 2; to get the factorial of 2 multiply 2 with the factorial of 1 which is just 1. Here the recursion ends... Look at the following code:
#include <iostream.h>
double f(int n);
int main() {
int input = 4;
cout << input << "! = " << f(input) << endl;
return 0;
}
double f(int n) {
if (n>1) return n*f(n-1);
return 1;
}
At first you define a so called "function prototype" so you can use the function within main(). The function f(int n) calls itself until 1 is reached... nus@mail:~/ccpp > ./factorial 4! = 24 |