View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Evaluation of Arithmetic Expression in C: A Complete Developer’s Guide

Updated on 05/05/20253,770 Views

In the world of programming, we frequently come across the need to perform calculations—whether it's computing totals, applying formulas, or making logical decisions based on numerical data. These calculations are built using arithmetic expressions, and when you're working with the C programming language, understanding how these expressions are evaluated is absolutely crucial.

The evaluation of arithmetic expression in C involves determining the final result of a combination of variables, constants, and arithmetic operators like +, -, *, /, and %. While this might sound simple at first glance, the actual process under the hood involves rules like operator precedence, associativity, and even different notations such as infix, prefix, and postfix. And that’s why, you’ll find this concept in every top-rated software development course

This blog will walk you through everything you need to know about the evaluation of arithmetic expression in C, from the basics to more advanced conversion techniques. Whether you're a beginner trying to grasp how C handles calculations or someone brushing up before an interview or exam, this guide will provide clarity with hands-on examples, clear explanations, and useful conversion tables.

What is an Arithmetic Expression in C?

An arithmetic expression in C is a combination of operands (such as constants, variables, or function calls) and arithmetic operators (like `+`, `-`, `*`, `/`, and `%`) that are evaluated to produce a numerical result. These expressions are fundamental in programming, as they allow you to perform calculations and control program logic.

Also explore different operators in C, such as: 

Basic Syntax

An arithmetic expression in C typically follows the pattern:

result = operand1 operator operand2;

Example:

int result = 10 + 5;  // Simple arithmetic expression using '+' operator

In this example, `10` and `5` are operands, and `+` is the arithmetic operator.

Types of Arithmetic Operators in C

  • `+` : Addition
  • `-` : Subtraction
  • `*` : Multiplication
  • `/` : Division
  • `%` : Modulus (returns the remainder)

Example of an Arithmetic Expression in C

#include <stdio.h>

int main() {
    int a = 8, b = 3;
    int sum = a + b;         // Addition
    int difference = a - b;  // Subtraction
    int product = a * b;     // Multiplication
    int quotient = a / b;    // Division
    int remainder = a % b;   // Modulus

    printf("Sum: %d\n", sum);
    printf("Difference: %d\n", difference);
    printf("Product: %d\n", product);
    printf("Quotient: %d\n", quotient);
    printf("Remainder: %d\n", remainder);

    return 0;
}

Output:

Sum: 11
Difference: 5
Product: 24
Quotient: 2
Remainder: 2

Explanation:

Each arithmetic expression in this program performs a different calculation using integer variables `a` and `b`. The results demonstrate how arithmetic operations are executed in C:

  • The addition `a + b` evaluates to `11`
  • The division `a / b` truncates the result to an integer, resulting in `2` (not 2.66)
  • The modulus `a % b` returns the remainder of `8 / 3`, which is `2`

Understanding how each arithmetic expression in C is evaluated helps prevent logical errors in programs and ensures correct results in numerical operations.

Supercharge your career journey with the following online courses: 

Types of Expression Evaluation in C

In C programming, expressions are evaluated based on their structure and the kind of result they produce. There are four main types of expression evaluation in C:

1. Evaluation of Arithmetic Expressions

This is the most common type, used to perform mathematical operations. These expressions consist of numeric operands and arithmetic operators like `+`, `-`, `*`, `/`, and `%`. The result is always a numeric value.

Example:

#include <stdio.h>

int main() {
    int result = 30 / 6;  // Simple arithmetic expression
    printf("Result: %d\n", result);
    return 0;
}

Output:

Result: 5

Explanation:

This arithmetic expression in C evaluates `30 / 6` and returns the numeric result `5`.

2. Evaluation of Relational Expressions

Relational expressions are used to compare values. They evaluate to either `1` (true) or `0` (false), depending on whether the relation is satisfied.

Example:

#include <stdio.h>

int main() {
    int a = 5, b = 3, c = 2, d = 2;

    int result = (a + b) >= (c * d);  // Relational expression
    printf("Result: %d\n", result);
    return 0;
}

Output:

Result: 1

Explanation:

`(a + b)` is `8`, and `(c * d)` is `4`. Since `8 >= 4` is true, the result is `1`.

3. Evaluation of Logical Expressions

Logical expressions use logical operators like `&&` (AND), `||` (OR), and `!` (NOT) to combine or invert Boolean values. They return `1` (true) or `0` (false).

