473,788 Members | 2,715 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

recursion

1 New Member
hi, i need a recursion program. i am very poor in programmin so i want to learn from the examples.
Apr 21 '08 #1
7 1434
Banfa
9,065 Recognized Expert Moderator Expert
Recursion is just a function that calls itself either directly or indirectly. There must be a condition that stops the recursion otherwise you end up with an infinite recursion which will ultimately destroy the program stack and cause a crash.

I have seen it written that any formula that can be implemented as a for loop can be implemented as a recursive function and vice versa but I have not put any effort into trying to verify this.

Expand|Select|Wrap|Line Numbers
  1. void RecursiveFunction(unsigned x, unsigned max)
  2. {
  3.     if (x >= max)
  4.     {
  5.         return;
  6.     }
  7.  
  8.     // Do something here
  9.  
  10.     RecursiveFunction(x+1, max);
  11. }
  12.  
  13. int main()
  14. {
  15.     RecursiveFunction(0, 20);
  16. }
  17.  
Apr 21 '08 #2
JosAH
11,448 Recognized Expert MVP
I have seen it written that any formula that can be implemented as a for loop can be implemented as a recursive function and vice versa but I have not put any effort into trying to verify this.
That's only true for the 'primitive recursive functions'; for the 'total recursive functions
or partial recursive functions' you need an explicit stack. e.g. try to implement
the Ackerman function without using a stack:

Expand|Select|Wrap|Line Numbers
  1. int Ack(int n, int m) {
  2.    if (n == 0) return m+1;
  3.    if (m == 0) return Ack(n-1, 1);
  4.    return Ack(n-1, Ack(n, m-1));
  5. }
  6.  
a terrible little monster that is ;-)

kind regards,

Jos
Apr 21 '08 #3
Nepomuk
3,112 Recognized Expert Specialist
A very common example for recursion is the calculation of the factorial of a number.
In case you don't know, the factorial of a positive integer n is:
n! = n * (n - 1) * ... * 2 * 1
and 0! = 1 per definition.

In pseudo code, that is:
Expand|Select|Wrap|Line Numbers
  1. fac(int x)
  2. {
  3.         if( x is 0 or 1 ) return 1
  4.         else return x * fac( x - 1 )
  5. }
  6.  
A very nice form of recursion (at least, if you want to transform your method to a loop or vice verca) is endrecursive recursion. Here's an example:
Expand|Select|Wrap|Line Numbers
  1. endrecursive_fac(int x, int y = 1)
  2. {
  3.         if( x is 0 or 1 ) return y
  4.         else return endrecursive_fac( x - 1 ,  y * x )
  5. }
  6.  
As you may see, the last thing that is done in the method is the recursive call. (While in the first example, the last thing done was the multiplikation x * fac( x - 1 ).)
As Jos pointed out, you can't do every translation between loops and recursions and in many cases loops are more difficult to write, but much more effective in terms of time it takes to calculate, memory used etc. But recursion often looks much more elegant. ^^

Hope you understand recursion a little better now.

Greetings,
Nepomuk
Apr 21 '08 #4
gsi
51 New Member
Hi Jos,
This question is a bit irrelevant to the OP's post but just curious, the Ackermann function that you have posted is supposed to return the result when m is towered n times exponentially ....(i.e ) for Ack(3,3) the result should be 3 raised to 3 raised to 3 ? . Please advice.

thanks in advance,
Gsi.
Apr 22 '08 #5
Nepomuk
3,112 Recognized Expert Specialist
Hi Jos,
This question is a bit irrelevant to the OP's post but just curious, the Ackermann function that you have posted is supposed to return the result when m is towered n times exponentially ....(i.e ) for Ack(3,3) the result should be 3 raised to 3 raised to 3 ? . Please advice.

