problem writing a recursive function in C

ROG 21 Reputation points
2021-01-02T16:57:25.567+00:00

hey,
I am trying to write a function that reads two numbers and
checks if the digits of 'n' are in descending or ascending order.
and return a different value (0/1) for different scenarios of 'f'.
for example:
if f=0 and digits are descending (example: 4321) return 1
if f=1 and digits are ascending (example: 1234) return 1

for some reason I get '1' even when I input f=0, n=5321
'5321' shouldn't return 1 since 5 doesn't follow 3

would really appreciate the help!

updated code:

void Ex2()
{
    int n, f, ans;
    printf("Enter a number: ");
    scanf_s("%d", &n);
    printf("Enter a number betwen 0-3 : ");
    scanf_s("%d", &f);
    ans = zeroORone(n, f);
    printf("ans= %d\n", ans);
}

int zeroORone(int n, int f)
{
    int result = 1;
    printf("n= %d\n", n);
    int num1, num2, i = 10;
    num1 = n % 10;
    num2 = n / 10 % 10;
    if (f == 0)
    {
        if (num1 != (num2 - 1))
        {
            result = 0;
        }
    }
    if (result == 0) return result;
    if (result == 1)
    {
        n /= 10;
        if (n > 9)
            zeroORone(n, f);
    }
    printf("res = %d\n", result);
    return result;
}

thanks (:

Developer technologies | C++
{count} votes

1 answer

Sort by: Most helpful
  1. Barry Schwarz 3,746 Reputation points
    2021-01-03T00:48:20.527+00:00

    You have succumbed to mental confusion caused by using the same names for variables in main and in zeroORone.

    When you call zeroORone on line 8, you save the return value in ans. However, when you call the function recursively in line 32, you throw the return value away. Within this function, the variable result is local to the current recursion level and is destroyed when that level returns to the next higher level.

    Lets call main level 0 and prefix its variables with L0::. L0::result is initialized to 1. line 8 passes this value to zeroORone at level 1. L1::Num1 is computed as 1 etc and line 32 passes L1::result to level 2. L2::num1 is computed as 2 etc and line 32 passes L2:result to level 3. L3::num1 is computed as 3 etc and line 25 sets L3::result to 0. line 34 prints L3::result and line 35 returns it to level 2 where it is promptly discarded. L2::result is still 1. Line 34 prints L2::result and line 35 returns it to level 1 where it is also discarded. L1::result is still 1. Line 34 prints L1::result and line 35 returns it to level 0 (main) where it is saved in ans. But as noted two sentences prior, the returned value is L1::result which was never changed from 1.

    When level n+1 returns a value, you must save that value so level n can in turn return that value back to level n-1.

    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.