Example:

#include <stdio.h>

int main() {
    int a = 2, b = 5, c = 3, d = 3;

    int result = (a < b) || (c == d);  // Logical OR expression
    printf("Result: %d\n", result);
    return 0;
}

Output:

Result: 1

Explanation:

`(a < b)` is true and `(c == d)` is also true. Since at least one condition is true, the OR (`||`) operator returns `1`.

4. Evaluation of Conditional Expressions

Also called ternary expressions, these use the `? :` operator to choose between two values or expressions based on a condition.

Example:

#include <stdio.h>

int main() {
    int a = 10, b = 3;

    const char* result = (a > b) ? "Expression is true" : "Expression is false";
    printf("%s\n", result);
    return 0;
}

Output:

Expression is true

Explanation:

Since `10 > 3` is true, the expression before the colon (`"Expression is true"`) is returned. This is a concise way to write conditional logic in C.

Each type of expression, arithmetic, relational, logical, and conditional plays a key role in the overall evaluation of expressions in C. While arithmetic expressions in C are primarily about computation, the other types allow decision-making and flow control, all evaluated under consistent rules of precedence and associativity.

Furthermore, if you want to develop an efficient C program, explore our articles on structure of a C program, and comments in C

The Order of Evaluation of Arithmetic Expression in C

In C, when you write arithmetic expressions, the order in which operations are performed can significantly impact the final result. The order of evaluation is governed by operator precedence and associativity, which dictate how operators are ranked and evaluated within an expression. Understanding these rules is crucial, as failing to adhere to them can result in incorrect calculations and unexpected behavior in your program.

Steps for Evaluating an Arithmetic Expression in C

1. Identify all operators and operands in the expression.

2. Check operator precedence:

  • Operators like `*`, `/`, `%` (multiplication, division, modulus) are evaluated before `+` and `-` (addition, subtraction).
  • For more complex expressions, refer to a precedence chart to determine which operators have higher precedence.

3. Apply associativity rules:

  • Most arithmetic operators (`+`, `-`, `*`, `/`, `%`) follow left-to-right associativity.
  • Assignment operators (e.g., `=`, `+=`) follow right-to-left associativity.

4. Evaluate expressions inside parentheses first, as they have the highest precedence regardless of the operators involved.

5. Perform the operations step by step following the precedence and associativity rules.

6. Use temporary variables in C or rewrite complex expressions if necessary to enhance readability or avoid potential mistakes.

7. Verify the final result, preferably by testing the expression with different inputs or using debug output to ensure the evaluation matches expectations.

Polish or Prefix Notation for Arithmetic Expression in C

In the realm of arithmetic expressions, Prefix Notation (also known as Polish Notation) is a way of writing expressions where the operator precedes the operands. Unlike the familiar infix notation (where operators are placed between operands), prefix notation eliminates the need for parentheses to determine operator precedence, since the operator’s position inherently determines the order of evaluation.

Why Use Prefix Notation?

Prefix notation is useful in stack-based calculations and expression trees because it eliminates the need for managing parentheses in a complex expression. This form of notation can be especially important in evaluating expressions in compilers and calculators that evaluate expressions using stacks. In prefix notation, the operator comes before its operands, making the evaluation order unambiguous.

Steps for Converting Infix to Prefix Notation

Converting an infix expression (the common mathematical format with operators between operands) to prefix notation requires several steps, all based on the operator precedence, associativity, and parentheses. Here's how you can do it:

1. Reverse the Infix Expression

Start by reversing the entire infix expression, making sure to reverse any parentheses as well. This step sets up the expression for easier handling.

Example:

`3 + 5 * 2` → Reversed: `(2 * 5) + 3`

2. Apply Operator Precedence and Associativity

  • Identify operators with the highest precedence. In C, multiplication (`*`), division (`/`), and modulus (`%`) have higher precedence than addition (`+`) and subtraction (`-`).
  • Apply associativity rules: Most arithmetic operators are left-associative, meaning they are evaluated left to right, but some operators like the assignment (`=`) are right-associative.

3. Convert to Prefix Notation

After reversing the expression, place the operator before its operands while respecting operator precedence and associativity. Ensure that each operator applies to the correct operands in its modified position.

4. Reverse the Expression Again

