Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
oorrja
GitHub Repository: oorrja/learntosolveit
Path: blob/master/languages/cprogs/Ex_4.3_rpn_modulus_negative.c
1240 views
1
/* Adding the Modulus operator and provision for negative numbers
2
* Program is given the input in a single and and it print the output upon
3
* getting a \n character.
4
* For e.g:
5
*
6
* 10 10 + 100 + 2 *
7
* 240
8
*/
9
10
#include<stdio.h>
11
#include<stdlib.h>
12
#include<math.h>
13
14
#define MAXOP 100
15
#define NUMBER '0'
16
17
int getop(char []);
18
void push(double);
19
double pop(void);
20
21
/* reverse polish calculator */
22
23
int main(void)
24
{
25
int type;
26
double op2;
27
char s[MAXOP];
28
29
while((type = getop(s)) != EOF)
30
{
31
switch(type)
32
{
33
case NUMBER:
34
push(atof(s));
35
break;
36
case '+':
37
push(pop()+pop());
38
break;
39
case '*':
40
push(pop()*pop());
41
break;
42
case '-':
43
op2 = pop();
44
push(pop()-op2);
45
break;
46
case '/':
47
op2 = pop();
48
if(op2 != 0.0)
49
push(pop()/op2);
50
else
51
printf("error:zero divisor\n");
52
break;
53
case '%':
54
op2 = pop();
55
if(op2 != 0.0)
56
push(fmod(pop(),op2));
57
else
58
printf("erro:zero divisor\n");
59
break;
60
case '\n':
61
printf("\t%.8g\n",pop());
62
break;
63
default:
64
printf("error: unknown command %s\n",s);
65
break;
66
67
}
68
}
69
return 0;
70
}
71
72
73
#define MAXVAL 100
74
75
int sp = 0;
76
double val[MAXVAL];
77
78
void push(double f)
79
{
80
if(sp < MAXVAL)
81
val[sp++]=f;
82
else
83
printf("error:stack full, cant push %g\n",f);
84
}
85
86
87
double pop(void)
88
{
89
if(sp>0)
90
return val[--sp];
91
else
92
{
93
printf("error: stack empty\n");
94
return 0.0;
95
}
96
}
97
98
#include<ctype.h>
99
100
int getch(void);
101
void ungetch(int);
102
103
int getop(char s[]) {
104
int i, c;
105
while ((s[0] = c = getch()) == ' ' || c == '\t')
106
;
107
s[1] = '\0';
108
if (!isdigit(c) && c != '.' && c != '-')
109
return c; // not a number
110
i = 0;
111
if (c == '-' || isdigit(c)) // collect integer part along with '-'
112
while (isdigit(s[++i] = c = getch()))
113
;
114
if (c == '.') // collect fraction part
115
while (isdigit(s[++i] = c = getch()))
116
;
117
s[i] = '\0';
118
if (c != EOF)
119
ungetch(c);
120
if (strcmp(s, "-") == 0)
121
return '-';
122
return NUMBER;
123
}
124
125
#define BUFSIZE 100
126
127
char buf[BUFSIZE];
128
int bufp = 0;
129
130
int getch(void)
131
{
132
return (bufp > 0) ? buf[--bufp] : getchar();
133
}
134
135
void ungetch(int c)
136
{
137
if(bufp >= BUFSIZE)
138
printf("ungetch: too many characters\n");
139
else
140
buf[bufp++] = c;
141
}
142
143
144