473,383 Members | 1,834 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,383 software developers and data experts.

recursive factorial function.

Hi,

Consider (factorial.cpp):
#include <iostream>
using namespace std;

double R=3.2; /* not used, but R is static because it is a global
variable (file scope) */

int F(int n); /* prototype */

int main()
{
int number;
cout << "Enter an integer of which to find the factorial of: ";
cin >> number;
cout << "Let's see what factorial(" << number << ") gives us. It gives
us: " << F(number) << endl;
}

int F(int i) /* automatic storage variable -> allocated in a stack (only
exists during execution of this function) */
{
static int count = 0; /* count on the other hand is static (explicitly)
-> exists during the whole program run */

++count; /* increment counter */

if (i==0)
{
cout << "Count = " << count << endl << endl;
return 1;
}

else
return i*F(--i);
}

I'm wondering why it gives me 0 as output (after count has been printed
to the screen)... Also: I'm not sure how to print out the correct
factorial value...
Best regards / Med venlig hilsen
Martin Jørgensen

--
---------------------------------------------------------------------------
Home of Martin Jørgensen - http://www.martinjoergensen.dk
Feb 20 '06 #1
11 4234
"Martin Jørgensen" writes:
Consider (factorial.cpp):
#include <iostream>
using namespace std;

double R=3.2; /* not used, but R is static because it is a global variable
(file scope) */

int F(int n); /* prototype */

int main()
{
int number;
cout << "Enter an integer of which to find the factorial of: ";
cin >> number;
cout << "Let's see what factorial(" << number << ") gives us. It gives us:
" << F(number) << endl;
}

int F(int i) /* automatic storage variable -> allocated in a stack (only
exists during execution of this function) */
{
static int count = 0; /* count on the other hand is static (explicitly) ->
exists during the whole program run */

++count; /* increment counter */

if (i==0)
{
cout << "Count = " << count << endl << endl;
return 1;
}

else
return i*F(--i);
}

I'm wondering why it gives me 0 as output (after count has been printed to
the screen)... Also: I'm not sure how to print out the correct factorial
value...


You're making it unnecessarily complicated. There is no need for a static
variable such as count. I suggest you start from scratch with that tidbit in
mind.
Feb 20 '06 #2
TB
Martin Jørgensen skrev:
Hi,

Consider (factorial.cpp):
#include <iostream>
using namespace std;

double R=3.2; /* not used, but R is static because it is a global
variable (file scope) */

int F(int n); /* prototype */

<snip>

int F(int i) /* automatic storage variable -> allocated in a stack (only
exists during execution of this function) */
{
static int count = 0; /* count on the other hand is static
(explicitly) -> exists during the whole program run */

++count; /* increment counter */

if (i==0)
{
cout << "Count = " << count << endl << endl;
return 1;
}

else
return i*F(--i);
return i * F(i - 1);

Why? On the second last recursion 'i' will equal 0, and
the statement

return 0 * F(0);

will return 0.
}


http://www.parashift.com/c++-faq-lit...html#faq-39.15

--
TB @ SWEDEN
Feb 20 '06 #3
"Martin Jørgensen" <un*********@spam.jay.net> wrote in message
news:b9************@news.tdc.dk...

....
return i*F(--i); I'm wondering why it gives me 0 as output (after count has been printed to
the screen)...


The expression i*F(--i) uses and modifies the value of i between two
sequence points. Therefore its behavior is undefined, and there is no point
in trying to find *any* other bugs in this program until this error is
corrected.
Feb 20 '06 #4
TB wrote:
else
return i*F(--i);


Is there even a sequence point in this line? I think this is UB.
Feb 20 '06 #5
TB
red floyd skrev:
TB wrote:
else
return i*F(--i);


Is there even a sequence point in this line? I think this is UB.


It's UB.

--
TB @ SWEDEN
Feb 20 '06 #6
TB wrote:
<snip>

