C Programming Code Examples C > Mathematics Code Examples A simple four-function calculator A simple four-function calculator #include <stdio.h> #include <stdlib.h> #define MAX 100 int *p; /* will point to a region of free memory */ int *top-of-stack ; int *bottom-of-stack; void push(int i) { if(p > bottom-of-stack) { printf("Stack Full\n"); return; } *p = i; p++; } int pop(void) { p--; if(p < top-of-stack ) { printf("Stack Underflow\n"); return 0; } return *p; } int main(void) { int x, y; char s[80]; p = (int *) malloc(MAX*sizeof(int)); /* get stack memory */ if(!p) { printf("Allocation Failure\n"); exit(1); } top-of-stack = p; bottom-of-stack = p + MAX-1; printf("Four Function Calculator\n"); printf("Enter 'q' to quit\n"); do { printf(": "); gets(s); switch(*s) { case '+': x = pop(); y = pop(); printf("%d\n", x+y); push(x+y); break; case '-': x = pop(); y = pop(); printf("%d\n", y-x); push(y-x); break; case '*': x = pop(); y = pop(); printf("%d\n", y*x); push(y*x); break; case '/': x = pop(); y = pop(); if(x==0) { printf("Divide by 0.\n"); break; } printf("%d\n", y/x); push(y/x); break; case '.': /* show contents of top of stack */ x = pop(); push(x); printf("Current value on top of stack: %d\n", x); break; default: push(atoi(s)); } } while(*s != 'q'); return 0; }