Operators in C
Operators in C
Operators in C
values. They are divided into several categories, each serving different purposes. Below is
an explanation of various operators in C with examples.
1. Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations like addition,
subtraction, multiplication, etc.
* Multiplication a * b (multiplies a by b)
/ Division a / b (divides a by b)
Example:
#include <stdio.h>
int main() {
int a = 10, b = 3;
printf("Addition: %d\n", a + b); // Output: 13
printf("Subtraction: %d\n", a - b); // Output: 7
printf("Multiplication: %d\n", a * b);// Output: 30
printf("Division: %d\n", a / b); // Output: 3
printf("Modulus: %d\n", a % b); // Output: 1
return 0;
}
2. Relational Operators
Relational operators are used to compare values. The result of a relational operation is
either true (1) or false (0).
Example:
#include <stdio.h>
int main() {
int a = 5, b = 10;
printf("a == b: %d\n", a == b); // Output: 0 (false)
printf("a != b: %d\n", a != b); // Output: 1 (true)
printf("a > b: %d\n", a > b); // Output: 0 (false)
printf("a < b: %d\n", a < b); // Output: 1 (true)
return 0;
}
3. Logical Operators
` `
Example:
c
#include <stdio.h>
int main() {
int a = 5, b = 10;
printf("Logical AND: %d\n", (a < b) && (b > 5)); // Output: 1
(true)
printf("Logical OR: %d\n", (a > b) || (b > 5)); // Output: 1
(true)
printf("Logical NOT: %d\n", !(a == b)); // Output: 1
(true)
return 0;
}
4. Bitwise Operators
` ` Bitwise OR
^ Bitwise XOR a ^ b
~ Bitwise NOT ~a
Example:
#include <stdio.h>
int main() {
int a = 5, b = 3;
printf("Bitwise AND: %d\n", a & b); // Output: 1
printf("Bitwise OR: %d\n", a | b); // Output: 7
printf("Bitwise XOR: %d\n", a ^ b); // Output: 6
printf("Left Shift: %d\n", a << 1); // Output: 10
printf("Right Shift: %d\n", a >> 1); // Output: 2
return 0;
}
5. Assignment Operators
Example:
#include <stdio.h>
int main() {
int a = 5, b = 3;
a += b; // Equivalent to a = a + b
printf("a += b: %d\n", a); // Output: 8
a -= b; // Equivalent to a = a - b
printf("a -= b: %d\n", a); // Output: 5
return 0;
}
Example:
#include <stdio.h>
int main() {
int a = 5;
printf("Post-increment: %d\n", a++); // Output: 5 (increment
happens after)
printf("Value after post-increment: %d\n", a); // Output: 6
printf("Pre-increment: %d\n", ++a); // Output: 7 (increment
happens before)
return 0;
}
Example:
#include <stdio.h>
int main() {
int a = 5, b = 10;
int max = (a > b) ? a : b; // Find maximum of a and b
printf("Maximum: %d\n", max); // Output: 10
return 0;
}
8. Sizeof Operator
The sizeof operator is used to determine the size of a data type or a variable in bytes.
Example:
#include <stdio.h>
int main() {
int a;
printf("Size of int: %lu\n", sizeof(a)); // Output: 4 (on most
systems)
printf("Size of char: %lu\n", sizeof(char)); // Output: 1
return 0;
}
These are the main operators used in C, each serving a specific role in manipulating data
and controlling program flow.