For working professionals
For fresh graduates
More
5. Array in C
13. Boolean in C
18. Operators in C
33. Comments in C
38. Constants in C
41. Data Types in C
49. Double In C
58. For Loop in C
60. Functions in C
70. Identifiers in C
81. Linked list in C
83. Macros in C
86. Nested Loop in C
97. Pseudo-Code In C
100. Recursion in C
103. Square Root in C
104. Stack in C
106. Static function in C
107. Stdio.h in C
108. Storage Classes in C
109. strcat() in C
110. Strcmp in C
111. Strcpy in C
114. String Length in C
115. String Pointer in C
116. strlen() in C
117. Structures in C
119. Switch Case in C
120. C Ternary Operator
121. Tokens in C
125. Type Casting in C
126. Types of Error in C
127. Unary Operator in C
128. Use of C Language
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.
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:
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.
#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:
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:
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:
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`.
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`.
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`.
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.
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.
1. Identify all operators and operands in the expression.
2. Check operator precedence:
3. Apply associativity rules:
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.
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.
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.
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
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.
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`
Infix Expression:
`(3 + 5) * 2`
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.
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:
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.
1. Identify operands and operators in the infix expression.
2. Check operator precedence:
3. Move operators after operands, as the operator is placed after its operands, respecting the order of operations.
4. Use a stack for operators:
5. Finish with the remaining operators, and once all operands have been processed, any operators left on the stack are placed in the result.
Let’s convert a simple infix expression `(3 + 5) * 2` into postfix notation:
`(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
`3 5 + 2 *`
Infix Expression:
`(3 + 5) * 2`
Postfix Expression:
`3 5 + 2 *`
Also, read our article on C compiler for Mac and compiling C program in Linux to develop programs on different operating systems.
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:
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.
Infix to Prefix:
Infix to 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 - + * |
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.
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.
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`.
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`.
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.
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.
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.
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.
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.
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.
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.
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.
Take a Free C Programming Quiz
Answer quick questions and assess your C programming knowledge
Author|900 articles published
Previous
Next
Start Learning For Free
Explore Our Free Software Tutorials and Elevate your Career.
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
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.