0

I need to write a function that'll print a 0 or 1 with

  1. f variable needs to be 0 or 1
  2. when user enters a number, for example 4321 and the f variable is 0 the function should return 1 because the number is an ascending series from right to left or else it returns 0
  3. when user enter a number, for example 1234 and f variable is 1 the function should return 1 because the number is ascending from left to right else it returns 0

here is my code attempt:

#include <stdio.h>
int f2(int num, int f)
{
    int x = num % 10, y = num % 100 / 10;
    //if (x == y) return 0;
    if (f == 0) {
        if (x > y) return 0;
         else {
            f2(num / 10, f);
            return 1;
        }
    }
    if (f == 1) {
        if (x < y) return 0;
        else {
            f2(num/10, f);
            return 1;
        }
    }


}

void main()
{
    int num, f;
    printf("please enter number and f:");
    scanf_s("%d %d", &num, &f);
    printf("The result of calling f2(%d) is: %d",num, f2(num, f));
}

the problem is when i put f=1 with numbers 1234 the output is blank the problem is when i put f=1 with numbers 1234 the output is blank

Barmar
  • 741,623
  • 53
  • 500
  • 612

1 Answers1

0

There's two problems.

  1. You have no base case to stop the recursion. The recursion should stop when num is a single digit, since that's always in order.
  2. You're not checking the result of the recursion. After calling f2(num/10, f) you always return 1, even if the recursive call returned 0. You should just do return f2(num/10, f).
int f2(int num, int f)
{
    if (num < 10) { // base case
        return 1;
    }
    int x = num % 10, y = num % 100 / 10;
    if (f == 0) {
        if (x > y) {
            return 0;
        }
         else {
            return f2(num / 10, f);
         }
    }
    if (f == 1) {
        if (x < y) {
            return 0;
        }
        else {
            return f2(num/10, f);
        }
    }
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • i did what you said and it returns a value higher than 0 or 1, i just want the output to return 1 when I type num=1234 and f=1 – erez zinger Dec 21 '20 at 21:37