473,569 Members | 2,845 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Recursivity Explanation in c++

37 New Member
Hi

Say we enter 4 at the prompt, factorial function is called with 4 as the argument. Now 4*factorial(4-1). The function calls itself now. So what happens at this point?

1.Does it return anything to main or does it call the function again from within?

2. Where would it hold the 4, the 3, and the 2 to multiply it to get 24? In other words, what is the step by step procedure to get 24?

Thanks a lot.


Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. long factorial (long x)
  5. {
  6.   if (x > 1)
  7.    return (x * factorial (x-1)); //calling the function from within the function.
  8.   else
  9.    return (1);
  10. }
  11.  
  12. int main ()
  13. {
  14.   long num;
  15.   cout << "Enter a number: ";
  16.   cin >> num;
  17.   cout << num << "! = " << factorial (num);
  18.   return 0;
  19. }
Apr 28 '10 #1
9 1937
newb16
687 Contributor
1. It will return to main after everything is calculated.
2. Most likely on the stack, where local variables and passed parameters are stored*. When it multiplies 2 by 1, there are three stack frames with local variables - for factorial called with argument equal 4,3, and 2.

Yes, they can be also passed in registers.
Apr 28 '10 #2
code green
1,726 Recognized Expert Top Contributor
Logically it would use the mathematical BODMAS rule.
So the command in the bracket would be implemented first.
So factorial would be called again and again until !(x>1).

Nothing could be returned to main until !(x>1).then the else is called.
I don't believe this function works. Does it?

It looks like it is missing a static
Apr 28 '10 #3
Banfa
9,065 Recognized Expert Moderator Expert
Looks like it should work to me, what makes you think it wont.
Apr 28 '10 #4
Dheeraj Joshi
1,123 Recognized Expert Top Contributor
It looks like it is missing a static
You mean static keyword for the function?

Regards
Dheeraj Joshi
Apr 28 '10 #5
code green
1,726 Recognized Expert Top Contributor
It looks like the value of (x-1) is continually passed to factorial()
without even the x * being implemented.

I mean a static variable to hold the value of x.
Or pass x as a pointer or reference.

I am beginning to doubt myself. Am I missing something here?
Apr 28 '10 #6
Dheeraj Joshi
1,123 Recognized Expert Top Contributor
It compiles and run's properly. No need of static, for variable x i think.

Regards
Dheeraj Joshi
Apr 28 '10 #7
code green
1,726 Recognized Expert Top Contributor
Apologies. I am seeing brackets that are not even there.
Apr 28 '10 #8
donbock
2,426 Recognized Expert Top Contributor
Use of static or global variables inside a recursive function is typically ill-advised.
Apr 28 '10 #9
Deanm007
37 New Member
Well, I just got here but it appears someone already chose newb16 as best answer for me. LOL. This is too funny. Anyway, it is the best answer. Thanks to everyone for chipping in.. By the way, it does compile and run.
Apr 28 '10 #10

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

Similar topics

2
4751
by: Swartz | last post by:
Hi all. I'm building a development webserver (redhat-based). I'm trying to compile PHP (v4.3.4 if anyone cares) with all the features I might require in the near future. I've ran into a problem with trying to understand what all those ./configure options do. Some of them are fairly straight forward and need no explanation at all, but...
0
1220
by: Premshree Pillai | last post by:
Hey, For the uninitiated: an explanation of makeExe.py (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/266471), in the form of an article, “Create Python Executables Automatically”, is available at DevX: http://www.devx.com/opensource/Article/20247 -Premshree Pillai http://www.qiksearch.com/]
3
2507
by: David MacQuigg | last post by:
I am writing a chapter for teaching OOP in Python. This chapter is intended as a brief introduction to replace the more complete discussion in Learning Python, 2nd ed, pp. 295-390. I need to explain instance variables. What I'm looking for is the best compromise between brevity and a full explanation. The students are non-CIS technical...
2
507
by: MatthewRoberts | last post by:
Howdy All, I have a Windows Service that often stops in its tracks with no exception and no explanation on our QA system. During testing on the development machine, it can handle any workload, and complete with no problems. Even during testing on another test machine, it can handle any workload, and complete with no problems. This...
1
3332
by: jimfortune | last post by:
From: http://groups-beta.google.com/group/comp.databases.ms-access/msg/769e67e3d0f97a90?hl=en& Errata: 19 solar years = 2939.6018 days should be 19 solar years = 6939.6018 days Easter Function explanation Part II
2
2418
by: Dave Taylor | last post by:
Is there a decent explanation of how menu merging with MDI forms work in VB.NET? I've read through the online help and it still seems that whenever I change menus around or whatever, it breaks everything. VB6, as repetitive as it was to retype menus, was at least consistent. It seems that VB.NET throws menu items wherever it feels like.
12
2094
by: jacob navia | last post by:
Hi I am writing this tutorial stuff again in the holidays and I came across this problem: The "width" field in printf is a minimum width. Printf will not truncate a field. for instance: #include <stdio.h> int main(void) {
4
1529
by: dismantle | last post by:
Hi all, this is my 3rd week in studying VB codes and i came across with this codes from a online tutorial about classes. Public Function MiddleInitial() As String MiddleInitial = Left$(middleNameValue, 1) End Function Public Function MiddleInitial(ByVal period As Boolean) As String MiddleInitial = Left$(middleNameValue, 1) & "."
6
2466
by: WolfgangS | last post by:
Ok first off, i am a total beginner at this groups stuff and i have no clue how this works. This is probabaly the wrong group for my problem but i will post it anyways. Learning by doing right? I will post a code snippet and explain my problem. I cant seem to find a logical explanation why this problem would occur after trying to figure it...
16
1648
by: DamienS | last post by:
In the interests of me saving hair, can someone please explain to me what's going on below? Why doesn't == work in comparing two int's when cast as objects? They're the same type. Note that it worked for strings. Thanks in advance, Damien
0
7695
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...
0
8119
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7668
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7964
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...
0
6281
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...
0
3637
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2111
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1209
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
936
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...

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.