100 likes | 209 Views
Experim ent 1. A genda. Problem description Reverse Polish notation Examples Structure of program Multiple files in a project. Problem description. The problem is to write a calculator program that provides the operators +, -, *and /.
E N D
Agenda • Problem description • Reverse Polish notation • Examples • Structure of program • Multiple files in a project
Problem description • The problem is to write a calculator program that provides the operators +, -, *and /. • The calculator will use reverse Polish notation instead of infix. Because it is easier to implement.
Reverse polish notation • Reverse Polish notation (RPN) is a mathematical notation in which every operator follows all of its operands. • The description "Polish" refers to the nationality of logician Jan Łukasiewicz, who invented (prefix) Polish notation in the 1920s.
Examples(1/3) • In reverse Polish notation the operators follow their operands; • to add 3 and 4, one would write "3 4 +" rather than "3 + 4". • If there are multiple operations, the operator is given immediately after its second operand; • "3 − 4 + 5" in conventional notation would be written "3 4 − 5 +" in RPN:
Examples(2/3) • RPN does not need parentheses that are required by infix. • “3 − 4 × 5” would be written as “3 4 5 × −” • “( 3 − 4 ) × 5” would be written as “3 4 - 5 × ”
Algorithm • While there are input tokens (operators or operand) left • Read the next token from input. • If the token is a operand • Push it onto the stack. • Otherwise, the token is an operator: • It is known a priori that the operator takes n arguments. • If there are fewer than n values on the stack • (Error) The user has not input sufficient values in the expression. • Else, Pop the top n values from the stack. • Evaluate the operator, with the values as arguments. • Push the returned results, if any, back onto the stack. • If there is only one value in the stack • That value is the result of the calculation. • Otherwise, there are more values in the stack • (Error) The user input has too many values.
Example(3/3) The infix expression "5 + ((1 + 2) × 4) − 3" can be written down like this in RPN: 5 1 2 + 4 × + 3 −
Structure of program • 4 source files and 1 head file: • calc.h contains declarations of global functions (external variable) and macro definitions • main.ccontains main function • stack.ccontains push/pop functions of stack • getop.ccontains getop() for fetching the next input token(opeator/operand) • getch.ccontains get a next character or push character back on input