• Source
    1. // Given a string, compute recursively (no loops) the number of times
    2. // lowercase “hi” appears in the string.
    3. //
    4. // countHi(“xxhixx”) → 1
    5. // countHi(“xhixhix”) → 2
    6. // countHi(“hi”) → 1
    7.  
    8. #include <stdio.h>
    9.  
    10. // To enable debug messages uncomment #define
    11. #define TEST 1
    12.  
    13. int countHi(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 countHi(char *s) {
    25. if (*s == '\0' || *(s+1) == '\0') {
    26. return 0;
    27. } else if (*s == 'h' && *(s+1) == 'i') {
    28. return (1 + countHi(s + 2));
    29. } else {
    30. return (countHi(++s));
    31. }
    32. }
    33.  
    34. void test1()
    35. {
    36. int count = countHi("xxhixx");
    37. printf("countHi(\"xxhixx\") = %d\n", count);
    38. }
    39.  
    40. void test2()
    41. {
    42. int count = countHi("xhixhix");
    43. printf("countHi(\"xhixhix\") = %d\n", count);
    44. }
    45.  
    46. void test3()
    47. {
    48. int count = countHi("hi");
    49. printf("countHi(\"hi\") = %d\n", count);
    50. }
    51.  
    52. void startTesting()
    53. {
    54. test1();
    55. test2();
    56. test3();
    57. }