Reverse Polish Calculator Reverse Polish Notation 연산자가 피연산자의 뒤에 온다. 예 ) (1 – 2) * (4 + 5)  1 2 – 4 5 + * * 수식에서 괄호가 요구되지 않는다. ( 수식이 애매하지 않다 )

Slides:



Advertisements
Similar presentations
Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional.
Advertisements

Recursive Descent Technique CMSC 331. UMBC 2 The Header /* This program matches the following A -> B { '|' B } B -> C { '&' C } C -> D { '^' D } D ->
Procedural Programming in C# Chapters Objectives You will be able to: Describe the most important data types available in C#. Read numeric values.
Slide: 1 Copyright © AdaCore Packages Presented by Quentin Ochem university.adacore.com.
Programming Languages and Paradigms The C Programming Language.
Stacks & Their Applications COP Stacks  A stack is a data structure that stores information arranged like a stack.  We have seen stacks before.
Programming III SPRING 2015 School of Computer and Information Sciences Francisco R. Ortega, Ph.D. McKnight Fellow and GAANN Fellow LECTURE #3 Control.
Stacks.
CS 177 Recitation Week 8 – Methods. Questions? Announcements  Project 3 milestone due next Thursday 10/22 9pm  Turn in with: turnin –c cs177=xxxx –p.
0 Chap. 4 Functions and Program Structure 4.1 Basics of Functions 4.2 Functions Returning Non-integers 4.3 External Variables 4.4 Scope Rules 4.5 Header.
Functions and Program Structure Chapter 4. Introduction Functions break large computing tasks into smaller ones Appropriate functions hide details of.
0 4.2 Functions Returning Non-integers The return statement is the mechanism for returning a value : return expression; Remark : The expression will be.
0 Chap. 2. Types, Operators, and Expressions 2.1Variable Names 2.2Data Types and Sizes 2.3Constants 2.4Declarations Imperative Programming, B. Hirsbrunner,
Inline Function. 2 Expanded in a line when it is invoked Ie compiler replace the function call with function code To make a function inline the function.
The Preprocessor #include #define N 10 C program Preprocessor Modified C program Preprocessor Object codes.
1 COMP 2130 Introduction to Computer Systems Computing Science Thompson Rivers University.
Data Structures: CSCI 362 – Stack Implementation Data Structures: CSCI 362 – Stack Implementation lecture notes adapted from Data Structures with C++ using.
Stacks. 2 What Are Stacks ? PUSHPOP 0 MAX Underflow Overflow.
Program A computer program (also software, or just a program) is a sequence of instructions written in a sequence to perform a specified task with a computer.
224 3/30/98 CSE 143 Recursion [Sections 6.1, ]
Homework K&R chapter 4. HW3: ASCII Hex to Integer int axtoi (char s[ ]) { int i, n, flag; n = 0; flag = 1; for ( i = 0; flag; i++) /* for (i = 0; ; i++)
0 4.3 First Large Coding Example: calculator (kr76-79): Example of a Stack Machine Description of the problem and approach Pseudo code Flat implementation.
Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.
Engineering Computing I Chapter 4 Functions and Program Structure.
C Functions Three major differences between C and Java functions: –Functions are stand-alone entities, not part of objects they can be defined in a file.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 18: Stacks and Queues (part 2)
ECE 103 Engineering Programming Chapter 36 C Storage Classes Herbert G. Mayer, PSU CS Status 8/4/2014 Initial content copied verbatim from ECE 103 material.
Exam / Homework Exam 1 Starting K&R chapter 4 tonight
Dale Roberts CSCI 230 Functions Scope, Parameter Passing, Storage Specifiers Department of Computer and Information Science, School of Science, IUPUI Dale.
1 Data Structures CSCI 132, Spring 2014 Lecture 6 Applications using Stacks.
Programming Language  C Functions and Program Structure 主講人:虞台文.
0 First Large Example: A Calculator (kr76-79) – Example of a Stack Machine (SM) AST ([extended] Abstract Syntax Tree) : a representation of C expressions.
CS 261 C Basics Page 2 1/14/2016 CS 261, WSU Vancouver Primitive Types Notes: 4 A is a constant; B is a variable.
0 Chap.2. Types, Operators, and Expressions 2.1Variable Names 2.2Data Types and Sizes 2.3Constants 2.4Declarations 2.5Arithmetic Operators 2.6Relational.
1 Data Structures CSCI 132, Spring 2016 Notes 6 Applications using Stacks.
2. C FUNDAMENTALS. Example: Printing a Message /* Illustrates comments, strings, and the printf function */ #include int main(void) { printf("To C, or.
0 4.1 Basics of Functions + Function Call Diagram + make 4.2 Functions Returning Non-integers + Prototype Function 4.3 External Variables 4.4 Scope Rules.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 실 습실 습 4.
Chapter 15: Writing Large Programs Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 15 Writing Large Programs.
Functions and Program Structure Chapter 4. Introduction Functions break large computing tasks into smaller ones Appropriate functions hide details of.
D. GotsevaPL - Lectures1 Programming Languages Lectures Assoc. Prof. PhD Daniela Gotseva
C 프로그래밍 개발 도구. 컴파일러 gnu c compiler 컴파일 gcc sample.c 실행 a.out 실행 파일 지정 컴파일 gcc –o sample sample.c 실행 sample.
Functions and Program Structure CSE 2031 Fall June 2016.
1 ENERGY 211 / CME 211 Lecture 3 September 26, 2008.
CSC 172 DATA STRUCTURES. A TALE OF TWO STRUCTURES.
Programming Abstractions
C Functions -Continue…-.
LESSON 3 IO, Variables and Operators
Chapter 4 - Program Control
CS102 – Exceptions David Davenport Latest: May 2015
CSC 172 DATA STRUCTURES.
Stack Data Structure, Reverse Polish Notation, Homework 7
Method Mark and Lyubo.
CSC 253 Lecture 8.
Functions and Modular Programming
Scope, Parameter Passing, Storage Specifiers
Functions and Program Structure
CSC 253 Lecture 8.
Structured Programming (Top Down Step Refinement)
Functions and Modular Programming
Functions and Modular Programming
Govt. Polytechnic,Dhangar
Program Control Topics While loop For loop Switch statement
Week 2 Variables, flow control and the Debugger
Functions and Program Structure
Functions and Program Structure
C – Programming Language
Programming Languages and Paradigms
Homework K&R chapter 4.
C Language B. DHIVYA 17PCA140 II MCA.
Presentation transcript:

