Home > Article > Backend Development > C++ program written using recursion to calculate the product of two numbers
Recursion is a technique of calling a function from the same function itself. There must be some base or terminating condition to end the recursive call. Recursive procedures are very helpful for performing complex iterative solutions with less code and finding easier solutions through sub-operations.
In this article, we will discuss the recursive method of performing the product (multiplication) between two numbers in C. First we understand the basic principles, recursive function calling syntax, algorithm and source code.
In high-level languages, there are multiplication operators that can perform multiplication directly. However, we know that multiplication is actually repeated addition. So the result of A*B is the number of repeated additions of A and B, or it can be said that the number of repeated additions of B and A. Whenever there are repetitions, we can do this using recursion. Let's look at the recursive function definition syntax first.
<return type> function_name ( parameter list ) { if ( base condition ) { terminate recursive call } recursive function call: function_name ( updated parameter list ) }
Let’s look at an algorithm that performs multiplication using recursion.
#include <iostream> #include <sstream> using namespace std; int multiply( int A, int B) { if( A < B ) { return multiply( B, A ); } else if( B != 0 ) { return A + multiply( A, B - 1 ); } else { return 0; } } int main() { cout << "Multiplication of 5, 7 is: " << multiply( 5, 7 ) << endl; cout << "Multiplication of 8, 0 is: " << multiply( 8, 0 ) << endl; cout << "Multiplication of 25, 3 is: " << multiply( 25, 3 ) << endl; cout << "Multiplication of 9, 1 is: " << multiply( 9, 1 ) << endl; }
Multiplication of 5, 7 is: 35 Multiplication of 8, 0 is: 0 Multiplication of 25, 3 is: 75 Multiplication of 9, 1 is: 9
Look, in this program, the function parameters A and B are both integers. Now, after each step, it decrements the second parameter B by 1 and adds A to A itself. Like this, the function is performing the multiplication process.
Recursion is the process of calling the same function from the function itself. When calling a function recursively, we update or change the parameter set slightly so that the same effect does not occur again and again, and then divide the problem into smaller sub-problems and solve the problem by solving these smaller problems in a bottom-up approach . Almost anything that can be implemented using a loop can also be implemented using recursion. In this article, we saw the simple process of multiplying two integers using recursion. Add integers multiple times to get the final multiplication result.
The above is the detailed content of C++ program written using recursion to calculate the product of two numbers. For more information, please follow other related articles on the PHP Chinese website!