C++ Exercises: Multiply two integers without using multiplication, division, bitwise operators, and loops
C++ Math: Exercise-17 with Solution
Write a C++ program to multiply two integers without using multiplication, division, bitwise operators, and loops.
Sample Input: 8, 9
Sample Output: 72
Sample Input: -11, 19
Sample Output: -209
Sample Solution:
C++ Code :
#include <iostream>
using namespace std;
// Function to multiply two integers recursively
int multiply_two_nums(int x, int y)
{
// Base case: if y is 0, the result is 0
if (y == 0)
return 0;
// If y is positive, recursively add x y times
if (y > 0)
return (x + multiply_two_nums(x, y - 1));
// If y is negative, convert it to positive, multiply, and make the result negative
if (y < 0)
return -multiply_two_nums(x, -y);
}
int main()
{
// Test cases to multiply two numbers using the multiply_two_nums function
cout << multiply_two_nums(8, 9) << endl; // Output the product of 8 and 9
cout << multiply_two_nums(-11, 19) << endl; // Output the product of -11 and 19
return 0; // Return 0 to indicate successful completion
}
Sample Output:
72 -209
Flowchart:
C++ Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a C++ programming to find the nth digit of number 1 to n.
Next: Write a C++ program to convert a given integer to a roman numeral.
What is the difficulty level of this exercise?
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/cpp-exercises/math/cpp-math-exercise-17.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics