22 * Exercise 4-4. Add commands to print the top element of the stack without
33 * popping, to duplicate it, and to swap the top two elements. Add command to
44 * clear the stack.
5+ *
56 * By Faisal Saadatmand
67 */
78
1314#define NUMBER '0' /* signal that a number was found */
1415#define MAXVAL 100 /* max depth of val stack */
1516#define BUFSIZE 100
16- #define TOP val[sp - 1] /* top element in stack */
1717
1818/* functions */
1919int getop (char []);
@@ -31,7 +31,6 @@ int sp; /* next free stack position */
3131double val [MAXVAL ]; /* value stack */
3232char buf [BUFSIZE ]; /* buffer from ungetch */
3333int bufp ; /* next free position in buf */
34- int peak ; /* flag to peak at top of the stack */
3534
3635/* push: push f onto value stack */
3736void push (double f )
@@ -103,19 +102,18 @@ void ungetch(int c)
103102/* printTOP: print top of the stack without pop */
104103void printTOP (void )
105104{
106- if (sp < 1 )
107- printf ("stack empty\n" );
108- printf ("\t%.8g\n" , TOP );
105+ double top ;
106+
107+ top = pop ();
108+ printf ("\t%.8g\n" , top );
109+ push (top );
109110}
110111
111112/* duplicateTop: duplicate the top element in the stack */
112113void duplicateTop (void )
113114{
114115 double top ;
115116
116- if (sp < 1 )
117- return ;
118-
119117 push (top = pop ());
120118 push (top );
121119}
@@ -125,24 +123,12 @@ void duplicateTop(void)
125123 {
126124 double top1 , top2 ;
127125
128- if (sp < 2 ) {
129- if (sp == 1 )
130- printf ("error: 1 element in stack\n" );
131- return ;
132- }
133126 top1 = pop ();
134127 top2 = pop ();
135128 push (top1 );
136129 push (top2 );
137130}
138131
139- /* clear: clears the entire stack */
140- void clearStack (void )
141- {
142- while (sp > 1 )
143- pop ();
144- }
145-
146132/* reverse Polish Calculator */
147133int main (void )
148134{
@@ -179,24 +165,17 @@ int main(void)
179165 else
180166 printf ("error: zero divisor\n" );
181167 break ;
182- case '! ' :
183- peak = 1 ;
168+ case '? ' :
169+ printTOP () ;
184170 break ;
185- case '# ' :
171+ case 'd ' :
186172 duplicateTop ();
187173 break ;
188- case '& ' :
174+ case 's ' :
189175 swapTopTwo ();
190176 break ;
191- case '~' :
192- clearStack ();
193- break ;
194177 case '\n' :
195- if (peak ) {
196- printTOP ();
197- peak = 0 ;
198- } else
199- printf ("\t%.8g\n" , pop ());
178+ printf ("\t%.8g\n" , pop ());
200179 break ;
201180 default :
202181 printf ("error: unknown command %s\n" , s );
0 commit comments