Home > OS >  How does this code give the correct result using a variable that was not entered
How does this code give the correct result using a variable that was not entered

Time:09-28

    #include<stdio.h>
const char *author ="Alexandre Santos";

int succ(int x)
{
  return x 1;
}

int pred(int x)
{
  return x-1;
}

int is_zero(int x)
{
  return x == 0;
}

int is_pos(int x)
{
  return x >= 0;
}

int sum(int x, int y)
{
 return is_zero(y)? x: sum(succ(x),pred(y));
}

int twice(int x)
{
  return sum(succ(x), pred(x));
}

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

I am in the first year of university and this is one of the exercises that a professor gave. I need to calculate the double of a number just using the given functions(succ, pred, is_zero, is_pos). I tried to do it and managed to come up with a solution but to be honest I don't understand how this is working. My main doubt is how the sum function is working since it uses the variable y and in this program this variable doesn't even exist/is not inserted in the input. Any tip?

CodePudding user response:

In your code, you called the function twice() with the parameter x, and in the function twice() you called the function sum() with the parameters succ(x) and pred(x), the value of succ(x) is assigned to x in sum, and the value of pred(x) is assigned to y in sum.

So for example; you passed the value 10 to x in the input, we will call the function twice with a value 10, and twice(10) returns the sum of succ(10) and pred(10) which are 11 and 9, so the values 11 and 9 are passed to the function sum like this: sum(11, 9), so in the function sum, the parameter x gets the value 11, and the parameter y gets the value 9.

  • Related