C Language | Introduction to C | Expressions and Calculations

This article explains arithmetic, assignment, increment, and decrement operations.

Arithmetic Expressions

Expressions consist of operands and operators.

Operator Meaning
+ addition
- subtraction
* multiplication
/ division
% remainder
= assignment

Code 1

#include <stdio.h>

int main() {
 int op1 = 0 , op2 = 0;
 printf("Enter two numbers. >");
 scanf("%d %d" , &op1 , &op2);
 printf("%d + %d = %d\n" , op1 , op2 , op1 + op2);
 return 0;
}

Store a result when it will be reused.

op3 = op1 * op2;

Operator precedence follows familiar arithmetic rules. Multiplication and division occur before addition and subtraction. Use parentheses to change the order.

2 + 2 * 3       /* 8 */
(2 + 2) * 3     /* 12 */

Compound Assignment

Compound assignment combines an operation with assignment.

Operator Equivalent form
+= a = a + b
-= a = a - b
*= a = a * b
/= a = a / b
%= a = a % b

Code 2

#include <stdio.h>

int main() {
 int width , height;
 printf("Enter the base and height of a triangle. >");
 scanf("%d %d" , &width , &height);
 width *= height / 2;
 printf("Area = %d\n" , width);
 return 0;
}

Increment and Decrement

Use ++ to add 1 and -- to subtract 1.

variable++;
variable--;

Prefix and postfix forms differ when used as part of a larger expression. A postfix operator yields the original value and then updates the variable. A prefix operator updates the variable first and yields the new value.

Code 3

#include <stdio.h>

int main() {
 int iVar1 = 0 , iVar2 = 0;
 printf("postfix increment = %d\n" , iVar1++);
 printf("prefix increment = %d\n" , ++iVar2);
 printf("iVar1 = %d, iVar2 = %d\n" , iVar1 , iVar2);
 return 0;
}