Path: blob/master/languages/cprogs/Ex_4.3_rpn_modulus_negative.c
1240 views
/* Adding the Modulus operator and provision for negative numbers1* Program is given the input in a single and and it print the output upon2* getting a \n character.3* For e.g:4*5* 10 10 + 100 + 2 *6* 2407*/89#include<stdio.h>10#include<stdlib.h>11#include<math.h>1213#define MAXOP 10014#define NUMBER '0'1516int getop(char []);17void push(double);18double pop(void);1920/* reverse polish calculator */2122int main(void)23{24int type;25double op2;26char s[MAXOP];2728while((type = getop(s)) != EOF)29{30switch(type)31{32case NUMBER:33push(atof(s));34break;35case '+':36push(pop()+pop());37break;38case '*':39push(pop()*pop());40break;41case '-':42op2 = pop();43push(pop()-op2);44break;45case '/':46op2 = pop();47if(op2 != 0.0)48push(pop()/op2);49else50printf("error:zero divisor\n");51break;52case '%':53op2 = pop();54if(op2 != 0.0)55push(fmod(pop(),op2));56else57printf("erro:zero divisor\n");58break;59case '\n':60printf("\t%.8g\n",pop());61break;62default:63printf("error: unknown command %s\n",s);64break;6566}67}68return 0;69}707172#define MAXVAL 1007374int sp = 0;75double val[MAXVAL];7677void push(double f)78{79if(sp < MAXVAL)80val[sp++]=f;81else82printf("error:stack full, cant push %g\n",f);83}848586double pop(void)87{88if(sp>0)89return val[--sp];90else91{92printf("error: stack empty\n");93return 0.0;94}95}9697#include<ctype.h>9899int getch(void);100void ungetch(int);101102int getop(char s[]) {103int i, c;104while ((s[0] = c = getch()) == ' ' || c == '\t')105;106s[1] = '\0';107if (!isdigit(c) && c != '.' && c != '-')108return c; // not a number109i = 0;110if (c == '-' || isdigit(c)) // collect integer part along with '-'111while (isdigit(s[++i] = c = getch()))112;113if (c == '.') // collect fraction part114while (isdigit(s[++i] = c = getch()))115;116s[i] = '\0';117if (c != EOF)118ungetch(c);119if (strcmp(s, "-") == 0)120return '-';121return NUMBER;122}123124#define BUFSIZE 100125126char buf[BUFSIZE];127int bufp = 0;128129int getch(void)130{131return (bufp > 0) ? buf[--bufp] : getchar();132}133134void ungetch(int c)135{136if(bufp >= BUFSIZE)137printf("ungetch: too many characters\n");138else139buf[bufp++] = c;140}141142143144