{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

LEC20081006

# LEC20081006 - Introduction to Computer Programming October...

This preview shows pages 1–6. Sign up to view the full content.

Introduction to Computer Programming October 6, 2008 Required readings: chapter 11. CSC180 Fall 2008, University of Toronto

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Program organization Divide calculator.c into calc.h , main.c , stack.c , getop.c , and getch.c . See the previous lecture note for calculator.c . main.c : /* main.c */ #include <stdio.h> #include <stdlib.h> /* for atof() */ #include ‘‘calc.h’’ #define MAXOP 100 /* max size of operand or operator */ /* reverse Polish calculator */ int main() { int type; CSC180 Fall 2008, University of Toronto 1
double op2; char s[MAXOP]; 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 != 0.0) push(pop()/op2); else printf(‘‘error: zero divisor\n’’); break; case ’\n’: CSC180 Fall 2008, University of Toronto 2

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
printf(‘‘\t%.8g\n’’, pop()); break; default: printf(‘‘error: unknown command %s\n’’, s); break; } } return 0; } stack.c : /* stack.c */ #include <stdio.h> #define MAXVAL 100 /* max depth of val stack */ static int sp = 0; /* next free stack position */ static double val[MAXVAL]; /* value stack */ /* push f onto value stack */ void push(double f) { if (sp < MAXVAL) CSC180 Fall 2008, University of Toronto 3
val[sp++] = f; else printf(‘‘error: stack full, can’t push %g\n’’, f); } /* pop and return top value from stack */ double pop(void) { if (sp > 0) return val[--sp]; else { printf(‘‘error: stack empty’’); return 0.0; } } getop.c

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 16

LEC20081006 - Introduction to Computer Programming October...

This preview shows document pages 1 - 6. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online