Jump to: navigation, search

The C Programming Language, 2nd Edition, by Kernighan and Ritchie
Exercise 4.04 on page 79

Add commands to print the top element of the stack without popping, to duplicate it, and to swap the top two elements. Add a command to clear the stack.

Solution by Bob Wightman


Mr Wightman's solution has a bug. It can be seen by using the command '?'. After entering '?' the result (printing the top item without popping) is delayed until the ENTER key is pressed, which causes a newline ('\n'), which, in turn, causes the top item to be popped and printed. This defeats the intent of the '?' command. The other stack-manipulation commands have the same, or similar problems.
This situation is encountered in most operating systems. This is so that line editing can be done prior to submitting the line.
--- Pilcrow 03:11, 22 September 2011 (UTC)

#include<stdlib.h>
#include<stdio.h>
#include<ctype.h>
#include<math.h>

#define MAXOP 100
#define NUMBER  0
#define TRUE 1
#define FALSE 0

/* This programme is a basic calculator.

Extra cases have been added to:
1. Show the top item of the stack without permanently popping it.
2. Swap the top two items on the stack.
3. Duplicate the top item on the stack.
4. Clear the stack.

I have used functions for each of the new cases rather than have the
code inline in order to limit the physical size of the switch block.

In anticipation of the following exercise the following characters have
been used for the operations (in the same order as above): ? ~ # !
rather than use alphabetic characters.

It is actually rather difficult to be original in this exercise.

This is exercise 4-4 from Kernighan & Ritchie, page 79.

 */

int Getop(char s[]);
void push(double val);
double pop(void);
void showTop(void);
void duplicate(void);
void swapItems(void);
void clearStack();

int main(void)
{
    int type;
    double op2;
    char s[MAXOP];
    int flag = TRUE;

    while((type = Getop(s)) != EOF)
    {
        switch(type)
        {
            case NUMBER:
                                push(atof(s));
                break;
            case '+':
                push(pop() + pop());
                break;
            case '*':
                push(pop() * pop());
                break;
            case '-':
                op2 = pop();
                push(pop()- op2);
                break;
            case '/':
                op2 = pop();
                if(op2)
                    push(pop() / op2);
                else
                    printf("\nError: division by zero!");
                break;
            case '%':
                op2 = pop();
                if(op2)
                    push(fmod(pop(), op2));
                else
                    printf("\nError: division by zero!");
                break;
            case '?':
                showTop();
                break;
            case '#':
                duplicate();
                break;
            case '~':
                swapItems();
                break;
            case '!':
                clearStack();
            case '\n':
                printf("\n\t%.8g\n", pop());
                break;
            default:
                printf("\nError: unknown command %s.\n", s);
                break;
        }
    }
    return EXIT_SUCCESS;
}

#define MAXVAL 100

int sp = 0;          /* Next free stack position. */
double val[MAXVAL];  /* value stack. */

/* push: push f onto stack. */
void push(double f)
{
    if(sp < MAXVAL)
        val[sp++] = f;
    else
         printf("\nError: stack full can't push %g\n", f);
}

/*pop: pop and return top value from stack.*/
double pop(void)
{
    if(sp > 0)
        return val[--sp];
    else
    {
        printf("\nError: stack empty\n");
        return 0.0;
    }
}

void showTop(void)
{
    if(sp > 0)
        printf("Top of stack contains: %8g\n", val[sp-1]);
    else
        printf("The stack is empty!\n");
}


void duplicate(void)
{
    double temp = pop();

    push(temp);
    push(temp);
}

void swapItems(void)
{
    double item1 = pop();
    double item2 = pop();

    push(item1);
    push(item2);
}

/* pop only returns a value if sp is greater than zero. So setting the
stack pointer to zero will cause pop to return its error */

void clearStack(void)
{
    sp = 0;
}

int getch(void);
void unGetch(int);

/* Getop: get next operator or numeric operand. */
int Getop(char s[])
{
    int i = 0;
    int c;
    int next;

    /* Skip whitespace */
    while((s[0] = c = getch()) == ' ' || c == '\t')
        ;
    s[1] = '\0';

    /* Not a number but may contain a unary minus. */
    if(!isdigit(c) && c != '.' && c != '-')
        return c;               

    if(c == '-')
    {
        next = getch();
        if(!isdigit(next) && next != '.')
        {
           return c;
        }
        c = next;
    }
    else
        c = getch();
 
    while(isdigit(s[++i] = c))
            c = getch();
    if(c == '.')                        /* Collect fraction part. */
        while(isdigit(s[++i] = c = getch()))
                        ;
    s[i] = '\0';
    if(c != EOF)
        unGetch(c);
    return NUMBER;
}

