[Solved] Doubling a number


Well, in your description you say that you need to take one input. However, your program reads two inputs.

Maybe this is what you need:

#include <stdio.h>
int sum(int x, int y)
{
 return y == 0 ? x : sum(x+1, y-1);
}
int main(void)
{
 int x;
 if (scanf("%d", &x) != 1)  // Only 1 input
 {
    // Input error
    return -1;
 }
 int z = sum(x, x);    // Use x for both arguments
 printf("%d\n", z);
 return 0;
} 

This works because the sum functions increments one argument and decrements the other in the recursive call and continues doing that until one of the arguments reach zero. In this way the end result will be 2 * x

Let’s say the input is 3. Then you’ll have these calls:

sum(3, 3)
sum(4, 2)
sum(5, 1)
sum(6, 0) // Which will end the recursion and return 6 all the way up

1

solved Doubling a number