C program to calculate addition, subtraction, multiplication using command line arguments

Learn: How to pass numbers and operators to perform the basic arithmetic operations using command line arguments in C programming language.

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 pass three arguments with the program's executable file name like (./main 10 + 20), program will calculate the result according to input operator. In this program allowed operators are +, -, and *, you can add other cases perform the calculations.

Sample Input:

./main 10 + 20

Sample Output:

Result: 10 + 20 = 30

#include <stdio.h>

int main(int argc, char *argv[])
{
	int a,b, result;
	char opr;
	
	if(argc!=4)
	{
		printf("Invalid arguments...\n");
		return -1;
	}
	
	//get values
	a = atoi(argv[1]);
	b = atoi(argv[3]);
	
	//get operator
	opr=argv[2][0];
	
	//calculate according to operator
	switch(opr)
	{
		case '+':
			result=a+b;
			break;
		case '-':
			result=a-b;
			break;
		case '*':
			result=a*b;
			break;
		default:
			result=0;
			break;
	}
	
	if(opr=='+' || opr=='-' || opr=='*')
		printf("Result: %d %c %d = %d\n",a,opr,b,result);
	else
		printf("Undefined Operator...\n");
	
	return 0;
}

Output

First run:
sh-4.2$ ./main 10 + 20
Result: 10 + 20 = 30

Second run:
sh-4.2$ ./main 10 - 20
Result: 10 - 20 = -10 

Third run:
sh-4.2$ ./main 10 / 20
Undefined Operator... 

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.

C Command Line Arguments Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.