/* sum.c */ #include <stdio.h> #include <stdlib.h> void printhelp(char progname[]); int main(int argc, char *argv[]) { int i; int sum = 0; /* Simple sanity check */ if (argc == 1) { printhelp(argv[0]); return 1; } for (i=1; i<argc; i++) { sum = sum + atoi(argv[i]); } printf("Total sum: %i\n", sum); return 0; } void printhelp(char progname[]) { printf("%s integer ...\n", progname); printf("This program takes any number of " "integer values and sums them up\n"); }
$ make sum cc sum.c -o sum
$ ./sum ./sum integer ... This program takes any number of integer values and sums them up
$ echo $? 1
$ ./sum 45 55 12 Total sum: 112
$ echo $? 0
* atoi() converts a string into an integer. * atol() converts a string into a long integer. * atoll() converts a string into a long long integer. * atof() converts a string into a floating-point number (of type double)