ALL IMPLMENTED IN C 3. Create a calculator. This is a textual calculator not a G
ID: 3765830 • Letter: A
Question
ALL IMPLMENTED IN C
3. Create a calculator. This is a textual calculator not a GUI.
a. Your calculator should begin by displaying the functions your calculator is able to perform.
b. The user should then be able to insert a formula for which you calculate and display the answer.
c. The following functions need to be handled by your calculator:
i. Sin
ii. Cos
iii. Tan
iv. X^2
v. X^Y
vi. Square root
vii. Addition
viii. Subtraction
ix. Multiplication
x. Division
xi. Parentheses
d. The user should be able to enter a formula like:
2 * (3 + 4) – 21 / 7
Your calculator should honor the order of operations and give the correct answer of 11.
ALL IMPLMENTED IN C
Explanation / Answer
#include<stdio.h>
#include<conio.h>
#define LEN 25
void push(int *stack , int* top ,int node)
{
printf(" pushing : %d ", node);
stack[*top] = node;
(*top)++;
}
int pop(int *stack , int* top)
{
int temp;
(*top)--;
temp = stack[*top];
printf(" popping : %d",temp);
return temp;
}
void calc(int* numstack , int* numtop, int* opstack , int* optop){
int num1,num2,ans;
char sign;
num1 = pop(numstack,numtop);
num1 = pop(numstack,numtop);
switch(pop(opstack,optop)){
case '+' : ans = num1 + num2; sign = '+' ; break;
case '-' : ans = num1 - num2; sign = '-' ; break;
case '*' : ans = num1 * num2; sign = '*' ; break;
case '/' : ans = num1 / num2; sign = '/' ; break;
}
printf("%d %c %d = %d ",num1,sign,num2,ans);
push(numstack,numtop,ans);
while(getchar()!=' '){}
}
int main(void)
{
int optop = 0 , numtop = 0, j=0 , numstack[50] , opstack[30];
char str[102], c;
clrscr();
printf("enter string to be evaluated (100 chars max): ");
fgets(str , 100 , stdin);
while(str[j]!=' '){ j++; }
str[j] = '';
printf(" string : %s Length : %d",str,j);
j = 0;
while( (c=str[j]) !=''){
printf(" reading : %c ",str[j]);
if(c=='('){ j++; continue; }
else if(c=='+'||c=='-'||c=='*'||c=='/') push(opstack,&optop,c);
else if(c>=48 && c <=57) push(numstack,&numtop,(c-48));
else if(c==')') calc(numstack , &numtop, opstack , &optop);
else printf(" %c is invalid.. ",c);
j++;
}
printf(" answer is : %g",pop(numstack,&numtop));
getch();
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.