Making a Simple Calculator Using C

CCBeginner
Practice Now

Introduction

In this project, we will learn how to create a simple calculator using the C programming language. The calculator will be capable of performing basic arithmetic operations such as addition, subtraction, multiplication, and division. We will also implement checks to ensure that the user input is valid and handle cases where the input leads to undefined behavior.

👀 Preview

$ ./Calculator
32+11
=43.000000

$ ./Calculator
41-34.9
=6.100000

$ ./Calculator
10/2
=5.000000

$ ./Calculator
2*4
=8.000000

$ ./Calculator
10%3
=1

🎯 Tasks

In this project, you will learn:

  • How to get user input in C using scanf()
  • How to check the format of the input arithmetic expression
  • How to perform arithmetic calculations based on the user input
  • How to handle division by zero errors
  • How to implement the remainder operator only for integer operands

🏆 Achievements

After completing this project, you will be able to:

  • Understand how to get user input in C
  • Implement different arithmetic operations in C
  • Perform error checking and handle invalid input
  • Compile and run C programs using the gcc compiler

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("`C`")) -.-> c/UserInteractionGroup(["`User Interaction`"]) c(("`C`")) -.-> c/BasicsGroup(["`Basics`"]) c(("`C`")) -.-> c/ControlFlowGroup(["`Control Flow`"]) c(("`C`")) -.-> c/PointersandMemoryGroup(["`Pointers and Memory`"]) c(("`C`")) -.-> c/FunctionsGroup(["`Functions`"]) c/UserInteractionGroup -.-> c/output("`Output`") c/BasicsGroup -.-> c/comments("`Comments`") c/BasicsGroup -.-> c/variables("`Variables`") c/BasicsGroup -.-> c/data_types("`Data Types`") c/BasicsGroup -.-> c/operators("`Operators`") c/ControlFlowGroup -.-> c/if_else("`If...Else`") c/ControlFlowGroup -.-> c/switch("`Switch`") c/ControlFlowGroup -.-> c/break_continue("`Break/Continue`") c/UserInteractionGroup -.-> c/user_input("`User Input`") c/PointersandMemoryGroup -.-> c/memory_address("`Memory Address`") c/PointersandMemoryGroup -.-> c/pointers("`Pointers`") c/FunctionsGroup -.-> c/function_parameters("`Function Parameters`") c/FunctionsGroup -.-> c/function_declaration("`Function Declaration`") subgraph Lab Skills c/output -.-> lab-298833{{"`Making a Simple Calculator Using C`"}} c/comments -.-> lab-298833{{"`Making a Simple Calculator Using C`"}} c/variables -.-> lab-298833{{"`Making a Simple Calculator Using C`"}} c/data_types -.-> lab-298833{{"`Making a Simple Calculator Using C`"}} c/operators -.-> lab-298833{{"`Making a Simple Calculator Using C`"}} c/if_else -.-> lab-298833{{"`Making a Simple Calculator Using C`"}} c/switch -.-> lab-298833{{"`Making a Simple Calculator Using C`"}} c/break_continue -.-> lab-298833{{"`Making a Simple Calculator Using C`"}} c/user_input -.-> lab-298833{{"`Making a Simple Calculator Using C`"}} c/memory_address -.-> lab-298833{{"`Making a Simple Calculator Using C`"}} c/pointers -.-> lab-298833{{"`Making a Simple Calculator Using C`"}} c/function_parameters -.-> lab-298833{{"`Making a Simple Calculator Using C`"}} c/function_declaration -.-> lab-298833{{"`Making a Simple Calculator Using C`"}} end

Get User Input

Getting user input is very simple, you can use the C language's formatted input-output functions printf() and scanf().

Here is the program code responsible for reading user input:

#include<stdio.h>
int main()
{
   double number1=0.0;     // Define the first operand
   double number2=0.0;     // Define the second operand
   char operation=0;       // operation should be '+' '-' '*' '/' or '%'

   printf("\nEnter the calculation\n");
   scanf("%lf%c%lf",&number1,&operation,&number2);

   return 0;
}

Checking the Format and Performing Calculations

The next functionality that our program needs to implement is to check the format of the input arithmetic expression.

The most basic check is to determine if the operation specified in the input expression is valid. The valid operations are +, -, *, /, %, so we need to check if the input operation belongs to this set.

Additionally, it is important to note that when the operation is / or %, the second operand cannot be 0. If it is 0, the operation is invalid.

The logic for these checks can be implemented using if statements. Alternatively, a switch statement provides a better and more concise way to handle this. It is easier to understand and less verbose compared to a series of if statements.

switch(operation)
{
    case '+':
        printf("=%lf\n",number1+number2);
        break;

    case '-':
        printf("=%lf\n",number1-number2);
        break;

    case '*':
        printf("=%lf\n",number1*number2);
        break;

    case '/':
        if(number2==0)
            printf("\n\n\aDivision by zero error!\n");
        else
            printf("=%lf\n",number1/number2);
        break;

    case '%':
        if((long)number2==0)
            printf("\n\n\aDivision by zero error!\n");
        else
            printf("=%ld\n",(long)number1%(long)number2);
        break;

    default:
        printf("\n\n\aInvalid operation!\n");
        break;
}

The remainder operator % is not meaningful for float or double types, as they can represent precise results. The % operator is only meaningful when applied to integer types. Therefore, before applying this operator, the operands need to be converted to integers. When the operator is %, the second operand is converted to an integer. Therefore, it is not sufficient to only check if the second operand is 0, but also whether the value of number2 is 0. when converted to a long. For example, 0.5 is not 0, but when converted to an integer, it becomes 0.

Compiling and Running Files

After writing the program file, you can compile the source file to obtain an executable file. The command for compiling is as follows:

gcc -o Calculator Calculator.c

Note: The format of the gcc command above is gcc -o output_filename source_filename.c. If no "output_filename" is provided, the default output filename is a.out.

At this point, you will notice a new file named Calculator in the directory. This is the executable file we obtained after compiling and linking the source file. To run it, use the command ./Calculator.

./Calculator
$ ./Calculator
32+11
=43.000000

$ ./Calculator
41-34.9
=6.100000

$ ./Calculator
10/2
=5.000000

$ ./Calculator
2*4
=8.000000

$ ./Calculator
10%3
=1

Summary

In this project, we used C language to create a simple calculator. Currently, the calculator has limited functionality and can only support basic calculations with two operands. Students can continue to expand on this calculator, such as adding support for multiple operands or introducing operator precedence mechanisms.

Other C Tutorials you may like