Home > database >  Is there a way to write a recursive function that multiplies the even numbers from 1 to n using c?
Is there a way to write a recursive function that multiplies the even numbers from 1 to n using c?

Time:07-02

I've found similar questions that do that to the sums of even numbers, but when i try to change that to the product of these, it always ends up printing out 0.

#include<stdio.h>
int SumEven(int num1, int num2)
{
   if(num1>num2)
    return 0;
return num1*SumEven(num1 2,num2);
}
int main()
{
    int num1=2,num2;
    printf("Enter your Limit:");
    scanf("%d",&num2);
    printf("Sum of all even numbers in the given range is: %d",SumEven(num1,num2));
}

this is an example of one of those i tried to adapt but it only returns 0, any ideas?

CodePudding user response:

You need to post code for a question like this. But the probable cause- when you do a sum, you start with an initial value of 0. When you do products, it needs to be 1. Otherwise you multiply 0*i, which is always 0.

CodePudding user response:

I believe what is happening is that no interim value is being captured as you recursively go deeper into the function calls and then return up the function call stack. I believe that along the way, the multiplication of the incrementing values has to be captured until the program finally gets to the limit and heads back up the call stack to the main program.

Following is some code for you to review and revise as you see fit.

#include<stdio.h>

int MultEven(int num1, int num2, int *n)
{
    if(num1>num2)
        return 0;
    *n *= num1;
    MultEven(num1   2, num2, n);
    return *n;
}
int main()
{
    int num1=2,num2;
    int initial = 1;
    printf("Enter your Limit:");
    scanf("%d", &num2);
    printf("Multiplication of all even numbers in the given range is: %d\n", MultEven(num1, num2, &initial));
}

I introduced an integer work variable to keep track of the multiplications until the recursive calls were complete. I reference it as an additional parameter in the function call as an integer pointer, but one could use a global variable as well. It's just up to preference.

Testing out a few small limits appeared to yield the results you were after.

:~/C_Programs/Console/MultEven/bin/Release$ ./MultEven 
Enter your Limit:4
Multiplication of all even numbers in the given range is: 8
:~/C_Programs/Console/MultEven/bin/Release$ ./MultEven 
Enter your Limit:8
Multiplication of all even numbers in the given range is: 384
:~/C_Programs/Console/MultEven/bin/Release$ ./MultEven 
Enter your Limit:10
Multiplication of all even numbers in the given range is: 3840

Test this out and see if this points you in the direction you want to go.

Regards.

  • Related