Right, this is (the last) assignment for my C introduction web class.
The assignment presents the main program, does not explain anything about it and tells you to write a function to print and sum the array in it.
However I don't really understand what is going on in the main program.
Translated for your convenience;
Source code:
#include <stdio.h>
#include <stlib.h>
void print_count(int *, int);
int main(int argc, char *argv[]) {
int x, sum = 0, size = 0, array[5];
if (argc == 6) {
/* Program name and parameters received from command line */
for (x = 0; x < argc - 1; x++) {
array[x] = atoi(argv[x + 1]);
}
print_count(array, size);
} else {
printf("Error\n");
}
return 0;
}
Now I am completely clueless as to how to start writing the program requested and what variables to call/how to write the function.
Edit3: completed exercise
void print_count(int *array, int size) {
int i;
int sum = 0;
printf("Elements: ");
for (i = 0; i <= size; i++) {
printf("%d ", (array[i]);
sum = sum += array[i]);
}
printf("\nSum = %d ", sum);
return 0;
}
I would like to understand what is going on in the main program and preferably come to an answer on how to actually write the function by myself.
array[5] = atoi(...had been give to you exactly this way?array[5] = atoi(argv[x+1]);is totally wrong.arrayis only defined as having 5 elements, not 6 (it starts at 0) and you probably want that to bearray[x]so you get all the values.print_countyou need to provide names for the two input variables. You can then use those names to access the variables. For examplevoid print_count(int *arr, int size) {.forloop in the lesson's code?int i; int count=argc-1; char ** values = &argv[1]; for (i=0; i<count; i++){arrray[i]=atoi(values[i]);}would be cleaner. I thought lessons are meant to teach good practice?stlib.h. Perhaps the OP made a slight error and the name should be:stdlib.h