HOW THE CODE WORKS
You may have noticed that this calculator isn't like many of the others you have seen. It allows you to enter expressions like 1+3*4
and then executes the expression when you press the equals key. The calculator also follows the mathematical rules for expressions containing multiplication and division operators. The answer to 1+3*4
is 13
, not 16
. Multiplication and division of terms is done before addition and subtraction.
So, how is this magic achieved? It is done using a technique called Top-down, recursive descent parsing. That's quite a mouthful, isn't it? It is also rather tedious to explain and this article would be far too long if I attempted to do so.
If you're interested in learning the technique, there is a series of articles written by Jack Crenshaw called Let's Build A Compiler. One of the articles in this series covers the development of a top-down, recursive descent expression parser, which is what you are after if you are thinking of building your own calculator. The article is very readable and you don't need a degree in Computer Science to understand it like you do with so many other articles on the subject on the Internet. It is located here: https://compilers.iecc.com/crenshaw/tutor2.txt
Don't worry if it takes you more than a few attempts to understand what Jack is talking about. Parsing is hard and requires study. And bare this in mind: it took them years in the 50s to work out how to do this stuff. "So, how long did it take you?" Not telling! :)
BTW if you build a calculator, drop me a message below and let me know where it is. I enjoy looking at them. Good luck!