Home > Software engineering >  Why is recursion not working as expected in C
Why is recursion not working as expected in C

Time:04-09

I want to count numbers in int from user input from char to zero. This code make only 1 cycle. (Please help me understand what is wrong in second part.)

void count_down_from(int num);
int main()
{
    int start;
    char letter;
    printf("print letter to reduce to zero in ACSCII");
    scanf("%c", &letter);
 
    count_down_from(letter);
    return 0;
}

This part working not good:

 void count_down_from(int num)
    {
        if (num > 0)
        {
            --num;
            count_down_from;
            printf("%d\n", num);
        }
        else
            return;
    }
    }

What behaviour expected:

void count_down_from(int num)
{
    printf("%d\n", num);
    --num;
    if (num < 0)
        return;
    else
        count_down_from(num);
}

CodePudding user response:

take a look at my modifications

void count_down_from(int num)
    {
        if (num >= 0) //need the >= operator to go down to zero not just 1
        {

            printf("%d\n", num);
            --num;
            count_down_from(num); //you need to send num to the call otherwise it won't be a recursive function
        }
        else
            return;
    }

CodePudding user response:

Missed (num) in function call in second block.

  • Related