The program is supposed to calculate the number of arguments, iterate over the list of arguments, for each argument convert the argument to an integer and copy it to an array, iterate over the elements of the array, adding the value of each one to a variable (this computes the sum of elements), and print the sum. There will not be more than 15 arguments. So far I have:
int sumofA (int sizeofA, int x, int y){ int i = sizeofA; if (i <= 15){ int z = x + y; return z; } } int main (int argc, char*argv[]){ int sizeofA = argc - 1; int i = 1; while (i <= sizeofA){ int x = GetInt (argc, argv, i); i = i + 1; int y = GetInt (argc, argv, i); printf ('%d\n', sumofA (sizeofA, x, y)); } return 0; }
Ok, now (when given three arguments other than ./a) it prints the sum of the first argument and the second argument…then the second and the third…and then the value of the third argument. Why?
Here’s the code for GetInt (I have to use this):
int GetInt (int argc, char * argv[], int i) { if (i < 0 || i >= argc) return 0; return atoi(argv[i]); }
Do I need to go through and assign each argument to an integer (ex. int z = GetInt (argc, argv, i + 2) )?
There are a couple of this going wrong here:
i is not defined in sumofA, so comparing with it yield undefined behavior.You return inside the loop; surely that’s not what you want.Your code is not actually storing anything in the array A.Please compile your code with all warning-flags on (gcc: -Wall -Werror -pedantic), and make sure there are no warnings when your code compiles.
Note that the variable size is unneeded: use while (i < argc).
Edit: Now that you added the code of GetInt, replace
with
There is no use for GetInt, so you can remove it completely.
Lastly: in your question you mention storing the numbers in an array and then summing them. Do you want to do that, or need to do that (due to some assignment?) Because it’s not necessary: simply add the result of all calls to atoi. The array A is then superfluous.
Edit 2: I see you fixed the code in some places. Your code currently (23:31 CEST) adds the first argument to each of the arguments separately and prints them. You’re not quite there yet. Good luck!