...
/Multiplication Without Using * Operator
Multiplication Without Using * Operator
Use Recursion to multiply two numbers without using the * operator.
We'll cover the following...
We'll cover the following...
Problem statement
In this problem, we need to find the result of the multiplication of two numbers, a and b but without using * operator. This looks like a pretty simple problem. We can easily iterate a loop from 1 to b and add a to our result. But there is a catch: you need to write a solution with a Recursive approach.
Implementation
Let’s write the solution first, and then visualize how recursion is working.
C++
#include <iostream>using namespace std;int prod(int a , int b){if(b==0){return 0;}else if(b==1){return a;}else if(b>0){return a + prod(a,b-1);}else {return -prod(a,-b);}}int main() {int a = 2, b = -3;cout << prod(a,b);return 0;}
Explanation:
- On line 4, we define our recursive function
prod(). - On line 5, we check for the base case as