After converting the expression to prefix notation, reverse it one more time to get the final result.

Example of Prefix Notation Conversion

Let’s convert a simple infix expression `(3 + 5) * 2` into prefix notation:

Step 1: Reverse the Expression

The original expression is:

`(3 + 5) * 2`

Reversed expression becomes:

`2 * (5 + 3)`

Step 2: Apply Operator Precedence

Since `*` (multiplication) has higher precedence than `+` (addition), we know that multiplication must happen first. However, to maintain the order, we must place the operator before its operands.

Step 3: Place the Operator Before Operands

After applying the operator precedence, we get:

`* + 3 5 2`

Step 4: Reverse the Expression Again

Finally, we reverse the expression to obtain the prefix notation:

`* + 3 5 2`

Detailed Breakdown of Prefix Notation

Infix Expression:

`(3 + 5) * 2`

  • First, evaluate the expression inside the parentheses: `(3 + 5) = 8`.
  • Then, multiply the result by `2`, so `8 * 2 = 16`.

Prefix Expression:

`* + 3 5 2`

Prefix expression eliminates parentheses. In this case, `+ 3 5` is evaluated first, followed by the multiplication with `2`. There’s no ambiguity in the evaluation order because of the operator position.

Example Code to Evaluate Prefix Expression in C

Here’s an example of a simple C program to evaluate a prefix expression:

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

#define MAX 50

// Stack structure to hold operands
int stack[MAX];
int top = -1;

// Function to push onto the stack
void push(int value) {
    stack[++top] = value;
}

// Function to pop from the stack
int pop() {
    return stack[top--];
}

// Function to evaluate a prefix expression
int evaluatePrefix(char* exp) {
    int i, operand1, operand2;
    for (i = strlen(exp) - 1; i >= 0; i--) {
        // If the character is an operand
        if (exp[i] >= '0' && exp[i] <= '9') {
            push(exp[i] - '0');  // Convert char to integer and push to stack
        }
        // If the character is an operator
        else {
            operand1 = pop();
            operand2 = pop();
            switch (exp[i]) {
                case '+': push(operand1 + operand2); break;
                case '-': push(operand1 - operand2); break;
                case '*': push(operand1 * operand2); break;
                case '/': push(operand1 / operand2); break;
            }
        }
    }
    return pop();  // The final result is the only element in the stack
}

int main() {
    char prefixExp[] = "*+35 2";  // Prefix expression: * + 3 5 2
    int result = evaluatePrefix(prefixExp);
    printf("Result of Prefix Evaluation: %d\n", result);      return 0;
}

Expected output:

16

Explanation:

  • The function `evaluatePrefix` processes the prefix expression from right to left.
  • It pushes operands onto the stack and, upon encountering an operator, pops two operands, applies the operator, and pushes the result back onto the stack.
  • Finally, the result remains on the stack, which is popped and returned as the result.

Reverse Polish (Postfix) Notation for Arithmetic Expression in C

Reverse Polish Notation (RPN), also known as Postfix Notation, is another mathematical notation that eliminates the need for parentheses to define the order of operations. Unlike Prefix Notation, where the operator precedes the operands, in Postfix notation, the operator follows the operands. This makes it easy to evaluate expressions using a stack because there is no need to worry about operator precedence or parentheses.

In Reverse Polish notation, the expression is written in a manner where each operator appears after its operands. This method simplifies computation and is extensively used in stack-based calculators, postfix evaluators, and compilers for efficient expression evaluation.

Also explore our article on Compiler vs Interpreter in C to gain a deeper understanding of the C language. 

Steps for Converting Infix to Postfix Notation

1. Identify operands and operators in the infix expression.

2. Check operator precedence:

  • Operators like `*`, `/`, `%` have higher precedence than `+`, `-`.
  • Postfix expression does not need parentheses, so precedence determines the position of operators relative to operands.

3. Move operators after operands, as the operator is placed after its operands, respecting the order of operations.

4. Use a stack for operators:

  • Push operators onto a stack as you encounter them.
  • If an operator has lower precedence than the operator already on the stack, pop the higher-precedence operator and place it in the result.

5. Finish with the remaining operators, and once all operands have been processed, any operators left on the stack are placed in the result.

Example of Postfix Notation Conversion

Let’s convert a simple infix expression `(3 + 5) * 2` into postfix notation:

Infix Expression:

