Calculator Program in C: Step-by-Step Guide

This calculator program in C is a fundamental program for beginners. This allows you to just perform basic operations like addition, subtraction z multiplication, and division. In this blog, we will. Learn to write a C program for a simple calculator using various operations like conditional statements and functions.

Learning to build this calculator will enhance problem-solving skills and also introduce key programming concepts like decision making, user input, and output formatting.

Blogging Illustration

Calculator Program in C: Step-by-Step Guide

image

In real-world scenarios, these programs gave practical applications such as automation of repetitive calculations, developing software tools, or even understanding the logic behind different mathematical operations in programming.

Option 1: Calculator Program in C Using switch case

Program code :

                    #include 

                    int main() {
                        char operator;
                        double num1, num2;

                        printf("Enter an operator (+, -, *, /): ");
                        scanf("%c", &operator);
                        printf("Enter two numbers: ");
                        scanf("%lf %lf", &num1, &num2);

                        switch (operator) {
                            case '+':
                                printf("%.2lf + %.2lf = %.2lf\n", num1, num2, num1 + num2);
                                break;
                            Case '-':
                                printf("%.2lf - %.2lf = %.2lf\n", num1, num2, num1 - num2);
                                break;
                            case '*':
                                printf("%.2lf * %.2lf = %.2lf\n", num1, num2, num1 * num2);
                                break;
                            Case '/':
                                if (num2 != 0)
                                    printf("%.2lf / %.2lf = %.2lf\n", num1, num2, num1 / num2);
                                else
                                    printf("Division by zero is not allowed.\n");
                                break;
                            Default:
                                printf("Invalid operator.\n");
                        }

                        return 0;
                    }

                    Output : 

                    Enter an operator (+, -, *, /): /
                    Enter two numbers: 900 10
                    900.00 / 10.00 = 90.00

                        

Explanation of code :

  • This C program for calculators just uses switch statements that will handle user input and also help in determining the operation.
  • Each set of arithmetic operations is just mapped to a particular case that will improve code readability and also efficiency for multiple sets of operations.

Option 2: C Program for a Calculator Using if-else

Program code :

                            #include 

                            int main() {
                                char operator;
                                double num1, num2;

                                printf("Enter an operator (+, -, *, /): ");
                                scanf("%c", &operator);
                                printf("Enter two numbers: ");
                                scanf("%lf %lf", &num1, &num2);

                                if (operator == '+')
                                    printf("%.2lf + %.2lf = %.2lf\n", num1, num2, num1 + num2);
                                else if (operator == '-')
                                    printf("%.2lf - %.2lf = %.2lf\n", num1, num2, num1 - num2);
                                else if (operator == '*')
                                    printf("%.2lf * %.2lf = %.2lf\n", num1, num2, num1 * num2);
                                else if (operator == '/')
                                    printf("%.2lf / %.2lf = %.2lf\n", num1, num2, num1 / num2);
                                else
                                    printf("Invalid operator.\n");

                                return 0;
                            }

                            Output : 

                            Enter an operator (+, -, *, /): *
                            Enter two numbers: 200 50
                            200.00 * 50.00 = 10000.00

                        

Explanation of code :

  • Using if-else, this calculator program in C will evaluate the operation based on the operator entered by the user.
  • This program will perform addition, subtraction, division, and multiplication.
  • This will just depend on the condition met.
  • This approach is also quite intuitive for all beginner learning programs.

Option 3: Simple Calculator Program in C Using Function

Program code :

                     #include 

                    double add(double a, double b) { return a + b; }
                    double subtract(double a, double b) { return a - b; }
                    double multiply(double a, double b) { return a * b; }
                    double divide(double a, double b) { return a / b; }

                    int main() {
                        char operator;
                        double num1, num2, result;

                        printf("Enter an operator (+, -, *, /): ");
                        scanf(" %c", &operator);
                        printf("Enter two numbers: ");
                        scanf("%lf %lf", &num1, &num2);

                        switch (operator) {
                            case '+': result = add(num1, num2); break;
                            case '-': result = subtract(num1, num2); break;
                            case '*': result = multiply(num1, num2); break;
                            case '/': 
                                if (num2 != 0)
                                    result = divide(num1, num2);
                                else {
                                    printf("Division by zero is not allowed.\n");
                                    return 0;
                                }
                                break;
                            default:
                                printf("Invalid operator.\n");
                                return 0;
                        }

                        printf("Result: %.2lf\n", result);
                        return 0;
                    }

                    Output : 

                    Enter an operator (+, -, *, /): +
                    Enter two numbers: 1043 383
                    Result: 1426.00

                        

