Q:

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

0

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

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

#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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C program to print program\'s name... >>
<< C program to find the sum of N integer numbers usi...