`(3 + 5) * 2`

Step 1: Identify the Operators

The operators in this expression are `+` and `*`.

Step 2: Apply Operator Precedence

`*` (multiplication) has higher precedence than `+` (addition).

Step 3: Place Operators After Operands

  • In this expression, `+` comes first, so it will be placed after its operands `3` and `5`.
  • Then, `*` comes after the result of `3 + 5`, followed by `2`.

Postfix Expression:

`3 5 + 2 *`

Detailed Breakdown of Postfix Notation

Infix Expression:

`(3 + 5) * 2`

  • First, evaluate the expression inside the parentheses: `(3 + 5) = 8`.
  • Then, multiply the result by `2`, so `8 * 2 = 16`.

Postfix Expression:

`3 5 + 2 *`

  • In postfix notation, the operands `3` and `5` come first, followed by the operator `+`. This means that `3 + 5` is evaluated first.
  • The multiplication operator `*` then comes after the result of `3 + 5`, so `8 * 2 = 16`.

Also, read our article on C compiler for Mac and compiling C program in Linux to develop programs on different operating systems. 

Example Code to Evaluate Postfix Expression in C

Here’s an example of a simple C program to evaluate a postfix expression:

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

#define MAX 50

// Stack structure to hold operands
int stack[MAX];
int top = -1;

// Function to push onto the stack
void push(int value) {
    stack[++top] = value;
}

// Function to pop from the stack
int pop() {
    return stack[top--];
}

// Function to evaluate a postfix expression
int evaluatePostfix(char* exp) {
    int i;
    for (i = 0; i < strlen(exp); i++) {
        // If the character is an operand (digit), push it to the stack
        if (isdigit(exp[i])) {
            push(exp[i] - '0');
        }
        // If the character is an operator, pop two operands and apply the operator
        else if (exp[i] == '+' || exp[i] == '-' || exp[i] == '*' || exp[i] == '/') {
            int operand2 = pop();
            int operand1 = pop();
            switch (exp[i]) {
                case '+': push(operand1 + operand2); break;
                case '-': push(operand1 - operand2); break;
                case '*': push(operand1 * operand2); break;
                case '/': push(operand1 / operand2); break;
            }
        }
    }
    return pop();  // The final result is the only element in the stack
}

int main() {
    char postfixExp[] = "35+2*";  // Postfix expression: 3 5 + 2 *
    int result = evaluatePostfix(postfixExp);
    printf("Result of Postfix Evaluation: %d\n", result);  
    return 0;
}

Expected output: 

16

Explanation:

  • The function `evaluatePostfix` reads the postfix expression from left to right.
  • Operands (numbers) are pushed onto the stack.
  • When an operator is encountered, two operands are popped from the stack, the operation is performed, and the result is pushed back onto the stack.
  • Finally, the result is popped and returned. 

Detailed Conversion Table: From Infix Notations to Prefix and Postfix

Converting arithmetic expressions from infix notation (where operators are placed between operands) to either prefix or postfix notation can be a bit tricky, but understanding the steps involved can make it much clearer. In this section, we’ll walk through the process with a detailed table to show how different infix expressions can be converted to prefix and postfix notations.

Conversion Rules

Infix to Prefix:

  • Reverse the infix expression.
  • Follow the operator precedence and associativity rules.
  • Reverse the expression again to get the correct prefix form.

Infix to Postfix:

  • Follow the operator precedence and associativity rules.
  • Operands are written in the same order as in infix notation.
  • Operators are written after the operands, respecting their precedence.

Conversion Table: From Infix to Prefix and Postfix

Infix Expression

Prefix Notation

Postfix Notation

(A + B) * C

* + A B C

A B + C *

A + B * C

+ A * B C

A B C * +

(A + B) * (C + D)

* + A B + C D

A B + C D + *

A + B / C

+ A / B C

A B C / +

A * (B + C)

* A + B C

A B C + *

(A + B) / (C - D)

/ + A B - C D

A B + C D - /

A + B * C - D

- + A * B C D

A B C * + D -

A + (B * C - D) / E

+ A / - * B C D E

A B C * D - E / +

A * (B + (C - D))

* A + B - C D

A B C D - + *

Conclusion 

