multiply two arbitrary integers a and b (a greater than b)
#include <iostream>
int multiply(int a, int b) {
int result = 0;
while (b > 0) {
if (b % 2 == 1) {
result += a;
}
a *= 2;
b /= 2;
}
return result;
}
int main() {
int a = 7; // Replace with your first integer
int b = 3; // Replace with your second integer
int product = multiply(a, b);
std::cout << "Product: " << product << std::endl;
return 0;
}
Explanation:
- Include necessary header files.
- Define a function named
multiply
that takes two integer argumentsa
andb
. - Initialize a variable
result
to store the product ofa
andb
. - Start a
while
loop that continues untilb
is greater than 0. - Check if the current value of
b
is odd (b % 2 == 1
). - If
b
is odd, add the value ofa
to theresult
. - Multiply
a
by 2. - Divide
b
by 2. - Repeat steps 5-8 until
b
becomes 0. - Return the
result
, which holds the product ofa
andb
. - In the
main()
function, define two integer variablesa
andb
with the desired values. - Call the
multiply
function witha
andb
as arguments and store the result inproduct
. - Print the
product
to the console.