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