/* Write and test a method mult with the following specification without using t
ID: 3801606 • Letter: #
Question
/*
Write and test a method mult with the following specification without using the
multiplication operator.
Write a recursive method that performs the multiplication by repeated addition. Make
your method work for both positive and
negative integers, as well as zero.
Start by calling a separate helper method that assumes both parameters are nonnegative.
Then, in the calling method,
make an adjustment afterwards for the case when the signs of the two original
numbers were different.
PARAMETERS: integers j and k
RETURN VALUE: the product j*k
*/
long mult(long j, long k);
Explanation / Answer
P,ease refer below code
#include<stdlib.h>
#include<stdio.h>
long mult(int i,int j)
{
if ( i < 0 ) return -mult(-i,j);
if ( j < 0 ) return -mult(i,-j);
if ( j == 0 ) return 0;
return (mult(i,j>>1)<<1)+(j&1?i:0);
}
int main()
{
int a,b;
long result;
printf("Enter value of a : ");
scanf("%d", &a);
printf(" Enter value of b : ");
scanf("%d", &b);
result = mult(a,b);
printf("Product is : %ld ", result);
return 0;
}
Please refer below output for reference
Enter value of a : -8
Enter value of b : 9
Product is : -72
Process returned 0 (0x0) execution time : 5.330 s
Press any key to continue.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.