Explanation of code :

  • This simple calculator program in C will use functions that will define separate functions for each of the arithmetic operations.
  • Code reusability is best possible with this modular approach and readability.
  • All this will make it quite easier to extend the program.

Option 4: Simple Calculator Program in C Using a Loop

Program code :

                    #include 

                    int main() {
                        char operator, choice;
                        double num1, num2;

                        do {
                            printf("Enter an operator (+, -, *, /): ");
                            scanf(" %c", &operator);
                            printf("Enter two numbers: ");
                            scanf("%lf %lf", &num1, &num2);

                            switch (operator) {
                                case '+': printf("%.2lf + %.2lf = %.2lf\n", num1, num2, num1 + num2); break;
                                case '-': printf("%.2lf - %.2lf = %.2lf\n", num1, num2, num1 - num2); break;
                                case '*': printf("%.2lf * %.2lf = %.2lf\n", num1, num2, num1 * num2); break;
                                case '/': 
                                    if (num2 != 0)
                                        printf("%.2lf / %.2lf = %.2lf\n", num1, num2, num1 / num2);
                                    else
                                        printf("Division by zero is not allowed.\n");
                                    break;
                                Default:
                                    printf("Invalid operator.\n");
                            }

                            printf("Do you want to perform another calculation? (y/n): ");
                            scanf(" %c", &choice);

                        } while (choice == 'y' || choice == 'Y');

                        return 0;
                    }

                    Output : 

                    Enter an operator (+, -, *, /): /
                    Enter two numbers: 22 9
                    22.00 / 9.00 = 2.44

                        

Explanation of code :

  • This C program for a calculator uses a loop that will allow multiple calculations without restarting the program.
  • The user can just continue performing operations until they choose to exit.
  • All this will make it interactive as well, ae user-friendly.

Option 5: Scientific program in C using Math library

Program code :

                        #include 
                        #include 

                        int main() {
                            int choice;
                            double num, result, base, exponent;

                            do {
                                printf("\n--- Scientific Calculator Menu ---\n");
                                printf("1. Sine\n2. Cosine\n3. Tangent\n4. Logarithm\n");
                                printf("5. Square Root\n6. Power\n7. Exponential (e^x)\n8. Exit\n");
                                printf("Enter your choice (1-8): ");
                                scanf("%d", &choice);

                                switch (choice) {
                                    Case 1:
                                        printf("Enter angle in degrees: ");
                                        scanf("%lf", &num);
                                        result = sin(num * M_PI / 180);
                                        printf("sin(%.2lf) = %.4lf\n", num, result);
                                        break;
                                    Case 2:
                                        printf("Enter angle in degrees: ");
                                        scanf("%lf", &num);
                                        result = cos(num * M_PI / 180);
                                        printf("cos(%.2lf) = %.4lf\n", num, result);
                                        break;
                                    Case 3:
                                        printf("Enter angle in degrees: ");
                                        scanf("%lf", &num);
                                        result = tan(num * M_PI / 180);
                                        printf("tan(%.2lf) = %.4lf\n", num, result);
                                        break;
                                    Case 4:
                                        printf("Enter a number: ");
                                        scanf("%lf", &num);
                                        if (num > 0)
                                            printf("log(%.2lf) = %.4lf\n", num, log(num));
                                        else
                                            printf("Logarithm of non-positive numbers is undefined.\n");
                                        break;
                                    Case 5:
                                        printf("Enter a number: ");
                                        scanf("%lf", &num);
                                        if (num >= 0)
                                            printf("sqrt(%.2lf) = %.4lf\n", num, sqrt(num));
                                        else
                                            printf("Square root of negative number is undefined.\n");
                                        break;
                                    Case 6:
                                        printf("Enter base and exponent: ");
                                        scanf("%lf %lf", &base, &exponent);
                                        printf("%.2lf ^ %.2lf = %.4lf\n", base, exponent, pow(base, exponent));
                                        break;
                                    Case 7:
                                        printf("Enter value of x: ");
                                        scanf("%lf", &num);
                                        printf("e^%.2lf = %.4lf\n", num, exp(num));
                                        break;
                                    Case 8:
                                        printf("Exiting Scientific Calculator.\n");
                                        break;
                                    Default:
                                        printf("Invalid choice. Try again.\n");
                                }

                            } while (choice != 8);

                            return 0;
                        }

                        Sample output : 

                        --- Scientific Calculator Menu ---
                        1. Sine
                        2. Cosine
                        3. Tangent
                        4. Logarithm
                        5. Square Root
                        6. Power
                        7. Exponential (e^x)
                        8. Exit
                        Enter your choice (1-8): 1
                        Enter angle in degrees: 30
                        sin(30.00) = 0.5000

                        

