How does the program give the product of the 2 numbers I put on the console?

Asked

Viewed 35 times

1

This program makes the product 2 numbers ie if I put 3 and 4 the result is 12 if put 4 and 4 is 16. But I don’t understand how does the product through the sum(x+1,y-1) and of sum(x, product(x, y-1)

#include <stdio.h>
int sum(int x, int y)
{
    return y == 0 ? x : sum(x+1, y-1);
}

int product(int x, int y)
{
    return y == 0 ? 0 : sum(x, product(x, y-1));
}

int main(void)
{
    int x;
    int y;
    scanf("%d%d", &x, &y);
    int z = product(x, y);
    printf("%d\n", z);
    return 0;
}
  • 3

    You have studied recursion?

  • 2

    I advise you to take it step by step to understand, like, product(3,4) => sum(3, product(3,4-1)) => etc

  • 3

    Take the table test: https://answall.com/q/220474/101 and read about https://answall.com/q/107657/101 and https://answall.com/q/21551/101 and https://answall.com/q/323954/101.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.