DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   C++ (http://www.daniweb.com/forums/forum8.html)
-   -   Simple Recursion (Multiplying by using Addition) (http://www.daniweb.com/forums/thread160731.html)

NinjaLink Dec 4th, 2008 1:38 pm
Simple Recursion (Multiplying by using Addition)
 
Hello all,

My objective is simple. I have to take in 2 positive integers and multiply them by using addition. This is a recursive problem.

Example of Output:


Please enter 2 positive integers to multiply:

4 2

4 * 2 = 8



The problem is whenever the user types in both numbers, the program window just disappears.

To receive my result, I am suppose to use something like:

x + multiply(x,--y);


Please help me with this...Thank you


#include <iostream>

using namespace std;

int multiply(int x, int y);

int main()
{
   
int x;
int y;         
   

cout<<"Please enter 2 positive integers to multiply"<<endl;
cin>>x;
cin>>y;

cout<<x<<" * "<<y<<" = "<<multiply(x,--y)<<endl;

   
system ("PAUSE");
return 0;
}


int multiply(int x, int y)
{


if (x == 0)
{
return 0;
}

if (x == 1)
{   
return x;
}

if (x > 1)

{
return (x + multiply(x,--y));
}

}

Salem Dec 4th, 2008 1:53 pm
Re: Simple Recursion (Multiplying by using Addition)
 
You test x, and only change y

mrboolf Dec 4th, 2008 1:56 pm
Re: Simple Recursion (Multiplying by using Addition)
 
As long as you are decrementing y you should put y in your base cases checks, otherwise
multiply(2, wathever);
would result in *endless* recursion.

EDIT: Sorry, Salem beated me in speed.


All times are GMT -4. The time now is 4:53 am.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC