/* lots of functions for summing the first n integers */ #include #include /* for atoi */ int sum1(int n) { return ((n+1)*n) / 2; } int sum2(int n) { if(n==0) { return 0; } else { return sum2(n-1) + n; } } int sum3(int n) { if(n==0) return 0; return sum3(n-1) + n; } int sum4(int n) { int ans = 0; while(n != 0) { ans += n; n -= 1; } return ans; } int sum5(int n) { int ans = 0; while(n) { ans += n; --n; /* or n-- or n = n - 1 */ } return ans; } int sum6(int n) { int ans = 0; while(n) ans += n--; /* NOT --n */ return ans; } int sum7(int n) { int ans = 0; for(; n >= 0; --n) { ans += n; } return ans; } int sum8(int n) { int ans = 0; for(; n >= 0; ans+=n, --n) ; return ans; } int sum9(int n) { int ans = 0; while(1) { if(n==0) break; ans += n--; } return ans; } int sum10(int n) { int ans = 0; while(1) { if(n==0) return ans; ans += n--; } } int sum11(int n) { int ans = 0; goto L2; L1: return ans; L2: if(n==0) goto L1; ans += n--; goto L2; } int sumWrong(int n) { /* illegal because of goto into scope */ if(n==0) return 0; goto L2; {int ans = 0; L1: return ans; L2: if(n==0) goto L1; ans += n--; goto L2; } } int main(int argc, char**argv) { if(argc != 2) { fprintf(stderr,"bad args\n"); return 1; } { int num = atoi(argv[1]); /* note: see strtol for better error checking */ if(num < 0) { fprintf(stderr,"bad args\n"); return 1; } /* later we will use function pointers to avoid this copy/paste */ fprintf(stdout, "1: %d\n", sum1(num)); fprintf(stdout, "2: %d\n", sum2(num)); fprintf(stdout, "3: %d\n", sum3(num)); fprintf(stdout, "4: %d\n", sum4(num)); fprintf(stdout, "5: %d\n", sum5(num)); fprintf(stdout, "6: %d\n", sum6(num)); fprintf(stdout, "7: %d\n", sum7(num)); fprintf(stdout, "8: %d\n", sum8(num)); fprintf(stdout, "9: %d\n", sum9(num)); fprintf(stdout, "10: %d\n", sum10(num)); fprintf(stdout, "11: %d\n", sum11(num)); fprintf(stdout, "12: %d\n", sumWrong(num)); } return 0; }