int F(int i) /* automatic storage variable -> allocated in a stack
(only exists during execution of this function) */
{
static int count = 0; /* count on the other hand is static
(explicitly) -> exists during the whole program run */
++count; /* increment counter */
if (i==0)
{
cout << "Count = " << count << endl << endl;
return 1;
}

else
return i*F(--i);

return i * F(i - 1);

Why? On the second last recursion 'i' will equal 0, and
the statement

return 0 * F(0);

will return 0.


Wauw... It works...
http://www.parashift.com/c++-faq-lit...html#faq-39.15


So you're saying that with i*F(--i), the i will decrement at the same
time both inside and outside the parenthesis...? It says that a sequence
point could be: "after evaluation of all a function's parameters but
before the first expression within the function is executed (1.9p17)"

So it evaluates the "inner" function first. And then multiplying it with
0 since i decreased... Instead of evaluating i in "the outer function"
first, which is "i * F(something)"...
Best regards / Med venlig hilsen
Martin Jørgensen

--
---------------------------------------------------------------------------
Home of Martin Jørgensen - http://www.martinjoergensen.dk
Feb 20 '06 #7
In article <44************@news.tdc.dk>,
Martin Jørgensen <un*********@spam.jay.net> wrote:
TB wrote:
<snip>

int F(int i) /* automatic storage variable -> allocated in a stack
(only exists during execution of this function) */
{
static int count = 0; /* count on the other hand is static
(explicitly) -> exists during the whole program run */
++count; /* increment counter */
if (i==0)
{
cout << "Count = " << count << endl << endl;
return 1;
}

else
return i*F(--i);

return i * F(i - 1);

Why? On the second last recursion 'i' will equal 0, and
the statement

return 0 * F(0);

will return 0.


Wauw... It works...
http://www.parashift.com/c++-faq-lit...html#faq-39.15


So you're saying that with i*F(--i), the i will decrement at the same
time both inside and outside the parenthesis...? It says that a sequence
point could be: "after evaluation of all a function's parameters but
before the first expression within the function is executed (1.9p17)"

So it evaluates the "inner" function first. And then multiplying it with
0 since i decreased... Instead of evaluating i in "the outer function"
first, which is "i * F(something)"...


Your sequence points are fine. Trace through your program (by hand if
you have to) where i == 1. It returns: i * F( --i ); Which *first*
decrements i (to 0) then calls F( 0 ) (which returns 1) *then*
multiplies the return value by i (which was already decremented to 0.)
--
Magic depends on tradition and belief. It does not welcome observation,
nor does it profit by experiment. On the other hand, science is based
on experience; it is open to correction by observation and experiment.
Feb 20 '06 #8
Daniel T. wrote:
-snip-
Your sequence points are fine. Trace through your program (by hand if
you have to) where i == 1. It returns: i * F( --i ); Which *first*
decrements i (to 0) then calls F( 0 ) (which returns 1) *then*
multiplies the return value by i (which was already decremented to 0.)


Eerh, that's exactly my problem... Gotta figure out how to debug
properly using either xcode or gdb under mac os x... And it is causing
me some troubles... But it's piece of cake to debug under visual studio
(but that isn't on this computer I'm sitting at right now)...

But I'll try it out tomorrow...
Best regards / Med venlig hilsen
Martin Jørgensen

--
---------------------------------------------------------------------------
Home of Martin Jørgensen - http://www.martinjoergensen.dk
Feb 20 '06 #9
TB wrote:
red floyd skrev:
TB wrote:

else
return i*F(--i);


Is there even a sequence point in this line? I think this is UB.

It's UB.


What does UB mean?
Best regards / Med venlig hilsen
Martin Jørgensen

--
---------------------------------------------------------------------------
Home of Martin Jørgensen - http://www.martinjoergensen.dk
Feb 20 '06 #10
Martin Jørgensen wrote:
TB wrote:
red floyd skrev:
TB wrote:
> else
> return i*F(--i);

Is there even a sequence point in this line? I think this is UB.

It's UB.


What does UB mean?


Undefined Behaviour.

Ben Pope
--
I'm not just a number. To many, I'm known as a string...
Feb 20 '06 #11
UB: Utterly broken

Feb 20 '06 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
by: BQ | last post by:
Due to a lack of resources, I have to translate the following recursive function in its iterative form. It's a kind of dichotomic search. void SearchSlaves(unsigned long start_uid, unsigned long...
10
by: action! | last post by:
this is my C Programming homework, It wants me to input 10! and output the follow result 10! ¡õ 10 * 9! ¡õ 9 * 8! ..................
1
by: Dane Carty | last post by:
Hi, Using a TreeView component to create a tree of the directories within my file system. I can't get my head around the logic of the recursion. Anyone with a bigger brain is welcome to...
33
by: patrick_woflian | last post by:
hey guys, im just writing a basic calculation at the moment, before building on it for an A-Level piece of work. i can add/divide etc... two numbers together yet i am having a major problem with...
11
by: randomtalk | last post by:
hi, i have the following recursive function (simplified to demonstrate the problem): >>> def reTest(bool): .... result = .... if not bool: .... reTest(True) .... else: .... print...
1
by: Manjiri | last post by:
Hello everybody... I want to know stack operation for recurssive factorilal function..... Means how it exactly returns value and over all calcultion will be carried out...U can follow the below...
59
by: Umesh | last post by:
i wrote the following program to calculate factorial: #include<stdio.h> #include<iostream.h> void main() { int i,n; long int p=1; // or long double p=1; for exponential result which I don't...
0
by: Killer42 | last post by:
Here's a very simple function for VB (written in VB6) to calculate the factorial (!) of a number. Note that it is limited by the magnitude of the value which can be stored in the Long data type. (In...
0
kadghar
by: kadghar | last post by:
Hi, I saw that Killer posted a simple Factorial Function that allows you to calculate up to 13!, well, you can use this for bigger numbers by changing the variable type. Why is this? You can...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

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.