fork download
  1. #include <stdio.h>
  2. //正の奇数nを引数とし、n以下の正の奇数の和を求める関数
  3. int rec(int n)
  4. {
  5. if (n == 1)
  6. {
  7. return 1; // n=1のとき、和は 1
  8. }
  9. else
  10. {
  11. return n+rec(n - 2); // n 以下の奇数の和 = (n-2) 以下の奇数の和 + n
  12. }
  13. }
  14.  
  15. int main(void)
  16. {
  17. int n = 11;
  18. printf("%d以下の正の奇数の和は%d\n", n, rec(n));
  19. return 0;
  20. }
  21. // 実行結果: 11以下の正の奇数の和は36 (1+3+5+7+9+11 = 36)
Success #stdin #stdout 0s 5276KB
stdin
Standard input is empty
stdout
11以下の正の奇数の和は36