C/C++ What Are the Benefits and Uses of Recursive Functions?

  • Thread starter Thread starter ineedhelpnow
  • Start date Start date
  • Tags Tags
    Functions
Click For Summary
Recursion involves functions that call themselves, which can be useful for solving problems that can be broken down into smaller, similar subproblems. A key aspect of recursion is establishing a terminating condition to prevent infinite loops, typically implemented using an if-else statement. For example, the factorial function demonstrates recursion: it defines factorial(1) as 1 and factorial(n) as factorial(n-1) multiplied by n for n greater than 1. The factorial function can be coded recursively in C, but it can also be converted to an iterative version using a loop. However, certain problems, especially those involving mutually recursive functions like expression parsing, may be more complex and better suited for recursive solutions.
ineedhelpnow
Messages
649
Reaction score
0
Hi :o

Recursion. Recursive functions. What are they used for and how they helpful?
 
Technology news on Phys.org
Technically, a recursive function is a function that makes a call to itself. To prevent infinite recursion, you need an if-else statement (of some sort) where one branch makes a recursive call, and the other branch does not. This branch that does not make a recursive call becomes the terminating condition. Mathematically it should have a recursive definition.

for an example we know

factorial (1) =1

factorial ( n) = factorial (n-1) * n for n > 1

this can be coded as

#include <stdio.h>

int factorial(unsigned int i)
{
if(i <= 1)
{
return 1;
}
return i * factorial(i - 1);
}

this can be converted to

int factorial(unsigned int i)
{
int product = 1;
while (i) {
product = product * i;
i--;
}
return product;
}SOme times it may not be easy to convert particlularly for mutually recursive function say parsing of expression and so on and it is best to leave it as it is.
 
Last edited:
Learn If you want to write code for Python Machine learning, AI Statistics/data analysis Scientific research Web application servers Some microcontrollers JavaScript/Node JS/TypeScript Web sites Web application servers C# Games (Unity) Consumer applications (Windows) Business applications C++ Games (Unreal Engine) Operating systems, device drivers Microcontrollers/embedded systems Consumer applications (Linux) Some more tips: Do not learn C++ (or any other dialect of C) as a...

Similar threads

Replies
18
Views
3K
  • · Replies 62 ·
3
Replies
62
Views
13K
  • · Replies 1 ·
Replies
1
Views
1K
  • · Replies 12 ·
Replies
12
Views
3K
  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 4 ·
Replies
4
Views
3K
  • · Replies 11 ·
Replies
11
Views
1K
  • · Replies 17 ·
Replies
17
Views
3K
  • · Replies 8 ·
Replies
8
Views
1K