How to multiply 2 numbers using recursion - c

I'm trying to multiply (3, 6) and (9, 9) using recursion. However, the result printed is 18 and 45. I need to find out which part is wrong.
Here's my code:
#include <stdio.h>
int multiply (int, int);
int main()
{
int a, b, c;
a = 6; b = 3; c = multiply(a, b);
printf("%d\n", c);
a = 9; b = 9; c = multiply(a, b);
printf("%d\n", c);
return 0;
}
int multiply(int a, int b)
{
static int c = 0, i = 0;
if (i < a) {
c = c + b;
i++;
multiply(a, b);
}
return c;
}

The issue is that multiply's static variables persist from call to call, which throws the second calculation off. It is possible to bandage this wound, but it's better to address the underlying design problem that is compelling use of static variables in the first place. There is no need to artificially maintain state in the function using i (the number of additions to perform) and c (a product accumulator).
Given that multiplication is repeated addition of a b times, you can establish a base case of b == 0 and recursively add a, incrementing or decrementing b (depending on b's sign) until it reaches 0. The product accumulator c is replaced by the function return value and the number of multiplications i is represented by b.
Using this approach, each stack frame's state is naturally self-reliant.
#include <stdio.h>
int multiply(int a, int b) {
if (b > 0) {
return a + multiply(a, b - 1);
}
else if (b < 0) {
return -a + multiply(a, b + 1);
}
return 0;
}
int main() {
printf("%d\n", multiply(3, 6));
printf("%d\n", multiply(9, 9));
printf("%d\n", multiply(-6, 2));
printf("%d\n", multiply(6, -2));
printf("%d\n", multiply(-7, -3));
printf("%d\n", multiply(0, 7));
printf("%d\n", multiply(7, 0));
printf("%d\n", multiply(0, 0));
return 0;
}
Output:
18
81
-12
-12
21
0
0
0
As a final note, I recommend following proper code style. Minifying your code and using single-character variable names only makes debugging more difficult (someone has since de-minified the original code in an edit).

Both c and i need to be reset to zero on each [outer] call to multiply [as others have mentioned] because a function scope static variable is only initialized once.
There is no way to do this because the static variables are at multiply function scope (i.e. how does main access/reset them?). They would need to be moved to global/file scope.
Adding a helper function and moving the variables to global scope will do it:
#include <stdio.h>
int multiply(int, int);
int
main()
{
int a,
b,
c;
a = 6;
b = 3;
c = multiply(a, b);
printf("%d\n", c);
a = 9;
b = 9;
c = multiply(a, b);
printf("%d\n", c);
return 0;
}
static int c, i;
int
mul(int a, int b)
{
if (i < a) {
c = c + b;
i++;
mul(a, b);
}
return c;
}
int
multiply(int a, int b)
{
i = 0;
c = 0;
return mul(a,b);
}

Try resetting your static variables before second call to multiply or do without them
int multiply(int a, int b) {
If (a==0)
return 1;
else if (a>0)
return b+multiply(a-1, b);
else
return - 1*multiply(-1*a, b); }

Related

The program needs to show the variable with greater first digit

The program needs to show an number which has a greater first digit, which works, only if the numbers of digits are the same on both variables. Try with these numbers 4506 29985, it should show 4506, but the program shows 29985, the program was written in C language.
#include <stdlib.h>
#include <stdio.h>
int disassembly1 (int a)
{
while (a>=10)
{
a /= 10;
}
return a;
}
int disassembly2 (int b)
{
while (b>=10)
{
b /= 10;
}
return b;
}
int main ()
{
int A1, B1, a, b;
printf("Int 2 numbers:\n");
scanf_s("%d %d", &A1, &B1);
a = A1;
b = B1;
disassembly1(A1);
disassembly2(B1);
if (a > b || ((a == b) && (A1 > B1)))
printf("%d\n", A1);
else
printf("%d\n", B1);
system("pause");
}
First of all, disassembly1 and disassembly2 are the same function and should not written twice.
Second and more important, the function disassembly returns the first digit, but you need to store it in a variable.
A working code (with a few changes):
#include <stdlib.h>
#include <stdio.h>
int disassembly(int a)
{
while (a>=10)
{
a /= 10;
}
return a;
}
int main()
{
int a, b, a_digit, b_digit;
printf("Int 2 numbers:\n");
scanf_s("%d %d", &a, &b);
a_digit = disassembly(a);
b_digit = disassembly(b);
if (a_digit > b_digit || ((a_digit == b_digit) && (a > b)))
printf("%d\n", a);
else
printf("%d\n", b);
system("pause");
return 0;
}
Also, the name disassembly does not match the function meaning. I would suggest to change it to something like get_first_digit.
Your code does not read the values returned from the functions, leaving variables a & b unchanged.
Change:
disassembly1(A1);
disassembly2(B1);
To:
a = disassembly1(A1);
b = disassembly2(B1);
Other suggestions:
define and use a single instance of function: int disassembly(int x); and call it twice.
a = disassembly(A1);
b = disassembly(B1);
Here is a much simpler version (this is matlab/octave, but can easily be ported to c)
a = 4506;
b = 29985;
isAbigger = floor(a/10^(floor(log10(a)))) > floor(b/10^(floor(log10(b))));

Looping operations

I would like to write something like this;
for (op1 in (plus, minus, times, divby, exponent)) {
printf("%d", a op1 b);
}
so that what actually ends up being executed is something like this
printf("%d", a + b);
printf("%d", a - b);
printf("%d", a * b);
printf("%d", a / b);
printf("%d", a ^ b);
How can I write this?
Since you've not posted any code, I'm not going to write any, but will be happy to help with some concepts which you can turn into working code.
Write functions to perform individual operations (addition, subtraction, multiplication etc).
Take an array of function pointers, initialize that with individual functions you want to perform.
Loop over the array and pass the required variables to the function call to get desired output.
Something like (pseudo-code)
funcptr arr[SIZE] = { func1, func2, func3... };
for (int i = 0; i < SIZE ; i++) {
printf("%d\n", arr[i](a, b));
}
That said, just a note, a ^ b is not an "exponent" operator in C, as you might have expected. It is bitwise XOR. You can make use of pow() to get that done.
FYI, you can refer to this question for related information.
Array of function pointers would do.
double plus(int a, int b);
double minus(int a, int b);
double times(int a, int b);
double divby(int a, int b);
double exponent(int a, int b);
typedef double (*p_fun)(int a, int b);
int main()
{
int a = 5, b = 10;
p_fun pa[] = {plus, minus, times, divby, exponent};
for( int i = 0; i < sizeof(pa)/sizeof(p_fun); i++ )
{
printf("%f\n", pa[i](a, b));
}
return 0;
}

C: Having an issue with scope

so I'm studying for a final and we are given this block of codeL
#include <stdio.h>
int a;
void addOne(void) {
a++;
printf(“W. a = %d\n”, a);
}
int removeOne(int a) {
int b = a – 1;
printf(“R. b = %d\n”, b);
}
void swap(int a, int *b) {
int temp = a;
a = *b;
*b = temp;
}
int main() {
a = 5;
int b = 20;
if (b > 15) {
int a = 53;
removeOne(b);
addOne(a);
printf(“X. a = %d\n”, a);
}
printf(“Y. a = %d, b = %d\n”, a, b);
swap(a, &b);
printf(“Z. a = %d, b = %d\n”, a, b);
return 0;
}
We are instructed to give the outputs of the program. I'm having trouble with the addone(a) where I came up with 54, the correct answer was 6. Is it 6 because when the function is declared it has the void (don't remember the technical term but the information it takes in to the function) rather than something like int a?
My more direct question is why does the function take the a initialized in the main function rather than the a in the if?
The reason that the answer is 6:
Note at the top that a is declared as a global. Later, in main there is a call to addOne(a) inside of a code block. That code block defines a local variable a as well. The a that is passed in that scope is the local a (53). It is passed into a function that accepts an unnamed void variable. In that function, however, there is a reference to a. Due to scoping, this will be the global a (5), so a++ will result in an output of 6.
That is a horrible exam question.

