Related Articles

# Recursive lambda expressions in C++

• Last Updated : 22 Jul, 2021

A recursive lambda expression is the process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. Using a recursive algorithm, certain problems can be solved quite easily. Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of Graph, etc.

A recursive function is a kind of loop structure only. The difference is it maintains a memory stack on its own. Obviously, it must have a break condition like for and while loop. Hence, the recursive function has the following structure-

```function name(arguments)
{
a base case (a breaking condition)
recursive code (the actual logic)
}```
```int fact(int n)
{
// Base Case
if (n < = 1)
return 1;
else
return n * fact(n - 1);
}```

C++ 11 introduced lambda expressions to allow us to write an inline function that can be used for short snippets of code that are not going to be reused and not worth naming. In its simplest form, the lambda expression can be defined as follows:

```[ capture clause ] (parameters) -> return-type
{
definition of method
} ```

Program 1:

Below is the program for the lambda expressions in the sort() method in C++:

## C++14

 `// C++ program to implement``// the above approach``#include ``using` `namespace` `std;` `// Driver code``int` `main()``{``    ``int` `arr[] = { 5, 2, 1, 4, 3 };``    ``sort(arr, arr + 5, [](``int``& a,``                          ``int``& b) {``        ``// Instant lambda function``        ``return` `a > b;``    ``});` `    ``for` `(``int` `i = 0; i < 5; i++)``        ``cout << arr[i] << ``" "``;``    ``return` `0;``}`
Output
`5 4 3 2 1 `

Explanation: Here, the instant lambda function is used, which cannot be used in another sorting method, i.e., the same code needs to be written again. This lambda expression exists only during the execution of the sort() method. But it is possible to store the lambda expression in a variable (better to call it a function) as well, like below. By storing it, it can be used further, and of course, perform recursion also.

Program 2:

## C++14

 `// C++ program to implement``// the above approach``#include ``using` `namespace` `std;` `// Stored lambda expression``auto` `cmp = [](``int``& a, ``int``& b) {``    ``return` `a > b;``};` `// Driver code``int` `main()``{``    ``int` `arr[] = { 5, 2, 3, 1, 4 };``    ``sort(arr, arr + 5, cmp);` `    ``for` `(``int` `i = 0; i < 5; i++)``        ``cout << arr[i] << ``" "``;` `    ``return` `0;``}`
Output
`5 4 3 2 1 `

Explanation: Here, auto cmp is the lambda stored function that can be used in as many sorting methods.

Recursion Using Lambda: Let’s discuss the concept of recursion and lambda expressions together by considering the recursive function below:

Program 3:

## C++14

 `// C++ program to implement``// the above approach``#include ``using` `namespace` `std;` `// Recursive function to print``// the digits of a number``void` `printReverse(``int` `n)``{``    ``if` `(n == 0)``        ``return``;``    ``cout << n % 10 << ``" "``;``    ``printReverse(n / 10);``}` `// Driver code``int` `main()``{``    ``int` `n = 12345;``    ``printReverse(n);``    ``return` `0;``}`
Output

`5 4 3 2 1 `

Explanation: Above is the function which prints the digits of a number in reverse order, using recursion. The same can be done using the lambda expression.

Program 4:

Below is the C++ program to implement the above code using lambda expressions:

## C++14

 `// C++ program to implement``// the above approach``#include ``using` `namespace` `std;` `// Driver code``int` `main()``{``    ``int` `n = 12345;` `    ``// Recursive lambda function to``    ``// print the digits of a number``    ``auto` `printReverse = [&]() {``        ``if` `(n == 0)``            ``return``;``        ``cout << n % 10;``        ``n = n / 10;``        ``printReverse();` `        ``// As it is a part of main body,``        ``// semicolon is must``    ``};` `    ``printReverse();``    ``return` `0;``}`

Output: Oops, the function, defined using auto return type, must be deducted first (Compiler must be able to determine whether the return type auto can be converted into void or int or something else)

Explanation: Here, how the function is going to recognize the variable n, even if it is not passed as an argument. A lambda with an empty capture clause [ ] can access only those variables which are local to it. Here, the capture close [&] is used, which allows the function to access the variable n ( The actual value of variable n is being changed). There are two ways to resolve the error above:

1. By passing the function itself, to the function argument:

Below is the C++ program to implement the above concept:

Program 5:

## C++14

 `// C++ program to implement``// the above approach``#include ``using` `namespace` `std;` `// Driver code``int` `main()``{``    ``int` `n = 12345;` `    ``// Function itself as a parameter``    ``auto` `printReverse = [&](``auto``&& printReverse) {``        ``if` `(n == 0)``            ``return``;``        ``cout << n % 10 << ``" "``;``        ``n = n / 10;``        ``printReverse(printReverse);``    ``};` `    ``// Function as an argument``    ``printReverse(printReverse);``    ``return` `0;``}`
