Skip to main content

Command Palette

Search for a command to run...

Escape Tutorial Hell: Build A Simple Calculator

Create a simple calculator in C

Published
6 min read
Escape Tutorial Hell: Build A Simple Calculator

Reading and utilizing official documentation can be difficult for inexperienced programmers like me. We frequently find ourselves learning or building projects using many coding tutorials or courses but never building any projects. This is what has popularly known as tutorial hell. One way to escape tutorial hell is to build simple projects that only require basic programming skills, such as a calculator.

Building a calculator is pretty straightforward and will solidify basic concepts, regardless of one’s skill level. All you need is a working knowledge of arithmetic operations and how to use “if…else” statements or the “switch case”. It goes without saying that you must also be familiar with how to declare variables and handle user input.

In this project, I cover creating a simple calculator program in the low-level language C. This calculator's functionality supports the 4 mathematical operations of addition, subtraction, multiplication, and division.

Besides this, the calculator will:

  • prompt the user to select a mathematical operation for the calculator to perform.
  • prompt the user to enter the 2 numbers to carry out the selected operation.
  • print the outcome of the operation after the calculation.

Prerequisites

  • A text editor (I used Vi)
  • Familiarity with the basic concepts of C (or any programming language).
  • Familiarity with essential Linux command-line commands.

Project Setup

First, open your terminal (in Linux) by pressing Ctrl, Alt, and T keys at the same time. Then create the folder that will hold all your files (the working directory) for the calculator project using the mkdir command. mkdir calculator

Then use the cd command to get into the working directory.

cd calculator

You can use the pwd (print working directory) command to ensure that you are in the correct working directory.

elsie_dev@Linux:~/calculator$ pwd

The output of this command should print the path to your directory, similar to this:

/home/elsie_dev/calculator

Now that we are in the correct directory, let us go ahead and create our project file. The name of the file that holds the code that runs the calculator must have a .c extension so that the compiler can recognize that the code therein is written in the C programming language.

To create the file, use the touch command, followed by the file name.

touch calculator.c

Use the ls command to be certain that the file was created.

elsie_dev@Linux:~/calculator$ ls
calculator.c

In the Vi editor, open the file using the command vi followed by the file name, i.e:

elsie_dev@Linux:~/calculator$ vi calculator.c

When opened in Vi, the empty file should look like this: vi.png

If using VS code, open the file using the format code as follows:

elsie_dev@Linux:~/calculator$ code calculator.c

Once the file is open, enter insert mode in Vi by pressing I on the keyboard. We can now start writing the calculator’s source code.

Coding The Calculator

The first statement in the code should be the directive #include <stdio.h>. The stdio.h library contains declarations for numerous functions and macros needed to receive input from input devices and display output on a C program's output screen. In this case, we want to use both the printf() and scanf() functions. We have to include stdio.h as a header file, or else the program will not recognize what the definition of printf() or scanf() is and will issue an error or warning stating that a function was implicitly declared.

Next, we declare our function. In C, a function declaration consists of the function’s name, return type, and parameters. In this program, the name of the function is main. All the code for the calculator program is contained in the main function. Its return type is an integer (int) and the function does not take in any parameters. The actual body of the function, known as the function declaration, will go in the curly brackets.

int main(void)
{

}

Now let's get into the actual code that gives the calculator its functionality.

First, we declare three variables, to represent the input that we expect from the user: ‘operator’, ‘num_1’, and ‘num_2’ with data types character and double respectively.

int main(void)
{
    char operator;
    double num_1, num_2;
}

After declaring the variables, ask the user to select an arithmetic operation for the calculator to carry out. Then use “scanf” to assign the user input to the variable that we have aptly named “operator”. Then we ask the user to enter any two numbers on which to perform the chosen operation and subsequently use scanf to assign them to the appropriate variables.

int main(void)
{
     char operator;
     double num_1, num_2;

     /*Ask user for input.*/
     printf("Select Operator (+, -, *, or /) : ");

     /*Assign user input to the variable operator.'*/
     scanf("%c", &operator);

     /*Ask the user to enter any two numbers on which to perform the operation.*/
     printf("Enter two numbers, one after another: ");

     /*Read user input and assign it to the two double variables.*/
     scanf("%lf %lf",&num_1,&num_2);    
}

Hereafter, we introduce the switch statement. In C, switch statements are decision-making tools. In a program where there are many alternative decisions, they evaluate a variable's value and compare it with several cases. Once the case that matches the variable in question is identified, the block of statements associated with that particular case is executed. “If…else…” statements allow you to accomplish the same task. However, the complexity of the program increases every time the number of potential paths increases.

The syntax of a switch statement in C is as follows:

switch(expression) {

   case constant-expression  :
      statement(s);
      break; /* optional */

   case constant-expression  :
      statement(s);
      break; /* optional */
 /* you can have any number of case statements */
   default : /* Optional */
   statement(s);
}

Note that the break statement terminates the switch statement.

Back to the calculator, below is the logic of the switch statement used for this calculator. We are using the switch statements to allow the user to choose a mathematical operator.

switch (operator)
{
    case '+':
        printf("%lf + %lf = %lf", num_1,num_2,(num_1+num_2));
        break;

    case '-':
        printf("%lf - %lf = %lf", num_1,num_2,(num_1-num_2));
        break;

    case '*':
        printf("%lf * %lf = %lf", num_1,num_2,(num_1*num_2));
        break;

    case '/':
        if (num_2 =! 0.0)
            printf("%lf / %lf = %lf",num_1,num_2,(num_1/num_2));
        else

            printf("Division by Zero");
        break;

    default:
        printf("Invalid Operator");
        break;
return (0);
}

The default statement is optional. In this case, it prints ‘Invalid Operator’ if the user selects an operator that is not supported by the calculator, e.g the modulus operator (%).

Conclusion

In this article, you’ve taken a step towards successfully escaping tutorial hell. I have shown you how to build a simple calculator in C. Find the source code referenced in this article on my Github. I hope this has inspired you to start building projects. You can go a step ahead and add more functionality to your calculator. If you enjoyed this article, please follow me as I continue to build projects and document them. Happy coding.