LEC20081006 - Introduction to Computer Programming October...

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

View Full Document Right Arrow Icon
Introduction to Computer Programming October 6, 2008 Required readings: chapter 11. CSC180 Fall 2008, University of Toronto
Background image of page 1

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

View Full DocumentRight Arrow Icon
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
Background image of page 2
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
Background image of page 3

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

View Full DocumentRight Arrow Icon
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
Background image of page 4
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
Background image of page 5

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

View Full DocumentRight Arrow Icon
Image of page 6
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 01/10/2011 for the course CSC 180 taught by Professor Na during the Fall '01 term at University of Toronto- Toronto.

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 Right Arrow Icon
Ask a homework question - tutors are online