• Source
    1. // Given a non-negative int n, return the count of the occurrences of 7 as a digit,
    2. // so for example 717 yields 2. (no loops). Note that mod (%) by 10 yields the
    3. // rightmost digit (126 % 10 is 6), while divide (/) by 10 removes the rightmost
    4. // digit (126 / 10 is 12).
    5. //
    6. // count7(717) → 2
    7. // count7(7) → 1
    8. // count7(123) → 0
    9.  
    10. #include <stdio.h>
    11.  
    12. // To enable debug messages uncomment #define
    13. #define TEST 1
    14.  
    15. int count7(int n);
    16. void startTesting();
    17.  
    18. int main(void) {
    19. #ifdef TEST
    20. startTesting();
    21. #endif
    22.  
    23. return 0;
    24. }
    25.  
    26. int count7(int n) {
    27. if (n == 7) {
    28. return 1;
    29. } else if (n / 10 <= 0) {
    30. return 0;
    31. }
    32.  
    33. if (n % 10 == 7) {
    34. return 1 + count7(n / 10);
    35. } else {
    36. return count7(n / 10);
    37. }
    38. }
    39.  
    40. void startTesting()
    41. {
    42. int result = 0;
    43. int i = 0;
    44.  
    45. for (i = 115; i <= 125; i++) {
    46. result = count7(i);
    47.  
    48. printf("Count7(%d) = %d\n", i, result);
    49. }
    50. }