• Source
    1. // We have triangle made of blocks.
    2. // The topmost row has 1 block, the next row down has 2 blocks,
    3. // the next row has 3 blocks, and so on. Compute recursively (no loops or multiplication)
    4. // the total number of blocks in such a triangle with the given number of rows.
    5. //
    6. // triangle(0) → 0
    7. // triangle(1) → 1
    8. // triangle(2) → 3
    9.  
    10. #include <stdio.h>
    11.  
    12. // To enable debug messages uncomment #define
    13. #define TEST 1
    14.  
    15. int triangle(int rows);
    16. void startTesting();
    17.  
    18. int main(void) {
    19. #ifdef TEST
    20. startTesting();
    21. #endif
    22.  
    23. return 0;
    24. }
    25.  
    26. int triangle(int rows) {
    27. if (rows == 0) {
    28. return 0;
    29. }
    30.  
    31. if (rows == 1) {
    32. return 1;
    33. }
    34.  
    35. return rows + triangle(rows - 1);
    36. }
    37.  
    38. void startTesting()
    39. {
    40. int result = 0;
    41. int i = 0;
    42.  
    43. for (i = 0; i <= 5; i++) {
    44. result = triangle(i);
    45.  
    46. printf("Triangle(%d) = %d\n", i, result);
    47. }
    48. }