|
From: Chad S. <ho...@ho...> - 2000-12-06 21:46:28
|
>From: "softnasolutions-ltd.fsbusiness.co.uk" ><so...@so...> >Reply-To: dev...@li... >To: <dev...@li...> >Subject: [Dev-C++] use of recursion >Date: Wed, 6 Dec 2000 20:26:39 -0000 > >Hi friends, > >I have just started learning C++ (i'm using a material from >Cprogramming.com). I've tried to write a program to recursively calculate >the factorial of a number but it doesn't work. Can someone please tell me >what i've done wrong, Here is the code: > >#include <iostream.h> >#include <stdlib.h> > >int factorial_cal(int results) >{ > if (results>0) > > results=1*results; > factorial_cal(results-1); > > return results; >} >int main() > >{ >int number; >int results; >cout<< "Enter a number for me to caculate its Factorial"<<endl; >cin>>number; >results=number; >factorial_cal(results); > >cout<< " The factorial of "<<number<< " is "<<results<<endl; > > system("PAUSE"); > return 0; >} Basically the problem you are having is caused by the fact that you aren't doing anything with the result of your recursion. You have the function calling itself, but it isn't in anyway affecting the return value. Try this instead. int factorial_cal(int value) { if(value == 1) return 1; else if(value > 0) return (value * factorial_cal(value-1)); else abort(); } Thus the recusion will result in: factorial_cal(5) creates (return 5*(return 4*(return 3*(return 2*1;);););) Where each set of parenthesis represents 1 call to the function. Chad Simmons _____________________________________________________________________________________ Get more from the Web. FREE MSN Explorer download : http://explorer.msn.com |