#define BUFSIZE 100

char buf[BUFSIZE];
int bufp = 0;

/* Getch: get a ( possibly pushed back) character. */
int getch(void)
{
     return (bufp > 0) ? buf[--bufp]: getchar();
}

/* unGetch: push character back on input. */
void unGetch(int c)
{
    if(bufp >= BUFSIZE)
        printf("\nUnGetch: too many characters\n");
    else
        buf[bufp++] = c;
}


In anticipation of the requirements of exercises 4-5 & 4-6 I have followed Mr Wightman's example by assigning the characters @ ? # ~ ! to various stack operations, rather than using letters.
--- Pilcrow 19:36, 22 September 2011 (UTC)

#include <stdio.h>
#include <stdlib.h>
#include <math.h>


#define MAXOP 100
#define NUMBER '0'

int getop(char []);
void push(double);
double pop(void);
void stakop(int);

int nopprint = 0;                       /* don't pop & print on ENTER after stack operations */
double op2, op3;

int main(void)
{
    int type;
    char s[MAXOP];

    while((type = getop(s)) != EOF) {
        switch (type) {
            case NUMBER:
                push (atof(s));
                break;
            case '@': case '?': case '#': case '~': case '!':       /* stack operations */
                stakop(type);
                break;
            case '_':                       /* unary minus (underscore) negates previous number */
                push( 0.0 - pop());
                break;
            case '+':
                push(pop() + pop());
                break;
            case '*':
                push(pop() * pop());
                break;
            case '-':
                op2 = pop();
                push(pop() - op2);
                break;
            case '/':
                op2 = pop();
                if(op2 != 0.0) push(pop() / op2);
                else printf("error: zero divisor\n");
                break;
            case '%':                       /* floating modulo operator, not integer */
                op2 = pop();
                if(op2 != 0.0) push(fmod(pop(),op2));
                else printf("error: zero divisor\n");
                break;
            case '\n':
                if(!nopprint)
                    printf("\t%.8g\n",pop());
                nopprint = 0;
                break;
            default:
                printf("error: unknown command %s\n", s);
                break;
        }
    }
    return 1;
}

#define MAXVAL 100

int sp = 0;
double val[MAXVAL];


void push(double f)
{
    if (sp < MAXVAL)
        val[sp++] = f;
    else
        printf("error: stack full, can't push %g\n", f);
    return;
}

double pop(void)
{
    if (sp > 0) return val[--sp];
    else {
        printf("stack empty\n");
        return 0.0;
    }
}

#include <ctype.h>

int getch(void);
void ungetch(int);

int getop(char s[])
{
    int i, c, type;

    while((s[0] = c = getch()) == ' ' || c == '\t') ;       /* skip leading spaces or tabs */
    s[1] = '\0';
    if (!isdigit(c) && c != '.') return c;                  /* was operator */
    i = 0;                                                  /* was digit    */

    if(isdigit(c)) {
        type = NUMBER;
        while(isdigit(s[++i] = c = getch())) ;              /* get digits   */
    }
    if(c == '.') {
        type = NUMBER;
        while(isdigit(s[++i] = c = getch())) ;              /* and dec pt   */
    }

    s[i] = '\0';
    if( c != EOF)
        ungetch(c);
    return type;
}

#define BUFSIZE 100

char buf[BUFSIZE];
int bufp = 0;

int getch(void)
{
    return (bufp > 0) ? buf[--bufp] : getchar();
}

void ungetch(int c)
{
    if (bufp >= BUFSIZE) printf("ungetch: too many characters\n");
    else buf[bufp++] = c;
}

void stakop(int op)
{
    int i;
    nopprint = 1;                       /* disable pop & print on '\n' */

    switch(op) {
        case '@':                       /* show whole stack (not required by K&R)*/
            if(sp) {
                putchar('\n');
                for(i = sp - 1 ; i >= 0; i--)   /* last in, first shown */
                    printf("*** %.8g\n",val[i]);
            }
            else printf("stack empty\n");
            return;
        case '?':                       /* print top item */
            if(sp) {
                putchar('\n');
                push(op2=pop());
                printf("*** %.8g\n",op2);
            }
            else printf("stack empty\n");
            return;
        case '#':                       /* dup top item */
            push(op2=pop());
            push(op2);
            return;
        case '~':                       /* swap top 2 items */
            op2 = pop();
            op3 = pop();
            push(op2);
            push(op3);
            return;
        case '!':                       /* clear stack */
            nopprint = 0;
            sp = 0;
            return;
        default:                        /* should only get here if there's a bug */
            printf("error: unknown command %s\n",op);
            return;
    }
}
Personal tools
Personal tools
Tidy_icons
not logged in