Understanding the evaluation of arithmetic expressions in C using different notations like infix, prefix, and postfix is fundamental for both programming and compiler design. While infix is the most intuitive for humans, prefix and postfix notations simplify expression evaluation by eliminating the need for parentheses and operator precedence rules. These notations can be efficiently evaluated using stack-based algorithms, making them ideal for compilers, interpreters, and other systems that require quick and accurate computation.

By mastering prefix and postfix notation, developers can improve their ability to design efficient expression parsers, calculators, and even contribute to the creation of more advanced computational systems. The ability to convert between different expression formats, and understand how to evaluate them correctly, opens up a deeper understanding of how expressions are handled in programming languages like C.

FAQs 

1. What is an arithmetic expression in C?

An arithmetic expression in C consists of variables, constants, and operators that perform mathematical operations. These operations include addition, subtraction, multiplication, division, and modulus. The result of these operations can be assigned to a variable or used in further computations. These expressions are essential for performing calculations within a C program.

2. How does operator precedence affect the evaluation of arithmetic expressions?

Operator precedence determines the order in which operators are evaluated in an expression. Operators with higher precedence are evaluated before those with lower precedence. For example, in the expression `3 + 4 * 5`, multiplication has higher precedence than addition, so the result is `3 + 20`, which equals `23` instead of `35`.

3. What is the role of parentheses in arithmetic expressions?

Parentheses are used to alter the default precedence of operators in arithmetic expressions. By using parentheses, you can ensure that certain operations are performed first. For example, in `(3 + 4) * 5`, the addition within parentheses is evaluated first, followed by multiplication, giving a result of `35`, not `23`.

4. How does C handle type conversion in arithmetic expressions?

C automatically performs type conversion, also known as type promotion, when different types are involved in an arithmetic expression. For example, when an integer is combined with a float, the integer is promoted to a float. This ensures that the expression is evaluated correctly without data loss, especially when dealing with mixed data types.

5. Can I use multiple operators in a single arithmetic expression?

Yes, you can use multiple operators in a single arithmetic expression. C follows specific rules for operator precedence and associativity. For example, in `3 + 5 * 2`, the multiplication operator has higher precedence and is evaluated first, followed by the addition. Parentheses can also be used to alter the evaluation order.

6. What happens if I divide by zero in an arithmetic expression in C?

Dividing by zero in C causes undefined behavior. In integer division, it typically results in a runtime error or crash, while in floating-point division, it may result in special values like "infinity" or "NaN" (Not a Number). Always check for zero before performing division to avoid runtime errors and ensure your program works correctly.

7. Can I perform arithmetic operations on non-numeric types in C?

Arithmetic operations in C are limited to numeric types, such as integers, floats, and doubles. Non-numeric types, like strings or structs, cannot be directly involved in arithmetic operations. If needed, custom logic must be implemented to perform operations on non-numeric types, as C doesn’t support arithmetic on them by default.

8. What is the difference between prefix and postfix notations?

In prefix notation, operators are placed before their operands (e.g., `+ 3 5`), while in postfix notation, operators come after the operands (e.g., `3 5 +`). The main difference lies in the position of the operator relative to the operands, which affects the order in which the operations are performed during evaluation.

9. How do compilers handle arithmetic expression evaluation?

Compilers use techniques like abstract syntax trees (AST) to analyze and evaluate arithmetic expressions. The AST represents the structure of the expression, breaking it down into operators and operands. The compiler applies operator precedence and generates machine code that performs the arithmetic operations, optimizing performance during the compilation process to generate efficient executable code.

10. What is the role of associativity in arithmetic expression evaluation?

Associativity dictates the direction in which operators of the same precedence are evaluated. For left-associative operators, like `+` and `-`, expressions are evaluated from left to right. For right-associative operators, like exponentiation, evaluation happens from right to left. Understanding associativity ensures correct evaluation, particularly when multiple operators of the same precedence are present in an expression.

11. What are the common errors to avoid when evaluating arithmetic expressions in C?

Common errors in evaluating arithmetic expressions include dividing by zero, mismatched data types, and incorrect parentheses placement. Failing to consider operator precedence can also lead to logical errors, producing incorrect results. Always verify the order of operations and ensure proper handling of special cases, like division by zero or mixing integer and floating-point types in expressions.

image

Take a Free C Programming Quiz

Answer quick questions and assess your C programming knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Start Learning For Free

Explore Our Free Software Tutorials and Elevate your Career.

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.