Home / Programs / C program to find the sum of two numbers using command line arguments
🚀 Programming Example

C program to find the sum of two numbers using command line arguments

👁 1,840 Views
💻 Practical Program
📘 Step Learning
How to find the sum of two integer numbers using command line arguments? Here, values will be given through the command line.

💻 Program Code

#include <stdio.h>

int main(int argc, char *argv[])
{
	int a,b,sum;
	if(argc!=3)
	{
		printf("please use \"prg_name value1 value2 \"\n");
		return -1;
	}
	
	a = atoi(argv[1]);
	b = atoi(argv[2]);
	sum = a+b;
	
	printf("Sum of %d, %d is: %d\n",a,b,sum);
	
	return 0;
}
                        

🖥 Program Output

First run:
sh-4.2$ ./main 10 20
Sum of 10, 20 is: 30 

Second run:
sh-4.2$ ./main 10 20 30 40
please use "prg_name value1 value2 "
                            

📘 Explanation

As we have discussed in?command line argument?tutorial, that we can also give the input to the program through the?command line.

In this program, we will provide the input (two integer values) through the command line and program will add them and print the value of input numbers along with the sum of them.

Sample input

./main  10  20

Here,?./main?is the program's executable file name,?10?and?20?are the input values.

Sample output

Sum of 10, 20 is: 30

What is atoi()?

atoi()?is a library function that converts string to integer, when program gets the input from command line, string values transfer in the program, we have to convert them to integers (in this program).?atoi()?is used to return the integer of the string arguments.

📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.