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

  • Thread starter Thread starter ineedhelpnow
  • Start date Start date
  • Tags Tags
    Functions
AI Thread 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:
Dear Peeps I have posted a few questions about programing on this sectio of the PF forum. I want to ask you veterans how you folks learn program in assembly and about computer architecture for the x86 family. In addition to finish learning C, I am also reading the book From bits to Gates to C and Beyond. In the book, it uses the mini LC3 assembly language. I also have books on assembly programming and computer architecture. The few famous ones i have are Computer Organization and...
I have a quick questions. I am going through a book on C programming on my own. Afterwards, I plan to go through something call data structures and algorithms on my own also in C. I also need to learn C++, Matlab and for personal interest Haskell. For the two topic of data structures and algorithms, I understand there are standard ones across all programming languages. After learning it through C, what would be the biggest issue when trying to implement the same data...

Similar threads

Back
Top