C Programming
Unit 4: Operators and Expression
Arithmetic, relational, logical, assignment, ternary, bit-wise, and increment/decrement operators.
Arithmetic operators
Arithmetic operators perform basic mathematical operations on numeric operands.
| Operator | Operation | Example |
|---|---|---|
+ | Addition | a + b |
- | Subtraction | a - b |
* | Multiplication | a * b |
/ | Division | a / b |
% | Modulus | a % b |
#include <stdio.h>
int main(void)
{
int a = 10, b = 3;
printf("a + b = %d\n", a + b);
printf("a - b = %d\n", a - b);
printf("a * b = %d\n", a * b);
printf("a / b = %d\n", a / b);
printf("a %% b = %d\n", a % b);
return 0;
}
Relational operators
Relational operators compare two values and return either 1 (true) or 0 (false).
| Operator | Meaning |
|---|---|
< | Less than |
> | Greater than |
<= | Less than or equal |
>= | Greater than or equal |
== | Equal to |
!= | Not equal to |
#include <stdio.h>
int main(void)
{
int a = 5, b = 10;
printf("%d\n", a < b); /* 1 */
printf("%d\n", a == b); /* 0 */
return 0;
}
Logical and Boolean operators
Logical operators are used to combine relational expressions.
| Operator | Meaning |
|---|---|
&& | Logical AND |
|| | Logical OR |
! | Logical NOT |
#include <stdio.h>
int main(void)
{
int age = 20;
if (age >= 18 && age <= 60)
printf("Eligible\n");
return 0;
}
Assignment operators
The assignment operator = stores the value of the right-hand expression in the variable on
the left. C also provides compound assignment operators.
| Operator | Equivalent to |
|---|---|
+= | a = a + b |
-= | a = a - b |
*= | a = a * b |
/= | a = a / b |
%= | a = a % b |
int a = 10;
a += 5; /* a = 15 */
a *= 2; /* a = 30 */
Ternary operator
The ternary operator (? :) is a shorthand for an if-else statement.
condition ? expr1 : expr2;
If condition is true, the expression evaluates to expr1; otherwise to expr2.
#include <stdio.h>
int main(void)
{
int a = 10, b = 20;
int max = (a > b) ? a : b;
printf("Max = %d\n", max);
return 0;
}
Bit-wise operators
Bit-wise operators work on the binary representation of integers.
| Operator | Meaning |
|---|---|
& | Bit-wise AND |
| | Bit-wise OR |
^ | Bit-wise XOR |
~ | Bit-wise complement |
<< | Left shift |
>> | Right shift |
#include <stdio.h>
int main(void)
{
int a = 12, b = 10; /* 1100 and 1010 */
printf("a & b = %d\n", a & b); /* 1000 = 8 */
printf("a | b = %d\n", a | b); /* 1110 = 14 */
printf("a ^ b = %d\n", a ^ b); /* 0110 = 6 */
printf("a << 1 = %d\n", a << 1);
printf("a >> 1 = %d\n", a >> 1);
return 0;
}
Increment and decrement operators
++increases the value of a variable by 1.--decreases the value of a variable by 1.
They can be used in prefix form (++a) or postfix form (a++).
- Prefix: increment/decrement first, then use the value.
- Postfix: use the value first, then increment/decrement.
#include <stdio.h>
int main(void)
{
int a = 5;
printf("%d\n", ++a); /* 6 (prefix) */
printf("%d\n", a++); /* 6 (postfix) */
printf("%d\n", a); /* 7 */
return 0;
}