TechTorch

Location:HOME > Technology > content

Technology

Creating a Simple Calculator Program in C to Evaluate Multiple Numbers and Operators

January 09, 2025Technology4515
Creating a Simple Calculator Program in C to Evaluate Multiple Numbers

Creating a Simple Calculator Program in C to Evaluate Multiple Numbers and Operators

In this article, we will demonstrate how to create a simple calculator program in the C programming language that can evaluate expressions containing multiple numbers and operators. This implementation will use a straightforward approach to parse, tokenize, and evaluate expressions according to the BODMAS/BIDMAS rule (Brackets, Orders, Division/Multiplication, Addition/Subtraction).

Parsing the Input

To start, the program reads the entire expression as a string using fgets. This function is ideal for handling input with spaces between numbers and operators. Here's how it works:

char expression[MAX_LEN];printf("Enter an expression: ");fgets(expression, sizeof(expression), stdin);

Tokenizing the Input

The next step is to tokenize the input string using the strtok function. This function breaks the string into tokens (numbers and operators), which are stored in respective arrays. We also need to handle negative numbers properly:

char token[MAX_LEN];tokeng  strtok(expression, " 
");while (token ! NULL) {    if (isdigit(token[0]) || (strlen(token)  2  isdigit(token[0])  token[1]  '-')) {        numbers[numIndex]  atof(token);    } else {        operators[opIndex]  token[0];    }    token  strtok(NULL, " 
");}

Evaluating the Expression

After parsing and tokenizing the input, we need to evaluate the expression. The evaluation follows the BODMAS/BIDMAS rule. The program first handles multiplication and division, then addition and subtraction:

for (int i  0; i  opIndex; i  ) {    if (operators[i]  '*' || operators[i]  '/') {        result  applyOperation(numbers[i], numbers[i   1], operators[i]);        numbers[i]  result;        for (int j  i   1; j  numIndex; j  ) {            numbers[j]  numbers[j   1];        }        numIndex--;        for (int j  i; j  opIndex - 1; j  ) {            operators[j]  operators[j   1];        }        opIndex--;        i--;    }}double result  numbers[0];for (int i  0; i  opIndex; i  ) {    result  applyOperation(result, numbers[i], operators[i]);}

Putting It All Together

Here is the complete C program:

#include stdio.h#include stdlib.h#include string.h#include ctype.h#define MAX_LEN 100// Function to perform basic arithmetic operationsdouble applyOperation(double a, double b, char op) {    switch (op) {        case ' ': return a   b;        case '-': return a - b;        case '*': return a * b;        case '/': return a / b;        default: return 0;    }}// Function to evaluate the expressiondouble evaluateExpression(char *expression) {    double numbers[MAX_LEN]  {0};    char operators[MAX_LEN]  {0};    int numIndex  0, opIndex  0;    char token[MAX_LEN];    token  strtok(expression, " 
");    while (token ! NULL) {        if (isdigit(token[0]) || (strlen(token)  2  isdigit(token[0])  token[1]  '-')) {            numbers[numIndex]  atof(token);        } else {            operators[opIndex]  token[0];        }        token  strtok(NULL, " 
");    }    // Perform multiplication and division    for (int i  0; i  opIndex; i  ) {        if (operators[i]  '*' || operators[i]  '/') {            double result  applyOperation(numbers[i], numbers[i   1], operators[i]);            numbers[i]  result;            for (int j  i   1; j  numIndex; j  ) {                numbers[j]  numbers[j   1];            }            numIndex--;            for (int j  i; j  opIndex - 1; j  ) {                operators[j]  operators[j   1];            }            opIndex--;            i--;        }    }    // Perform addition and subtraction    double result  numbers[0];    for (int i  0; i  opIndex; i  ) {        result  applyOperation(result, numbers[i], operators[i]);    }    return result;}int main() {    char expression[MAX_LEN];    printf("Enter an expression: ");    fgets(expression, sizeof(expression), stdin);    // Remove the newline character from input    expression[strcspn(expression, "
")]  0;    double result  evaluateExpression(expression);    printf("Result: %f
", result);    return 0;}

Conclusion

By following the steps outlined in this guide, you can create a simple yet effective calculator program in C. This program demonstrates input handling, tokenization, and the evaluation of expressions according to the BODMAS/BIDMAS rule. Feel free to modify and expand upon this implementation to suit your needs!