16.8k views
1 vote
Write a program "addnumbers.c" where it takes as many arguments as the user includes as command line arguments and calculates the sum of all numbers entered, and prints it. You will find using function atoi() from stdlib.h library helpful, where it converts the string representation of an integral number to an int value. Compile it on a lab machine and run it using command line.

User Demz
by
5.8k points

1 Answer

1 vote

Answer:

#include <stdio.h>

#include <stdlib.h>

int main(int argc, char* argv[])

{

int first, second, total;

if (argc < 2)//checking if there are enough arguments

{

printf("not enough values\\");

return -1;//terminate program

}

total = 0;

for (int i = 1; i < argc; i++)

{

//atoi convert a string into int. doing this to use operator

total = total + atoi(argv[i]);//add current total to next argumment

}

printf("final total sum: %d\\", total);//printing final total

return 0;

}

Step-by-step explanation:

For command line arguments you have to use command prompt. It varies depending on you machine and where you code is placed.

So, go to command line, called "command prompt" on Windows. This should open the black screen, also called the Terminal. A picture is attached in the answer. Then you have to NAVIGATE to the directory of your program. So, let's say your code is on your desktop. You will have to navigate to your desktop. To do this, type:

"cd Desktop", and press enter.

The picture of my process is attached below too.

Then, the program we have made is called addnumbers. we will type,

"addnumbers 10 20 30 40 50"

add numbers is the name of the program followed by arguments, separated with spaces.

Write a program "addnumbers.c" where it takes as many arguments as the user-example-1
Write a program "addnumbers.c" where it takes as many arguments as the user-example-2
User Kibernetik
by
5.2k points