Explanation of code :

  • This program just uses math.h to perform a set of advanced mathematical functions.
  • Here we can see that the degree input is converted into radians since all these C functions expect radians.
  • Loop structure helps in making them interactive, like real scientific calculators.

Option 6: Financial calculator in C or EMI calculator

Program code :

                            #include 
                        #include 

                        int main() {
                            double principal, annualRate, timeInYears, monthlyRate, emi;
                            int months;

                            printf("Enter loan amount (principal): ");
                            scanf("%lf", &principal);

                            printf("Enter annual interest rate (in percent): ");
                            scanf("%lf", &annualRate);

                            printf("Enter loan tenure (in years): ");
                            scanf("%lf", &timeInYears);

                            months = timeInYears * 12;
                            monthlyRate = annualRate / (12 * 100);

                            emi = (principal * monthlyRate * pow(1 + monthlyRate, months)) /
                                (pow(1 + monthlyRate, months) - 1);

                            printf("\nEMI Details:\n");
                            printf("Loan Amount: ₹%.2lf\n", principal);
                            printf("Annual Interest Rate: %.2lf%%\n", annualRate);
                            printf("Loan Tenure: %.0lf years (%d months)\n", timeInYears, months);
                            printf("Monthly EMI: ₹%.2lf\n", emi);

                            return 0;
                        }

                        Sample Output : 

                        Enter loan amount (principal): 500000
                        Enter annual interest rate (in percent): 7.5
                        Enter loan tenure (in years): 5

                        EMI Details:
                        Loan Amount: ₹500000.00
                        Annual Interest Rate: 7.50%
                        Loan Tenure: 5 years (60 months)
                        Monthly EMI: ₹10013.05

                        

Explanation of code :

  • Here we can see that the standard EMI formula is used mentioned below :

    EMI = [P × r × (1+r)^n] / [(1+r)^n – 1]

    Where:

    P = principal, r = monthly interest rate, n = total months

  • You can use them in practical real-world applications like home, education, and car loans. etc

Real world scenario :

Grade Average and Result Calculator in C

Program code :

                            #include 

                    int main() {
                        int numSubjects, i;
                        double marks, total = 0, average;

                        printf("Enter the number of subjects: ");
                        scanf("%d", &numSubjects);

                        if (numSubjects <= 0 0) { printf("invalid number of subjects.\n"); return 0; } for (i="1;" i <="numSubjects;" i++) printf("enter marks subject %d: ", i); scanf("%lf", &marks); if (marks ||> 100) {
                                printf("Marks should be between 0 and 100. Try again.\n");
                                i--;
                                continue;
                            }

                            total += marks;
                        }

                        average = total / numSubjects;

                        printf("\nTotal Marks: %.2lf\n", total);
                        printf("Average Marks: %.2lf\n", average);

                        // Display grade
                        if (average >= 90)
                            printf("Grade: A+ (Excellent)\n");
                        else if (average >= 80)
                            printf("Grade: A (Very Good)\n");
                        else if (average >= 70)
                            printf("Grade: B (Good)\n");
                        else if (average >= 60)
                            printf("Grade: C (Average)\n");
                        else if (average >= 50)
                            printf("Grade: D (Pass)\n");
                        else
                            printf("Grade: F (Fail)\n");

                        return 0;
                    }

                    Sample Output : 

                    Enter the number of subjects: 5
                    Enter marks for subject 1: 78
                    Enter marks for subject 2: 82
                    Enter marks for subject 3: 91
                    Enter marks for subject 4: 65
                    Enter marks for subject 5: 87

                    Total Marks: 403.00
                    Average Marks: 80.60
                    Grade: A (Very Good)
                        

Explanation of code :

  • This program is known for taking user input for both the number of subjects and their marks.
  • It will validate and say the marks are in the range of 0 to 100.
  • It will calculate ate total and average, and it will print a grade just based on average marks.
  • Quite ideal for using in academic software, school project-related tools, and also for validation work in C.

For more such learning, enroll in theC programming course in Noida and increase your knowledge.

Placed Students

Our Clients

Partners

Uncodemy Learning Platform

Uncodemy Free Premium Features

Popular Courses