Reverse Polish Calculator Reverse Polish Notation 연산자가 피연산자의 뒤에 온다. 예 ) (1 – 2) * (4 + 5)  1 2 – * * 수식에서 괄호가 요구되지 않는다. ( 수식이 애매하지 않다 )

구현 방법 1) 피연산자는 stack(LIFO) 상에 push 2) 연산자가 입력되면 적절한 수의 피연산자를 pop 시킨다. ( 이항연산자  2 개 ) 3) 연산자를 pop 된 피연산자에 적용하고, 그 계 산 결과를 stack 상에 push 예 ) 1 2 – * 1) 1 과 2 는 stack 상에 push 2) – 를 만나면 stack 상의 2 개 자료를 pop 3) 이들의 차를 구한 (-1) 다음 이 결과값을 stack 에 push

1 ’ ) 4 와 5 를 stack 상에 push 2 ’ ) + 를 만날 때, stack 상의 2 개의 자료를 pop 3 ’ ) 4 와 5 를 더한 다음 그 결과 9 를 stack 상에 push 2 ’’ ) * 를 만나면 stack 상의 2 개의 자료를 pop (-1 과 9) 3 ’’ ) – 1 과 9 를 곱한 다음 그 결과 – 9 를 stack 에 push * newline 을 만나면 stack 상의 자료를 pop 한 다음 출력한다.

