A Simple Calculator

Of course computers can do math! Of course, programming has some math in it! Yet one reason that programmers are not necessarily geniuses at math is that it’s the computer that does the math, not the programmer. To prove that truth, why not code your very own calculator program?

Forget about being all fancy with a display, scrolling input list, or other eloquent doodads. The most basic calculator program uses simple equation input: Type the first operand, the symbol, and then the second operand. It looks something like this:

Enter math equation:
 value [+-*/] value : 2 * 16

Then the program then makes the calculation and display the results, something like this:

2.00 * 16.00 = 32.00

The input can be handled by a single scanf() function.

Here’s the code snippet:

#include <stdio.h>

int main()
{
    float first,second;
    char symbol;

    puts("Enter math equation:");
    printf(" value [+-*/] value : ");
    scanf("%f %c %f",&first,&symbol,&second);

/* Perform Calculations Here */

    return(0);
}

Your job is to write the meat of the program, the part that takes variables first and second and performs some type of arithmetic wizardry on both. How you do that exactly is this month’s exercise.

Keep in mind you need to perform only the four basic operations: addition, subtraction, multiplication, and division.

The scanf() function helps you by limiting input to only the three types of variables listd: float, char, and float. Even so, your code also needs to handle what happens when an illegal operator (char) is input. That shouldn’t be too terrible.

As usual, please avoid peeking at my solution until you’ve given this one a stab. And keep in mind that you have multiple ways of solving this puzzle, some of which are better than others but nothing in C is considered the absolute perfect answer.

Exercise Solution

Leave a Reply