Calculator program in C

A calculator program in C is a computer program that allows users to perform mathematical calculations interactively. It typically takes input from the user in the form of arithmetic expressions and evaluates them to produce the corresponding result.

The main components of a calculator program in C include:

  1. User Input: The program prompts the user to enter an arithmetic expression, which can consist of numbers, operators, and parentheses. The input can be obtained using functions like fgets() or scanf().

  2. Parsing: Once the input is obtained, the program needs to parse the expression to understand its structure and identify the operands and operators involved. This is usually done using string manipulation techniques, such as tokenization and parsing algorithms.

  3. Evaluation: After parsing the expression, the program evaluates it to calculate the result. This involves applying the arithmetic operators to the operands according to the rules of precedence and associativity. The evaluation can be performed using loops, conditionals, and mathematical functions provided by the C programming language.

  4. Error Handling: A well-designed calculator program includes error handling mechanisms to detect and handle invalid input or unexpected situations. This may involve checking for division by zero, detecting mismatched parentheses, identifying invalid characters, and displaying appropriate error messages to the user.

  5. Advanced Functionality: Advanced calculator programs may offer additional features such as support for trigonometric functions, logarithms, exponentiation, memory storage, scientific notation, and more. These functionalities require implementing more complex algorithms or utilizing standard math libraries available in C.

Here's a simplified example of a calculator program in C:

#include <stdio.h>
#include <stdlib.h>

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

    printf("Enter an arithmetic expression: ");
    scanf("%lf %c %lf", &num1, &operator, &num2);

    switch (operator) {
        case '+':
            result = num1 + num2;
            break;
        case '-':
            result = num1 - num2;
            break;
        case '*':
            result = num1 * num2;
            break;
        case '/':
            if (num2 != 0)
                result = num1 / num2;
            else {
                printf("Error: Division by zero!\n");
                exit(1);
            }
            break;
        default:
            printf("Error: Invalid operator!\n");
            exit(1);
    }

    printf("Result: %.2f\n", result);

    return 0;
}

In this program, the user is prompted to enter an arithmetic expression consisting of two numbers and an operator. The program uses a switch statement to perform the corresponding arithmetic operation based on the operator entered by the user. The result is then displayed on the screen.

This example demonstrates a basic calculator program that handles simple arithmetic operations and includes error handling for division by zero and invalid operators.

Below is an example of a calculator program written in C that includes error handling for invalid input and some advanced functionalities such as handling parentheses and exponentiation:

#include <stdio.h>

#include <stdlib.h>
#include <ctype.h>
#include <math.h>

#define MAX_EXPRESSION_LENGTH 100

typedef enum {
    OPERATOR_PLUS,
    OPERATOR_MINUS,
    OPERATOR_MULTIPLY,
    OPERATOR_DIVIDE,
    OPERATOR_EXPONENT,
    OPERATOR_NONE
} Operator;

typedef struct {
    double value;
    Operator op;
} Operand;

Operand evaluateExpression(char* expression);

Operator getOperator(char opChar) {
    switch (opChar) {
        case '+':
            return OPERATOR_PLUS;
        case '-':
            return OPERATOR_MINUS;
        case '*':
            return OPERATOR_MULTIPLY;
        case '/':
            return OPERATOR_DIVIDE;
        case '^':
            return OPERATOR_EXPONENT;
        default:
            return OPERATOR_NONE;
    }
}

double applyOperator(Operator op, double a, double b) {
    switch (op) {
        case OPERATOR_PLUS:
            return a + b;
        case OPERATOR_MINUS:
            return a - b;
        case OPERATOR_MULTIPLY:
            return a * b;
        case OPERATOR_DIVIDE:
            return a / b;
        case OPERATOR_EXPONENT:
            return pow(a, b);
        default:
            return 0;
    }
}

Operand evaluateOperand(char* expression, int* index) {
    Operand operand;
    operand.value = 0;
    operand.op = OPERATOR_NONE;

    // Skip any leading whitespace
    while (isspace(expression[*index]))
        (*index)++;

    // Handle parentheses
    if (expression[*index] == '(') {
        (*index)++;
        operand = evaluateExpression(expression);
        if (expression[*index] == ')')
            (*index)++;
        else {
            printf("Error: Mismatched parentheses.\n");
            exit(1);
        }
    } else {
        char* endptr;
        operand.value = strtod(&expression[*index], &endptr);
        if (endptr == &expression[*index]) {
            printf("Error: Invalid operand.\n");
            exit(1);
        }
        (*index) += endptr - &expression[*index];
    }

    // Handle exponentiation
    while (expression[*index] == '^') {
        (*index)++;
        Operand nextOperand = evaluateOperand(expression, index);
        operand.value = applyOperator(OPERATOR_EXPONENT, operand.value, nextOperand.value);
    }

    // Skip any trailing whitespace
    while (isspace(expression[*index]))
        (*index)++;

    // Get the next operator, if any
    operand.op = getOperator(expression[*index]);

    return operand;
}

Operand evaluateExpression(char* expression) {
    Operand result = evaluateOperand(expression, 0);

    while (result.op != OPERATOR_NONE) {
        Operator nextOp = result.op;
        int nextIndex = 1;
        Operand nextOperand = evaluateOperand(&expression[nextIndex], &nextIndex);

        if (nextOperand.op == OPERATOR_NONE) {
            printf("Error: Invalid expression.\n");
            exit(1);
        }

        while (nextOperand.op != OPERATOR_NONE && nextOperand.op >= nextOp) {
            nextOp = nextOperand.op;
            nextOperand = evaluateOperand(&expression[nextIndex], &nextIndex);
        }

        result.value = applyOperator(result.op, result.value, nextOperand.value);
        result.op = nextOperand.op;
    }

    return result;
}

int main() {
    char expression[MAX_EXPRESSION_LENGTH];
    printf("Enter an expression: ");
    fgets(expression, sizeof(expression), stdin);

    // Remove newline character, if present
    int len = strlen(expression);
    if (expression[len - 1] == '\n')
        expression[len - 1] = '\0';

    Operand result = evaluateExpression(expression);
    printf("Result: %.2f\n", result.value);

    return 0;
}

This program allows the user to enter an arithmetic expression and evaluates it, providing the result. It handles basic arithmetic operations such as addition, subtraction, multiplication, and division. It also supports exponentiation using the caret (^) symbol. The program handles invalid input by printing an error message and exiting if it encounters any issues with the input.

Please note that this is a simplified calculator program, and there are many additional features and edge cases that could be considered. This code provides a starting point that you can build upon to enhance the calculator's functionality further.

Prasun Barua

Prasun Barua is an Engineer (Electrical & Electronic) and Member of the European Energy Centre (EEC). His first published book Green Planet is all about green technologies and science. His other published books are Solar PV System Design and Technology, Electricity from Renewable Energy, Tech Know Solar PV System, C Coding Practice, AI and Robotics Overview, Robotics and Artificial Intelligence, Know How Solar PV System, Know The Product, Solar PV Technology Overview, Home Appliances Overview, Tech Know Solar PV System, C Programming Practice, etc. These books are available at Google Books, Google Play, Amazon and other platforms.

*

Post a Comment (0)
Previous Post Next Post