Command Line Calculator in C.
A simple Command Line Calculator in C.
Main.c
#include<stdio.h>
#include<stdlib.h>
#define LESS_ARGS "Insufficient arguments\n"
#define USAGE "Usage : calc <option> <arguments>\n"
void add(char* argv[],int argc);
void subtract(char* argv[],int argc);
void multiply(char* argv[],int argc);
int main(int argc, char* argv[]){
if (argc < 2){
printf(USAGE);
return 1;
}
else{
switch(*argv[1]){
case 'a':
add(argv,argc);
break;
case 's':
subtract(argv,argc);
break;
case 'm':
multiply(argv,argc);
break;
default:
printf(USAGE);
}
}
return 0;
}
void add(char* argv[],int argc){
if(argc < 4){
printf(LESS_ARGS);
return;
}
else{
int temp = 0;
for(int i = 2;i < argc;i++){
printf("DEBUG[ADD FOR LOOP] TEMP : %d I : %d VAL I : %d \n",temp,i,atoi(argv[i]));
temp += atoi(argv[i]);
}
printf("Result : %d\n",temp);
return;
}
}
void subtract(char* argv[],int argc){
if(argc < 4){
printf(USAGE);
return;
}
int temp = atoi(argv[2]);
for(int i = 3;i< argc;i++){
temp -= atoi(argv[i]);
}
printf("Result : %d\n",temp);
}
void multiply(char* argv[],int argc){
if (argc < 4){
printf(USAGE);
return;
}
int temp = atoi(argv[2]);
for(int i =3; i< argc;i++){
temp *= atoi(argv[i]);
}
printf("Result : %d\n",temp);
}
Comments
Post a Comment