Calculator Project in C
Projects are where everything you've learned comes together: loops, switch, functions, input checking and the math library. The first one is a classic: a menu-driven calculator that keeps running until the user chooses Exit.
In this project you will build the calculator step by step, protect it from bad input (division by zero, square root of a negative number, letters instead of numbers), and then write a second version that reads expressions like 12 * 3 and remembers a history of results.
What You Will Learn
- How to plan a small project before coding.
- How to build a menu loop with
whileandswitch. - How to split work into functions.
- How to check
scanf's return value and handle errors. - How to use
pow()andsqrt()frommath.h. - How to store a history of results in an array.
Calculator Project in C Explained
Exam definition: A menu-driven program displays a list of options, reads the user's choice and performs the selected operation, repeating until the user selects an exit option. It is usually built with an infinite loop (while (1) or do-while) containing a switch statement, where each case handles one option and an exit case ends the loop.
Memory trick: A menu-driven program is a restaurant waiter: show the menu, take the order, serve it, and come back with the menu again, until the customer says "bill, please" (Exit). The switch is the kitchen deciding which dish to cook.
Project plan
| Part | What it does | C feature |
|---|---|---|
| Menu | Show options 0 to 6 | printf in a function |
| Loop | Repeat until choice 0 | while (1) + break |
| Choice | Run the selected operation | switch |
| Input | Read numbers safely | scanf return value |
| Math | Power and square root | pow(), sqrt() (link with -lm) |
| Errors | Divide by zero, negative root, wrong choice | if checks, default case |
Syntax: The Menu-Driven Skeleton
int main(void)
{
int choice;
while (1)
{
show_menu();
if (scanf("%d", &choice) != 1) /* letters typed instead of a number */
break;
if (choice == 0)
break; /* Exit */
switch (choice)
{
case 1: /* add */ break;
case 2: /* subtract */ break;
/* ... */
default: printf("Invalid choice\n");
}
}
return 0;
}
Compile with the math library: gcc calculator.c -o calculator -lm.
Example 1: Menu-Driven Calculator
#include <stdio.h>
#include <math.h>
void show_menu(void)
{
printf("\n===== CALCULATOR =====\n");
printf("1. Add 2. Subtract\n");
printf("3. Multiply 4. Divide\n");
printf("5. Power 6. Square root\n");
printf("0. Exit\n");
printf("Enter choice: ");
}
int read_two(double *a, double *b)
{
printf("Enter two numbers: ");
return scanf("%lf %lf", a, b) == 2;
}
int main(void)
{
int choice;
double a, b;
while (1)
{
show_menu();
if (scanf("%d", &choice) != 1)
{
printf("Please enter a number. Bye!\n");
return 1;
}
if (choice == 0)
{
printf("Thank you for using the calculator!\n");
break;
}
switch (choice)
{
case 1:
if (read_two(&a, &b))
printf("Result: %g + %g = %g\n", a, b, a + b);
break;
case 2:
if (read_two(&a, &b))
printf("Result: %g - %g = %g\n", a, b, a - b);
break;
case 3:
if (read_two(&a, &b))
printf("Result: %g x %g = %g\n", a, b, a * b);
break;
case 4:
if (read_two(&a, &b))
{
if (b == 0)
printf("Error: cannot divide by zero\n");
else
printf("Result: %g / %g = %g\n", a, b, a / b);
}
break;
case 5:
if (read_two(&a, &b))
printf("Result: %g ^ %g = %g\n", a, b, pow(a, b));
break;
case 6:
printf("Enter a number: ");
if (scanf("%lf", &a) == 1)
{
if (a < 0)
printf("Error: square root of a negative number\n");
else
printf("Result: sqrt(%g) = %g\n", a, sqrt(a));
}
break;
default:
printf("Invalid choice, try again\n");
}
}
return 0;
}
Output
===== CALCULATOR ===== 1. Add 2. Subtract 3. Multiply 4. Divide 5. Power 6. Square root 0. Exit Enter choice: 1 Enter two numbers: 12 8 Result: 12 + 8 = 20 ===== CALCULATOR ===== 1. Add 2. Subtract 3. Multiply 4. Divide 5. Power 6. Square root 0. Exit Enter choice: 4 Enter two numbers: 7 0 Error: cannot divide by zero ===== CALCULATOR ===== 1. Add 2. Subtract 3. Multiply 4. Divide 5. Power 6. Square root 0. Exit Enter choice: 5 Enter two numbers: 2 10 Result: 2 ^ 10 = 1024 ===== CALCULATOR ===== 1. Add 2. Subtract 3. Multiply 4. Divide 5. Power 6. Square root 0. Exit Enter choice: 9 Invalid choice, try again ===== CALCULATOR ===== 1. Add 2. Subtract 3. Multiply 4. Divide 5. Power 6. Square root 0. Exit Enter choice: 0 Thank you for using the calculator!
Code Explanation
show_menu()prints the options. Putting it in a function keepsmainshort and lets us call it on every loop.while (1)repeats forever; the only ways out are choice 0 (break) or invalid input (return 1).read_two()asks for two numbers and returns 1 only ifscanfread both. Checking the return value protects us from input like "abc".- Each
casedoes one job and ends withbreak, so control doesn't fall into the next case. - Division and square root have their own error checks;
defaultcatches any choice that isn't on the menu. %gprints a number without useless zeros: 20 instead of 20.000000, but 3.5 stays 3.5.
How the Program Flows
┌──────────────┐
│ show menu │◄─────────────────────┐
└──────┬───────┘ │
▼ │
read choice ── not a number ──► exit │
│ │
choice == 0 ? ── yes ──► "Thank you", exit
│ no │
▼ │
switch(choice): add / sub / mul / │
div / pow / sqrt / invalid ───────────┘
Testing tip: always test the normal cases (12 + 8), the edge cases (divide by 0, sqrt of −4) and wrong input (choice 9, letters). A project is finished only when all three kinds work.
Example 2: Expression Calculator with History
This version reads a whole expression such as 12 * 3 on one line and stores the last results in an array. Type q to quit.
#include <stdio.h>
#define MAX_HISTORY 5
double history[MAX_HISTORY];
int count = 0;
void save(double value)
{
int i;
if (count == MAX_HISTORY) /* full: drop the oldest */
{
for (i = 1; i < MAX_HISTORY; i++)
history[i - 1] = history[i];
count--;
}
history[count++] = value;
}
int main(void)
{
double a, b, r;
char op;
int i, ok;
printf("Enter expressions like 12 + 3 (q to quit)\n");
while (1)
{
printf("> ");
if (scanf("%lf %c %lf", &a, &op, &b) != 3)
break; /* 'q' or bad input ends the loop */
ok = 1;
switch (op)
{
case '+': r = a + b; break;
case '-': r = a - b; break;
case '*': r = a * b; break;
case '/':
if (b == 0) { printf("Error: divide by zero\n"); ok = 0; }
else r = a / b;
break;
default:
printf("Unknown operator '%c'\n", op);
ok = 0;
}
if (ok)
{
printf("= %g\n", r);
save(r);
}
}
printf("\nHistory (oldest first):\n");
for (i = 0; i < count; i++)
printf("%d) %g\n", i + 1, history[i]);
return 0;
}
Output
Enter expressions like 12 + 3 (q to quit) > 12 + 30 = 42 > 7 / 2 = 3.5 > 2.5 * 4 = 10 > 9 / 0 Error: divide by zero > 15 % 4 Unknown operator '%' > q History (oldest first): 1) 42 2) 3.5 3) 10
scanf("%lf %c %lf", ...)reads a number, an operator character and another number. The spaces in the format skip any spaces the user types.- When the user types
q,scanfcan't read a number, returns 0, and the loop ends. One check handles both "quit" and bad input. - Only successful results are saved. When the history is full,
save()shifts everything left to make room, so the newest 5 results are kept.
Important Points to Remember
- Menu-driven programs = loop + menu + switch + exit option.
- Put the menu and repeated steps in functions.
- Always check scanf's return value before using the numbers.
- Handle edge cases: division by zero, negative square root, invalid choice.
- End each case with break; use default for wrong choices.
- Link the math library with -lm when you use
poworsqrt.
Common Mistakes Beginners Make
| Mistake | What happens | Fix |
|---|---|---|
Missing break in a case | The next operation also runs | End every case with break |
| Not checking scanf | Typing a letter causes an endless loop | if (scanf(...) != 1) stop or clear input |
Using int for division | 7 / 2 gives 3 | Use double |
Forgetting -lm | "undefined reference to pow" | gcc calc.c -lm |
| No exit option | The user must close the window | Add "0. Exit" with break |
Calculator Project Practice Questions
- What is a menu-driven program? Which statements are used to build one?
- Why do we check the return value of
scanf? - Which two edge cases does the calculator handle, and how?
- Why is
%gused to print the result? - What does the
-lmoption do?
Show answers
- A program that shows options, performs the chosen one and repeats until exit; built with a loop and a switch statement.
- scanf returns how many values it read; if the user types invalid input, the variables aren't filled, so we must stop or ask again.
- Division by zero (checks b == 0) and square root of a negative number (checks a < 0); each prints an error instead of calculating.
- It prints numbers in the shortest form, without trailing zeros (20 instead of 20.000000).
- It links the math library, which contains pow, sqrt and other math.h functions.
Coding Exercise
Write functions double percentage(double part, double total) and double average3(double a, double b, double c) for the calculator. Print 45 out of 60 as a percentage and the average of 78, 85 and 92. Handle total == 0.
Show solution
#include <stdio.h>
double percentage(double part, double total)
{
if (total == 0)
{
printf("Error: total is zero\n");
return 0;
}
return part * 100.0 / total;
}
double average3(double a, double b, double c)
{
return (a + b + c) / 3.0;
}
int main(void)
{
printf("45 out of 60 = %.2f%%\n", percentage(45, 60));
printf("Average of 78, 85, 92 = %.2f\n", average3(78, 85, 92));
printf("10 out of 0 = %.2f%%\n", percentage(10, 0));
return 0;
}
45 out of 60 = 75.00% Average of 78, 85, 92 = 85.00 Error: total is zero 10 out of 0 = 0.00%
Add them to the menu as options 7 and 8 to extend your calculator.
Quick Quiz: Calculator Project (MCQ)
-
Which statement is best for choosing an operation from a menu number?
A) for B) switch C) goto D) return
-
scanf("%lf %lf", &a, &b)returns 2 when:A) Both numbers were read B) An error happened C) a equals b D) Always
-
Which header declares
sqrt()?A) stdio.h B) stdlib.h C) math.h D) string.h
-
What happens without
breakat the end of case 1?A) Compile error B) Case 2 also runs C) The loop ends D) Nothing
-
Printing 20.0 with
%gshows:A) 20.000000 B) 20 C) 2e1 D) 20.0
Show answers
- B: switch.
- A: both numbers were read.
- C: math.h.
- B: case 2 also runs (fall-through).
- B: 20.
Quick Revision for Exams and Interviews
Read this before your exam. The highlighted words are the answer.
Must-remember facts
| Menu program | Loop + switch + exit option |
|---|---|
| Infinite loop | while (1) ended with break |
| Wrong choice | Handled by default |
| Safe input | Check scanf's return value |
| Edge cases | Divide by zero, negative sqrt |
| pow, sqrt | math.h, compile with -lm |
| %g | Prints numbers without extra zeros |
Frequently asked questions
- How do you make a simple calculator in C?
- Read two numbers and an operation, use a switch to perform it, and wrap it in a loop with an exit option.
- How do you prevent division by zero?
- Check if the divisor is 0 before dividing and print an error instead.
- Why does typing a letter break a scanf loop?
- scanf fails and leaves the letter in the input, so it fails again forever; check the return value and stop or clear the input.
Remember
- Menu program = waiter: show, take order, serve, repeat.
- Test normal, edge and wrong input.
Next Topic
Next lesson: Number Guessing Game in C. You will use random numbers and loops to build a number guessing game.