Calculator Postfix

#include "stdio.h"
#include "string.h"
#include "stdlib.h"

#define MAX 20

int data[20];
int top=-1;

int isFull(){
	if(top==MAX-1) return 1; else return 0;
}

int isEmpty(){
	if(top==-1) return 1; else return 0;
}

void push(int d){
	if(isFull()==0){
		top++;
		data[top]=d;
	}
}

int pop(){
	int t=-1;
	if(isEmpty()==0){
		t=data[top];
		top--;
	}
	return t;
}

void operasi(char o){
	int a, b, h;
	switch(o){
		case '+':
					a = pop();
					b = pop();
					h = b + a;
					push(h);
					break;
		case '-':
					a = pop();
					b = pop();
					h = b - a;
					push(h);
					break;
		case '*':
					a = pop();
					b = pop();
					h = b * a;
					push(h);
					break;
		case '/':
					a = pop();
					b = pop();
					h = b / a;
					push(h);
					break;
		case '=':
					a = pop();
					if(a!=-1) printf("%d\n",a);
					else printf("EMPTY\n");
	}
}

int isOp(char* op){
	if(strcmp(op,"+")==0 || strcmp(op,"-")==0 || strcmp(op,"*")==0 || strcmp(op,"/")==0 || strcmp(op,"=")==0)
		return 1;
	else return 0;
}

void main(){
	char d[10];
	while(1){
		scanf("%s",d);
		if(isOp(d)){
			operasi(d[0]);
		} else if(strcmp(d,"x")==0){
			break;
		} else push(atoi(d));
	}
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s