실행 과정 1 2 – * … stack 0sp 1 2 sp 4 5 sp 9 sp -9 sp

개략적인 프로그램 구성 While (next operator or operand is not EOF) if (number) push it else if (operator) pop operands do operation push result else if (newline) pop and print top of stack else error

#define MAXOP 100 #define NUMBER '0' int getop(char []); void push(double); double pop(void); /* reverse polish calculator */ main() { int type; 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("erroe: zero division\n"); break;

case '\n': printf("\t%.8g\n",pop()); break; default: printf("error: unknown command %s\n",s); break; } return 0; }

#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); }

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

#include int getch(void); void ungetch(int); /* getop: get next operator or numeric operand */ int getop(char s[]) { int i, c; while ((s[0] = c = getch()) == ' ' || c == '\t') ;

s[1] = '\0'; if (!isdigit(c) && c != '.') return c; i = 0; if (isdigit(c)) while (isdigit(s[++i] = c = getch())) ; if (c == '.') 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; 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; }

Scope rule( 유효범위 규칙 ) main() { … } /**********************************/ int sp = 0; double val[MAXVAL]; void push(double f) { … } double pop(void) { … }  sp, val 변수의 scope : 선언된 위치부터 파일 의 끝까지 (push, pop 에서 ok, main 에서 X, main 내에서 push 나 pop 도 X)

전역변수가 정의되기 전에 사용될 필요 가 있거나, 다른 파일에서 정의된다면 extern 선언이 반드시 요구됨. 선언 (declaration) vs 정의 (definition) 선언 : 변수의 속성 ( 타입 ) 을 지시 정의 : 기억장소 할당 예 ) 정의 int sp; double val[MAXVAL]; 예 ) 선언 extern int sp; extern double val[];

예 In file1: extern int sp; extern double val[]; void push(double f) { … } double pop(void) { … } In file2: int sp = 0; double val[MAXVAL];

Separate Compile Let us now consider dividing the calculator program into several source files. 1 st file : main (main.c) 2 nd file : push, pop (stack.c) 3 rd file : getop (getop.c) 4 th file : getch, ungetch (getch.c)

#define NUMBER ‘ 0 ’ void push(double); double pop(void); int getop(char []); int getch(void); void ungetch(int); calc.h Separate Compile #include #inlcude #include “ calc.h ” #define MAXOP 100 main() { … } main.c

getop.c #include #include “ calc.h ” int getop() { … } stack.c #include #include “ calc.h ” #define MAXVAL 100 int sp = 0; double val[MAXVAL]; void push(double) { … } double pop(void) { … } Separate Compile

getch.c #include #define BUFSIZE 100 char buf[BUFSIZE]; int bufp = 0; int getch(void) { … } void ungetch(int c) { … }

Turbo-C( 분리컴파일 ) Create the file rcalc.prj and put into it the name of each file that contains definitions of functions used in the program. The names may be separated by white space, commas, or semicolons. In file rcalc.prj: main.c (calc.h) getop.c (calc.h) stack.c (calc.h) getch.c(calc.h)

Select the Project menu from main menu line. Then in turn select Project name and type in the name rcalc.prj Now press Alt-r to make and run the program. Turbo-C project facility will recompile only those files that have been changed since the last time rcalc.exe was updated.

Static 변수 사용 예 Static 변수의 선언은 컴파일되는 파일의 나머지 부분에 대해서만 scope 를 제약하 는 기능 예 static char buf[BUFSIZE]; static int bufp = 0; int getch(void) { … }

C 전처리기 1.File inclusion #include “ filename ” #include 2. Macro 대치 #define name replacement text #define forever for(;;) #define max(A,B) ((A) > (B) ? (A) : (B)) #define square(x) ( (x) * (x) )