-5

Okay, the problem is the following..I need to enter a number and the program need to print how much digits of the number are < 5. The printing of the digits should be done with a recursive function. Example: "For the number 8423871 is should print 4231 : 4". Here is my solution without recursion, can someone help me with the recursive solution please..

int main() 

{

    int n, pom, digit=0, a;
    printf("Enter a number: ");
    scanf("%d", &n);
    pom=n;
    while(pom > 0)
    {
        a = pom % 10;
        if(a < 5)
            digit++;
        pom=pom/10;
    }
    printf("%d : %d\n", n, digit);

    return 0;
}
3
  • Since recursion is entirely unnecessary here, I can only assume this is homework. What attempt have you made, and in what way did that attempt not work as expected?
    – David
    Jan 1, 2014 at 14:18
  • You are getting downvotes because you don't show your attempt. Try this as recursive function: print_if_lower(int input), which should print a digit, then call itself minus the digit just printed.
    – Jongware
    Jan 1, 2014 at 14:18
  • 1
    By the way: your own solution is not only not recursive, it also doesn't do what you describe.
    – Jongware
    Jan 1, 2014 at 14:21

1 Answer 1

0
#include <stdio.h>

int func_r(int n, int counter){
    int q = n / 10;
    int r = n % 10;
    if(n == 0) return counter;
    if(r < 5){
        counter = func_r(q, counter + 1);
        printf("%d", r);
    } else {
        counter = func_r(q, counter);
    }
    return counter;
}

int main(){
    int n, digit;
    printf("Enter a number: ");
    scanf("%d", &n);
    digit = func_r(n, 0);
    printf(" : %d\n", digit);

    return 0;
}
2
  • 2
    Much as I hate to be the one to complain, but: do you really feel a code-only answer is appropriate in this case? (Edit: see also How to improve code-only answers)
    – Jongware
    Jan 1, 2014 at 14:57
  • @Jongware Is there anything you want to ask something? I think described as almost unnecessary since only embodies the contents of the question. And it is simple as there are no more.
    – BLUEPIXY
    Jan 1, 2014 at 15:19

Not the answer you're looking for? Browse other questions tagged or ask your own question.