Example 1 — Sum the numbers given on the command line
Run as ./sum 4 6 10.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int sum = 0;
printf("argc = %d\n", argc);
for (int i = 1; i < argc; i++) {
sum += atoi(argv[i]);
}
printf("sum = %d\n", sum);
return 0;
} How It Works
./sum 4 6 10givesargc4: the program name plus three arguments.- The loop starts at 1 to skip
argv[0]. atoiconverts each string; 4 + 6 + 10 = 20.
