ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

C - Program for arithmetic operations using Command Line Arguments.


IncludeHelp 18 September 2016

In this code snippet/program/example we will learn how to perform arithmetic operations like sum (+), subtraction (-) and multiplication (*) using command line arguments?

In this example we will pass two integer arguments with operator like (+, -, *) and program will calculate their result and print.

In this example/program we are performing only three arithmetic operators +, -, and *.

Command format will be:

./prg_name opr value1 value2

C Code Snippet - Program for arithmetic operations using Command Line Arguments

/*C - Program for arithmetic operations 
using Command Line Arguments.*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char* argv[]){
	int a,b,result;
	char opr[10];
	
	if(argc<4){
	    printf("Some parameters are missing\n");
	    printf("use prg_name opr value1 value2\n");
	    return -1;
	}
	
	//getting operator
	strcpy(opr,argv[1]);
	//getting values from arguments
	a=atoi(argv[2]);
	b=atoi(argv[3]);
	
	
	switch(opr[0]){
		case '+':
			result=a+b;
			break;
		case '-':
			result=a-b;
			break;
		case '*':
			result=a*b;
			break;
		default:
			printf("Invalid Operator!!!\n");
			return -1;
	}
	printf("Result is: %d %c %d = %d\n",a,opr[0],b,result);
	return 0;
}
    ./main + 10 20
    Result is: 10 + 20 = 30

ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.