Question: To complete this program you will need to extract strings from the argv array and convert them to integers, then add them together. To do
To complete this program you will need to extract strings from the argv array and convert them to integers, then add them together. To do this, you will need to use the atoi functionLinks to an external site.. This will require you to #include
Create a file named lab4.c
Add a line at the top of the file to include stdlib.h (needed to call atoi function)
#include
Define a main function to contain your program code
int main(int argc,char** argv){ //...Your code goes here } In main, first check argc to verify the number of arguments is <=4. If not, just return 0. (an if statement)
Next declare a variable to hold the sum of type int and set it to 0.
Write a for loop that counts from 1 to argc-1, extracts the arguments from argv and converts them to integers using the atoi function (i.e. sum=sum + atoi(argv[i]);
After the loop return the sum.
Compile and test your code. You can type
gcc lab4.c -o lab4 ./lab4 1 2 3 4 echo $?
Then you should see
10
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
