/* ex0.c * CSE 333 13au exercise 0 sample solution. * This solution takes advantage of some C language features and * libraries we would not necessarily expect to see in submitted programs * since we have not talked about them yet (specifically, fixed-sized * integer types, asserts, and somewhat fussy use of casts). **/ #include // for printf, sscanf #include // for EXIT_SUCCESS / EXIT_FAILURE and exit // Print out the usage of the program and exit with failure status. void usage () { fprintf(stderr, "usage: ./sec1 failure\n"); exit(EXIT_FAILURE); } // sum all of the numbers from 1 to n int sum_nums(int n) { int result = 0; int i; for (i = 1; i <= n; i++) { result += i; } return result; } // Given input argument n, print sum of all numbers from 1 to n int main(int argc, char **argv) { // Print usage and exit if no command line argument provided if (argc != 2) usage(); // Convert command line argument // Print usage and exit if unsuccessful or if value is too large. int res; if (sscanf(argv[1], "%d", &res) != 1) usage(); // Calculate and print the sum of numbers 1 to n. printf("The sum of the numbers 1 to %d is %d\n", res, sum_nums(res)); // Quit return EXIT_SUCCESS; }