I have an assignment. The program is to print the sum of all command line arguments in C. I tried this code it compiles but throws an error after passed arguments in the console. Below is the code.
/* Printing sum of all command line arguments */
#include <stdio.h>
int main(int argc, char *argv[]) {
int sum = 0, counter;
for (counter = 1; counter <= argc; counter++) {
sum = atoi(sum) + atoi(argv[counter]);
}
printf("Sum of %d command line arguments is: %d\n", argc, sum);
}
After compiling it outputs a Segmentation fault (core dumped)
error. Your experience may solve my problem.
Below is my edited code:
/* Printing sum of all command line arguments*/
#include <stdio.h>
#include <stdlib.h> // Added this library file
int main (int argc, char *argv[]) {
int sum = 0, counter;
for (counter = 1; counter < argc; counter++) {
// Changed the arithmetic condition
sum = sum + atoi(argv[counter]);
// Removed the atoi from sum variable
}
printf("Sum of %d command line arguments is: %d\n", argc, sum);
}