Skip to content

Emsa001/C_calculator

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Calculator in C

Why a Calculator in C?

This project was developed as part of a challenge to implement a calculator in "exam mode." This means it was coded without any external help or internet access, relying purely on knowledge and problem-solving skills.

How It Works

The calculator processes mathematical expressions by first tokenizing the input string. Each character is identified as part of a number or an operator, and operators are assigned priorities to ensure correct order of operations.

Tokenization Example

Given the equation:

2 + 2 * 3

It is tokenized as:

(N) [2]
(O) [+] - (priority: 1)
(N) [2]
(O) [*] - (priority: 2)
(N) [3]

Here, multiplication * has a higher priority than addition +, ensuring the correct calculation order.

Handling Brackets

Brackets () modify the priority of operators, enforcing a different order of evaluation.

Example:

(2 + 2) * 3

Tokenized as:

(N) [2]
(O) [+] - (priority: 4)
(N) [2]
(O) [*] - (priority: 2)
(N) [3]

Since the addition is inside parentheses, its priority is increased, ensuring it is evaluated before multiplication.

Supported Operators

The calculator currently supports the following operators:

  • + (Addition)
  • - (Subtraction)
  • * (Multiplication)
  • / (Division)
  • ^ (Exponentiation)

Handling Negative Numbers

The tokenizer correctly identifies negative numbers, even in complex expressions with multiple negative signs.

Example:

-1 + -2 * ------3 / ---4

Tokenized as:

(N) [-1]
(O) [+] - (priority: 1)
(N) [-2]
(O) [*] - (priority: 2)
(N) [3]
(O) [/] - (priority: 2)
(N) [-4]

This ensures proper evaluation of negative numbers and consecutive negative signs.

Summary

  • Expressions are tokenized and operators are assigned priorities.
  • Brackets increase operator priority for correct evaluation.
  • Supports basic arithmetic operations and exponentiation.
  • Properly handles negative numbers and chained negative signs.

About

I was bored

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages