Home » C++ programs

C++ program to obtain Multiplication recursively

Here, we are implementing a C++ program to obtain multiplication recursively.
Submitted by Indrajeet Das, on December 10, 2018

Given two integers m and n, calculate and return their multiplication using recursion. You can only use subtraction and addition for your calculation. No other operators are allowed.

Input format: m and n (in different lines)

    Sample Input:
    3 
    5

    Sample Output:
    15

Explanation:

In this question, recursion enables us to multiply the numbers by adding them multiple times. So, for inputs, 3 and 5, the result occurs to be 15.

Algorithm:

  1. To solve using recursion, define a recursion function with 2 parameters m and n (the numbers you want to multiply).
  2. Base Case: if n==0 then return 0.
  3. return m + recursive call with parameters m and n - 1.

C++ Code/Function:

#include <bits/stdc++.h>
using namespace std;

int multiplyTwoInteger(int m, int n){
	if(n == 0){
		return 0;
	}
	return m + multiplyTwoInteger(m,n-1);
}

int main(){
	int m = 3, n =5;

	cout<<multiplyTwoInteger(m,n);

	return 0;
}

Output

15


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.