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:
Thread 'Is this public key encryption?'
I've tried to intuit public key encryption but never quite managed. But this seems to wrap it up in a bow. This seems to be a very elegant way of transmitting a message publicly that only the sender and receiver can decipher. Is this how PKE works? No, it cant be. In the above case, the requester knows the target's "secret" key - because they have his ID, and therefore knows his birthdate.
I tried a web search "the loss of programming ", and found an article saying that all aspects of writing, developing, and testing software programs will one day all be handled through artificial intelligence. One must wonder then, who is responsible. WHO is responsible for any problems, bugs, deficiencies, or whatever malfunctions which the programs make their users endure? Things may work wrong however the "wrong" happens. AI needs to fix the problems for the users. Any way to...

Similar threads

Back
Top