Last Updated:

Recursive functions with C++

recursive function in programming is understood as a function that calls itself. Recursive functions are most often used to compactly implement recursive algorithms. Classical recursive algorithms can be the exponentiation of a number to an integer positive power, the calculation of the factorial.

Let's move on to the example of applying a recursive function.

Task:

Calculate the factorial of the number n.

For reference: "The factorial of the number N is the product of all natural numbers from 1 to N"

 

Overloading functions

 

The C++ language allows you to associate different definitions with the same function name, which means that there can be several functions with the same name. They can have different numbers of parameters or different types of parameters. This feature is called function name overloading. Overloaded functions create when the same action should be performed on different types of input.

In the program text below, there are three functions named Pow. The first performs the operation of exponentiation of the real number to the fractional power n = k/m, where k and m are integers. The second raises the real number to the integer power n, and the third to the integer a to the integer power n1. Which function to call, the compiler determines by the type of actual parameters.

So, if a is a real number and k is an integer, then the Pow operator (a, k) will call the second function, since it has the heading float Pow(float a, int n). The pow((int) a, k) command will call the third function int Pow(int a, int n), since the real variable is converted to an integer type. The first function float Pow(float a, int k, int m) has three parameters, which means that it is accessed by the Pow command (a, k, m).

The result of the program:

In the early stages of programming, you probably won't need to overload functions, but in the future this procedure can be very useful for implementing a specific algorithm.