w3resource

C++ Recursion: Calculating product of two numbers without multiplication operator

C++ Recursion: Exercise-13 with Solution

Write a C++ program to implement a recursive function to calculate the product of two numbers without using the multiplication operator.

Sample Solution:

C Code:

// Recursive function to calculate the product of two numbers without using the multiplication operator
#include <iostream>

// Recursive function to multiply two numbers without using the multiplication operator
int multiply(int x, int y) {
  // Base case: if either number is 0, the product is 0
  if (x == 0 || y == 0)
    return 0;

  // Recursive case: recursively add x to the product of (x, y - 1)
  // when y is positive, or recursively add (-x) to the product of (x, y + 1)
  // when y is negative
  if (y > 0)
    return x + multiply(x, y - 1); // Positive y: add x to the product
  else
    return -x + multiply(x, y + 1); // Negative y: add (-x) to the product
}

int main() {
  int n1, n2;
  std::cout << "Input the first number: ";
  std::cin >> n1;
  std::cout << "Input the second number: ";
  std::cin >> n2;

  // Calculate the product using recursion
  int result = multiply(n1, n2);

  std::cout << "Product of " << n1 << " and " << n2 << ": " << result << std::endl;

  return 0;
}

Sample Output:

Input the first number: 12
Input the second number: 34
Product of 12 and 34: 408

Explanation:

In the above exercise,

  • The "multiply()" function takes two integers x and y as parameters and calculates their product without using the multiplication operator.
  • The base case is when either x or y is 0, in which case the function returns 0.
  • In the recursive case, if y is positive, the function recursively adds x to the product of x and y - 1. If y is negative, the function recursively adds -x to the product of x and y + 1.
  • The recursive calls continue until the base case is reached, and the function returns the final product.
  • The "main()" function prompts the user to enter two numbers, calls the "multiply()" function to calculate their product, and then displays the result.

Flowchart:

Flowchart: Calculating product of two numbers without multiplication operator.

CPP Code Editor:

Contribute your code and comments through Disqus.

Previous C++ Exercise: Counting occurrences of an element in an array with recursive function.
Next C++ Exercise: Calculating the sum of even and odd numbers in a range.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.