• Source
    1. // Given a string, compute recursively (no loops) the number of lowercase ‘x’
    2. // chars in the string.
    3. //
    4. // countX(“xxhixx”) → 4
    5. // countX(“xhixhix”) → 3
    6. // countX(“hi”) → 0
    7.  
    8. #include <stdio.h>
    9.  
    10. // To enable debug messages uncomment #define
    11. #define TEST 1
    12.  
    13. int countX(char *s);
    14. void startTesting();
    15.  
    16. int main(void) {
    17. #ifdef TEST
    18. startTesting();
    19. #endif
    20.  
    21. return 0;
    22. }
    23.  
    24. int countX(char *s) {
    25. if (*s == '\0') {
    26. return 0;
    27. } else {
    28. return ((*s == 'x' ? 1:0) + countX(++s));
    29. }
    30. }
    31.  
    32. void test1()
    33. {
    34. int count = countX("xxhixx");
    35. printf("countX(\"xxhixx\") = %d\n", count);
    36. }
    37.  
    38. void test2()
    39. {
    40. int count = countX("xhixhix");
    41. printf("countX(\"xhixhix\") = %d\n", count);
    42. }
    43.  
    44. void test3()
    45. {
    46. int count = countX("hi");
    47. printf("countX(\"hi\") = %d\n", count);
    48. }
    49.  
    50. void startTesting()
    51. {
    52. test1();
    53. test2();
    54. test3();
    55. }