Skip to content
Tutorials Center
My learning

Topics

Lesson 177 of 182 ยท Projects

Project: Console Calculator

Build an expression calculator in C# in three stages: a tokenizer, a recursive-descent parser with precedence, parentheses and functions, and clear error messages checked by a table of tests.

A calculator that reads 2 + 3 * (4 - 1) and prints 11 looks small, but it teaches one of the most useful ideas in programming: parsing. Compilers, query languages, template engines and spreadsheet formulas all turn text into a structure and then evaluate it. If you can write this calculator, you can read the next level of programs with confidence.

The key problem is precedence. A naive left-to-right calculation says 2 + 3 * 4 is 20; the correct answer is 14, because multiplication binds tighter. We will solve it cleanly in three stages:

Stage What you build Idea
1 A tokenizer Turn the string into numbers, operators and parentheses
2 A parser and evaluator One method per precedence level (recursive descent)
3 Errors and tests Report the position of a mistake; check a table of cases

The calculator uses double for simplicity. A pocket calculator for money should use decimal instead, as in the bank project. The lesson on floating-point numbers explains why 0.1 + 0.2 prints a surprising result with double.

Stage 1: the tokenizer

A tokenizer (or lexer) reads characters and groups them into tokens: a number such as 3.14, an operator such as +, a parenthesis, or an identifier such as sqrt. Everything else (spaces) is skipped. Splitting the work this way means the parser later never has to think about digits or whitespace.

We represent a token as a small record with a kind, its text and its position in the input. Keeping the position lets us point at the mistake later.

C# Stage 1: tokenizing an expression

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The numbers are cut out with the range operator (text[start..i], see ranges and indices). A final End token means the parser never has to check for "running off the array".

Stage 2: the parser and evaluator

Now the interesting part. We express the grammar as one method per precedence level, from loosest to tightest:

Text
expression = term   { ("+" | "-") term }
term       = unary  { ("*" | "/" | "%") unary }
unary      = "-" unary | power
power      = primary [ "^" unary ]          (right-associative)
primary    = number | name | name "(" args ")" | "(" expression ")"

Read it as: an expression is a sum of terms; a term is a product of unary items; and so on down to the smallest pieces, numbers and parenthesized expressions. Because expression calls term and term calls unary, multiplication is automatically evaluated before addition. This technique is called recursive descent, and each method is only a few lines.

Two details deserve attention:

  • ^ (power) is right-associative: 2 ^ 3 ^ 2 means 2 ^ (3 ^ 2) = 512. We get that by parsing the right side with unary, which can contain another power.
  • Unary minus is below * but above ^ in our grammar, so -2 ^ 2 is -(2 ^ 2) = -4, as in most math notation.
C# Stage 2: a recursive-descent calculator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Check the surprising rows against the grammar. 7 % 4 + 2 * -3 is 3 + (2 * -3) = -3. 2 ^ 3 ^ 2 is 512 because power is right-associative. And -2 ^ 2 is -4, not 4. Because every method is tiny and mirrors one line of the grammar, adding a new operator or function is a one-line change: add an entry to Functions for round, sqrt or abs.

Stage 3: errors and tests

Users make mistakes: 2 +, (3 * 4, sqrt(, 5 / 0, foo(3). A good calculator does not crash with a stack trace. It says what went wrong and where, and keeps running. There are two parts to doing that well.

First, throw one specific exception type (CalcException) that carries the position, and catch it once in the main loop. Second, check unknown names and arity (the number of arguments) before using them, so you do not leak internal exceptions such as KeyNotFoundException.

Division by zero deserves a decision. With double, 1 / 0 gives Infinity without any exception, which is almost never what a user wants, so we check the result and report an error.

Finally, tests. A parser is the perfect candidate for table-driven tests: a list of (input, expected) pairs, plus a list of inputs that must fail. The real project would use xUnit; here a tiny runner does the same job.

C# Stage 3: friendly errors and a table of tests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Take a moment to read the last two lines of output. Because every error carries a position, you can print a caret under the mistake, the same way compilers do. The tests are both a safety net and documentation: each row states one rule of the language.

Never hand untrusted text to something like eval or a general-purpose scripting engine to calculate it. A parser that you control, with a fixed grammar and a fixed function list, cannot do anything except arithmetic.

Making it interactive

The programs above use fixed samples because the online editor has no keyboard. At a real terminal the main loop is only a few lines:

C#
// Read-only: the interactive loop (needs a real console).
Console.WriteLine("Type an expression, or 'quit'.");
while (true)
{
    Console.Write("> ");
    string? line = Console.ReadLine();
    if (line is null || line.Trim() == "quit") { break; }

    var result = Calc.Run(line);
    Console.WriteLine(result.Error is null ? result.Value : $"Error: {result.Error}");
}

Ideas to extend it

  1. Variables: x = 5 stores a value in a dictionary; later expressions can use x.
  2. History: an ans constant that holds the last result.
  3. Switch to decimal for money-style arithmetic and compare the output of 0.1 + 0.2 in both types.
  4. Build a tree: instead of calculating while parsing, return an expression tree of nodes (Add, Multiply, Number) and evaluate it separately. This is how real compilers work, and it ties in with expression trees and pattern matching.
  5. More tests: turn the table into xUnit theory data.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a tokenizer do?

    A tokenizer turns raw text into a list of tokens so the parser can work with meaningful units instead of single characters.
  2. 2. In recursive descent, how is operator precedence expressed?

    expression calls term, term calls unary, and so on, so multiplication binds tighter than addition automatically.
  3. 3. What is the value of 2 ^ 3 ^ 2 in our calculator?

    Power is right-associative: it is 2 ^ (3 ^ 2) = 2 ^ 9 = 512, not (2 ^ 3) ^ 2 = 64.
  4. 4. Why should errors carry a position?

    With a position you can print a caret under the problem, which is far more helpful than a generic message.
  5. 5. Why does the calculator check for a zero divisor itself?

    Floating-point division by zero gives Infinity or NaN instead of an exception, so the calculator reports a clear error.

Summary

  • Parsing has two phases: a tokenizer that groups characters, and a parser that gives the tokens structure.
  • Recursive descent uses one small method per grammar rule; precedence comes from the order of the calls, and right-associativity from recursing on the right-hand side.
  • Report errors with a specific exception that carries a position, and validate names and argument counts before using them.
  • Table-driven tests (good inputs with expected results, bad inputs with expected messages) document and protect the grammar.
  • Never use eval-style execution for user input; a fixed grammar is safe.

Next: keep practicing with advanced exercises, or look back at the Library Management project.