In: Computer Science
Complete these steps to write a simple calculator program:
1. Create a calc project directory
2. Create a mcalc.c source file containing five functions; add, sub, mul, div, and mod; that implement integer addition, subtraction, multiplication, division, and modulo (remainder of division) respectively. Each function should take two integer arguments and return an integer result.
3. Create a mcalc.h header file that contains function prototypes for each of the five functions implemented in mcalc.c.
4. Create a calc.c source file with a single main function that implements a simple calculator program with the following behavior:
-> Accepts a line of input on stdin of the form ”number operator number” where number is a signed decimal integer, and operator is one of the characters ”+”, ”-”, ”*”, ”/”, or ”%” that corresponds to the integer addition, subtraction, multiplication, division, and modulo operation respectively.
-> Performs the corresponding operation on the two input numbers using the five mcalc.c functions.
-> Displays the signed decimal integer result on a separate line and loops to accept another line of input.
-> Or, for any invalid input, immediately terminates the program with exit status 0.
5. Create a Makefile using the following Makefile below as a starting point. Modify the Makefile so that it builds the executable calc as the default target. The Makefile should also properly represent the dependencies of calc.o and mcalc.o.
CC = gcc
CFLAGS = -g -O2 -Wall -Werror
ASFLAGS = -g
objects = calc.o mcalc.o
default: calc
.PHONY: default clean clobber
calc: $(objects)
$(CC) -g -o $@ $^
calc.o: calc.c mcalc.h
%.o: %.c
$(CC) -c $(CFLAGS) -o $@ $<
%.o: %.s
$(CC) -c $(ASFLAGS) -o $@ $<
clean:
rm -f $(objects)
clobber: clean
rm -f calc
6. Compile the calc program by executing ”make” and verify that the output is proper. For example:
# ./calc
3 + 5
8
6 * 7
42
If you have any doubts, please give me comment...
mcalc.h
int add(int n1, int n2);
int sub(int n1, int n2);
int mul(int n1, int n2);
int div(int n1, int n2);
int mod(int n1, int n2);
mcalc.c
#include "mcalc.h"
int add(int n1, int n2){
return n1+n2;
}
int sub(int n1, int n2){
return n1-n2;
}
int mul(int n1, int n2){
return n1*n2;
}
int div(int n1, int n2){
return n1/n2;
}
int mod(int n1, int n2){
return n1%n2;
}
calc.c
#include<stdio.h>
#include "mcalc.h"
int main(){
int n1, n2;
char op;
while(scanf("%d %c %d", &n1, &op, &n2)==3){
if(op=='+')
printf("%d\n", add(n1, n2));
else if(op=='-')
printf("%d\n", sub(n1, n2));
else if(op=='*')
printf("%d\n", mul(n1, n2));
else if(op=='/')
printf("%d\n", div(n1, n2));
else if(op=='%')
printf("%d\n", mod(n1, n2));
else{
printf("Invalid operator");
break;
}
}
return 0;
}