Output

`5 4 3 2 1 `

2. By declaring the function first:

Declaring a function means declaring its name and parameters type in order to inform a compiler that there is a function named xyz, which will write its body later.

Program 6:

Below is the C++ program to implement the above concept:

## C++

 `// C++ program to implement``// the above approach``#include ``using` `namespace` `std;` `// Declaring of a function``void` `declaringFunction(string s);` `// Driver code``int` `main()``{``    ``declaringFunction(``"Hello I am learning how to declare a function"``);``    ``return` `0;``}` `// Body of a function``void` `declaringFunction(string s)``{``    ``cout << s;``}`
Output
`Hello I am learning how to declare a function`

Program 7:

Since it is a lambda function, there must be some unique way of declaring the function. Below is the C++ program for the same:

## C++14

 `// C++ program to implement``// the above approach``#include ``#include ``using` `namespace` `std;` `// Driver code``int` `main()``{``    ``int` `n = 12345;` `    ``// Function < return type (parameter``    ``// types) > functionName` `    ``// Don't forget to include functional``    ``// header` `    ``// Declaration``    ``function<``void``()> printReverse;` `    ``printReverse = [&]() {``        ``if` `(n == 0)``            ``return``;` `        ``// Defination``        ``cout << n % 10 << ``" "``;``        ``n /= 10;``        ``printReverse();``    ``};` `    ``printReverse();``}`
Output
`5 4 3 2 1 `

Explanation: In the above code, first, the function printReverse is declared, then we have defined its body. Instead of that, we can directly declare the function and its body along with, which is known as defining a function. Below is the C++ program to implement the above approach:

Program 8:

## C++14

 `// C++ program to implement``// the above approach``#include ``#include ``using` `namespace` `std;` `// Driver code``int` `main()``{``    ``int` `n = 12345;` `    ``// Function < return type (parameter``    ``// types) > functionName``    ``function<``void``()> printReverse = [&]() {``        ``if` `(n == 0)``            ``return``;` `        ``// Declaration + Body``        ``cout << n % 10 << ``" "``;``        ``n /= 10;``        ``printReverse();``    ``};` `    ``printReverse();``}`
Output
`5 4 3 2 1 `

Examples: Below are some examples of recursive functions using lambda expressions.

Program 9:

## C++14

 `// C++ program to implement``// the above approach``#include ``using` `namespace` `std;` `// Driver code``int` `main()``{``    ``int` `n = 6;` `    ``// Recursive Lambda function to``    ``// find the factorial of a number``    ``auto` `factorial = [&](``auto``&& factorial) {``        ``if` `(n == 1)``            ``return` `n;``        ``return` `n-- * factorial(factorial);``    ``};` `    ``auto` `factorial2 = [](``int` `n, ``auto``&& factorial2) {``        ``if` `(n == 1)``            ``return` `n;``        ``return` `n * factorial2(n - 1, factorial2);``    ``};` `    ``// Given n = 6``    ``cout << factorial(factorial) << endl;` `    ``// Given n = 5``    ``cout << factorial2(5, factorial2);``}`
Output
```720
120```

Explanation: In the factorial function, n is directly accessed using the [&] capture clause. In the factorial2 function, n is passed as an argument. Hence, there is no need for the [&] clause.

Program 10:

## C++14

 `// C++ program to implement``// the above approach``#include ``using` `namespace` `std;` `// Driver code``int` `main()``{``    ``// Sorted array``    ``int` `arr[] = { 1, 2, 5, 7, 10, 12, 15 };``    ``int` `size = 7;` `    ``// Item to be searched``    ``int` `key = 10;` `    ``auto` `binarySearch = [&](``int` `startIndex,``                            ``int` `endIndex,``                            ``auto``&& binarySearch) {``        ``if` `(startIndex > endIndex)``            ``return` `-1;``        ``int` `midIndex = (startIndex + endIndex) / 2;``        ``if` `(arr[midIndex] == key)``            ``return` `midIndex;``        ``if` `(arr[midIndex] > key)``            ``return` `binarySearch(startIndex,``                                ``midIndex - 1,``                                ``binarySearch);``        ``if` `(arr[midIndex] < key)``            ``return` `binarySearch(midIndex + 1,``                                ``endIndex,``                                ``binarySearch);``        ``// Not found``        ``return` `-1;``    ``};` `    ``int` `index = binarySearch(0, size - 1,``                             ``binarySearch);``    ``if` `(index == -1)``        ``cout << ``"Not found"``;``    ``else``        ``cout << ``"Found on index "` `<< index;` `    ``return` `0;``}`
Output
`Found on index 4`
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up