Skip to content
C project #01Beginner

Menu-Driven Calculator

A console calculator with seven operations, input validation and safe handling of division by zero.

Estimated time
~2 hours to build
Files
5 files · 299 lines
Technologies
C11, <stdio.h>, <math.h>

Introduction

This is the classic first C project, done properly. Instead of trusting the user to type valid numbers, it checks every scanf result, recovers from bad input and refuses mathematically undefined operations. You will practise breaking a program into small functions and driving it with a menu loop.

Problem statement

Build a program that repeatedly shows a menu of arithmetic operations, reads the user's choice and the operands, prints the result with sensible formatting, rejects invalid input without crashing, and reports how many calculations were performed when the user exits.

Objectives

  • Structure an interactive program around a menu loop
  • Validate numeric input using scanf's return value
  • Use <math.h> functions (fmod, pow, sqrt)
  • Handle error cases such as division by zero explicitly

Features

  • Addition, subtraction, multiplication, division, modulus, power and square root
  • Re-prompts on non-numeric input instead of looping forever
  • Rejects division/modulus by zero and square roots of negatives
  • Counts completed calculations and reports them on exit

Concepts demonstrated

  • Functions
  • switch
  • Input validation
  • Floating-point formatting

System architecture

The program has one loop in main that prints the menu, reads a choice and dispatches with a switch. A helper, read_number, owns all input validation: it loops until scanf("%lf", ...) succeeds, discarding the rest of a bad line with getchar. Each case computes and prints its result; error cases print a message and continue so they are not counted as calculations.

TextArchitecture diagram
+------------+ +-------------+ +----------------+
| print_menu | --> | read choice | --> | read_number(s) |
+------------+ +-------------+ +----------------+
|
v
+-----------------------+
| switch: compute/print |
+-----------------------+
|
(loop until choice 0)

Folder structure

TextProject tree
calculator/
├── README.md
├── Makefile
├── src/main.c
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

Makefile

20 lines
MakefileMakefile
# Generated for KENHOLT Skills. Usage: make | make test | make clean
CC = gcc
CFLAGS = -std=c11 -Wall -Wextra -O2
SRC := $(wildcard src/*.c)
HDR := $(wildcard src/*.h)
ARGS := $(shell cat tests/args.txt 2>/dev/null)
INPUT := $(wildcard tests/sample-input.txt)
app: $(SRC) $(HDR)
$(CC) $(CFLAGS) -Isrc $(SRC) -o app -lm
test: app
./app $(ARGS) $(if $(INPUT),< $(INPUT),) > actual.txt
diff actual.txt tests/expected-output.txt && echo "Test passed: output matches tests/expected-output.txt"
clean:
rm -f app app.exe actual.txt
.PHONY: test clean

What each file does

src/main.c
The whole program: read_number (validated input), print_menu, and the menu loop with one case per operation.
Makefile
Build automation: make builds ./app, make test runs the sample session and compares it with the expected output, make clean removes build files.

How to run it

Build

Terminal
gcc -std=c11 -Wall -Wextra -Isrc src/*.c -o app -lm
# or simply: make

Run

Terminal
./app # Linux / macOS
.\app.exe # Windows

Test against the expected output

Terminal
./app < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt # no output means they match
# Windows PowerShell:
# Get-Content tests\sample-input.txt | .\app.exe > actual.txt
# Compare-Object (Get-Content actual.txt) (Get-Content tests\expected-output.txt)

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
===== KENHOLT Calculator =====
1. Add 2. Subtract
3. Multiply 4. Divide
5. Modulus 6. Power
7. Square root 0. Exit
Choice:
First number:
Second number:
Result: 12.5 + 7.5 = 20
===== KENHOLT Calculator =====
1. Add 2. Subtract
3. Multiply 4. Divide
5. Modulus 6. Power
7. Square root 0. Exit
Choice:
First number:
Second number:
Error: division by zero is undefined.
===== KENHOLT Calculator =====
1. Add 2. Subtract
3. Multiply 4. Divide
5. Modulus 6. Power
7. Square root 0. Exit
Choice:
First number:
Second number:
Result: 2 ^ 10 = 1024
===== KENHOLT Calculator =====
1. Add 2. Subtract
3. Multiply 4. Divide
5. Modulus 6. Power
7. Square root 0. Exit
Choice:
First number:
Result: sqrt(81) = 9
===== KENHOLT Calculator =====
1. Add 2. Subtract
3. Multiply 4. Divide
5. Modulus 6. Power
7. Square root 0. Exit
Choice:
Unknown option 9.
===== KENHOLT Calculator =====
1. Add 2. Subtract
3. Multiply 4. Divide
5. Modulus 6. Power
7. Square root 0. Exit
Choice:
Goodbye.
Input
1
12.5
7.5
4
10
0
6
2
10
7
81
9
abc
0

Testing

  • Run the scripted session in tests/sample-input.txt and compare with tests/expected-output.txt.
  • Try dividing by zero and taking the square root of -4; both must print an error and return to the menu.
  • Type letters instead of a number for an operand; the program must ask again.
  • Press Ctrl+D (Linux/macOS) or Ctrl+Z then Enter (Windows) at the menu; it must exit cleanly.

Common errors

undefined reference to `pow'

On Linux, link the maths library by adding -lm at the end of the gcc command.

Program loops forever after typing letters

You removed the getchar loop in read_number; the bad characters stay in the input buffer and scanf fails again immediately.

Possible improvements

  • Keep a history of the last ten results and allow reusing the previous answer
  • Support expressions like 12 * (3 + 4) (see the Expression Evaluator project)
  • Add trigonometric and logarithmic functions

Additional challenges

  1. 1Add a memory feature (M+, M-, MR, MC).
  2. 2Print results as exact fractions when both inputs are integers and the result isn't.
  3. 3Accept input in a single line such as 12 + 30.

Built and tested it yourself? Mark it to update your dashboard.