Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

    #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?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading