w3resource

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:

Flowchart: Multiply two integers without using multiplication, division, bitwise operators, and loops.

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?



Follow us on Facebook and Twitter for latest update.