thanks in advance,
Gsi.
Actually, the Ackermann function is quite an evil thing, when entering even small values. On Wikipeida you can find an article with a table of some values - according to them Ack(3,3) is 61. Here's a little calculation:
Ack(3,3)
=Ack(2,Ack(3,2) )
=Ack(2,Ack(2,Ac k(3,1)))
=Ack(2,Ack(2,Ac k(2,Ack(3,0))))
=Ack(2,Ack(2,Ac k(2,Ack(2,1))))
=Ack(2,Ack(2,Ac k(2,Ack(1,Ack(2 ,0)))))
=Ack(2,Ack(2,Ac k(2,Ack(1,Ack(1 ,1)))))
=Ack(2,Ack(2,Ac k(2,Ack(1,Ack(1 ,Ack(1,0))))))
=Ack(2,Ack(2,Ac k(2,Ack(1,Ack(1 ,Ack(0,1))))))
=Ack(2,Ack(2,Ac k(2,Ack(1,Ack(1 ,2)))))
=Ack(2,Ack(2,Ac k(2,Ack(1,Ack(0 ,Ack(1,1))))))
=Ack(2,Ack(2,Ac k(2,Ack(1,Ack(0 ,Ack(0,Ack(1,0) ))))))
=Ack(2,Ack(2,Ac k(2,Ack(1,Ack(0 ,Ack(0,Ack(0,1) ))))))
=Ack(2,Ack(2,Ac k(2,Ack(1,Ack(0 ,Ack(0,2))))))
=...
As you see, it gets pretty extreme - much more extreme than just exponential growth! There are some more examples on that Wikipedia page.

Greetings,
Nepomuk
Apr 22 '08 #6
JosAH
11,448 Recognized Expert MVP
Hi Jos,
This question is a bit irrelevant to the OP's post but just curious, the Ackermann function that you have posted is supposed to return the result when m is towered n times exponentially ....(i.e ) for Ack(3,3) the result should be 3 raised to 3 raised to 3 ? . Please advice.

thanks in advance,
Gsi.
According to my quick implementation Ack(3, 3) == 61 != 27. Have a look here.

kind regards,

Jos
Apr 22 '08 #7
gsi
51 New Member
Thanks guys for the info.

Gsi.
Apr 22 '08 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

5
3424
by: Peri | last post by:
I'm trying to create Python parser/interpreter using ANTLR. Reading grammar from language refference I found: or_expr::= xor_expr | or_expr "|" xor_expr For me it looks like infinite recursion. And so it says ANTLR. Maybe I don't understand EBNF notation. For me it should look like this. or_expr::= xor_expr | xor_expr "|" xor_expr and in ANTLR grammar file like this:
12
2768
by: da Vinci | last post by:
Greetings. I want to get everyone's opinion on the use of recursion. We covered it in class tonight and I want a good solid answer from people in the "know" on how well recursion is accepted in modern day applications. Should we readily use it when we can or only when absolutly forced to use it?
43
4172
by: Lorenzo Villari | last post by:
I've tried to transform this into a not recursive version but without luck... #include <stdio.h> void countdown(int p) { int x;
2
1569
by: Csaba Gabor | last post by:
I suppose spring fever has hit at alt.math.undergrad since I didn't get any rise from them when I posted this a week ago, so I am reposting this to some of my favorite programming groups: I'm looking for problems that have double (or more) recursion, where the split is not clean (ie. where there may be overlap). Let's call this overlapped recursion, where the
75
5644
by: Sathyaish | last post by:
Can every problem that has an iterative solution also be expressed in terms of a recursive solution? I tried one example, and am in the process of trying out more examples, increasing their complexity as I go. Here's a simple one I tried out: #include<stdio.h> /* To compare the the time and space cost of iteration against
19
2288
by: Kay Schluehr | last post by:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691
18
3724
by: MTD | last post by:
Hello all, I've been messing about for fun creating a trial division factorizing function and I'm naturally interested in optimising it as much as possible. I've been told that iteration in python is generally more time-efficient than recursion. Is that true? Here is my algorithm as it stands. Any suggestions appreciated!
13
4528
by: robert | last post by:
My code does recursion loops through a couple of functions. Due to problematic I/O input this leads sometimes to "endless" recursions and after expensive I/O to the Python recursion exception. What would be a good method to detect recursion loops and stop it by user-Exception (after N passes or some complex criteria) without passing a recursion counter parameter through all the funcs? Robert
20
3007
by: athar.mirchi | last post by:
..plz define it.
35
4741
by: Muzammil | last post by:
int harmonic(int n) { if (n=1) { return 1; } else { return harmonic(n-1)+1/n; } } can any help me ??
0
9656
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10366
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9967
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8993
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6750
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5399
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5536
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3674
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2894
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.