Undefined behaviour in C program. Please explain

Below is a program to add two numbers using bitwise operators. Though the final value returned in function add is as expected the value printed in main function is showing some junk value.Can anyone explain this undefined behaviour and let me know what is going wrong here.Sample output below.
#include <stdio.h>
#include <string.h>
#include <windows.h>
int add (int, int);
int main ()
{
int n1 = 0, n2 = 0;
scanf("%d %d", &n1, &n2);
printf("\nSum: %d\n",add(n1, n2));
system("pause");
return 0;
}
int add (int a, int b)
{
printf("%d %d\n", a, b);
if (!a) {
return b;
} else {
add ((a & b) << 1, a ^ b);
}
}
Sample output:-
3 1
3 1
2 2
4 0
0 4
Sum: 2686756
you need to return the result of add in your recursive call
int add (int a, int b)
{
printf("%d %d\n", a, b);
if (!a) {
return b;
} else {
return add ((a & b) << 1, a ^ b);
}
}
which could be
int add (int a, int b)
{
if (!a) return b;
return add ((a & b) << 1, a ^ b);
}
The line add ((a & b)... is missing return, so it's just returning a random number off the stack.
I can be wrong (C is loooong time away) but
if (!a) {
Is not bit "not" operator.
It will be "true" for every value, except 0
Edit :
See other answers. But in c++ ot's working :)

Given two int numbers A and B. How to find next multiple of B that is not less than A?

Suppose you input A = 15, B = 6, The answer is 18. What algorithm do I need?
This is what I try, but it doesn't work:
#include <stdio.h>
int main() {
int a, b;
scanf("%d %d", &a, &b);
for ( ; a % b != 0; a++ ) {
if ( a % b == 0 ) {
printf("%d\n", a);
return a;
}
}
return 0;
}
I get infinite loop.
The question (now) asks for:
The next multiple of b that is not less than a?
Using your notation of a and b, you can write it directly like this:
int NextMultipleUp(int a, int b)
{
int r = a % b;
if (r == 0)
return a;
else
return a + b - r;
}
The question originally asked for
The next multiple of a that is not greater than b
And for that the answer is
int NextMultipleDown(int a, int b)
{
return b - b % a;
}
This was the answer for which the original comments applied to.
return (((a-1) / b )+1) * b;
Always returns a multiple of b. Increment the integer dividend to get a multiple that is larger than the original a - subtract one from the original, because we want 'not less than' rather than 'greater than' a
I think that you want a do - while iterative loop, so I will give an alternative answer.
How to find next multiple of B that is not less than A?
Obviously this code is slower than David's.
int main ( void ){
int a, b, c;
long int result;
scanf("%d %d", &a, &b);
c = 0;
do {
result = b * c;
c++;
} while ( result < a );
printf( " The number is: %d \n", result );
}
int nextMultiple(int a,int b)
{
if(a%b == 0) return a;
return a+(b-(a%b));
}
so if a=15 b=6
the ans is
=15+(6-(15%6))
=15+(6-(3))
=15+3
=18

Resources