Explain C Operators With Examples
Explain C Operators With Examples
expressions. They play a vital role in manipulating data and controlling program flow. Here's a
breakdown of the main C operators with examples:
1. Arithmetic Operators:
Examples:
```c
int x = 10, y = 5;
int sum = x + y; // sum will be 15
int difference = x - y; // difference will be 5
int product = x * y; // product will be 50
int quotient = x / y; // quotient will be 2 (integer division
truncates decimals)
int remainder = x % y; // remainder will be 0
```
2. Assignment Operators:
Examples:
```c
int count = 0;
count += 5; // Equivalent to count = count + 5; (count becomes 5)
float price = 10.5;
price *= 1.1; // Equivalent to price = price * 1.1; (price becomes
11.55)
```
3. Comparison Operators:
● Compare values and return true (1) or false (0) based on the condition.
● Operators: == (equal to), != (not equal to), < (less than), > (greater than), <= (less than or
equal to), >= (greater than or equal to).
Examples:
```c
int age = 21;
bool isAdult = age >= 18; // isAdult will be true (1)
char initial = 'A';
bool isFirstLetter = initial == 'A'; // isFirstLetter will be true (1)
```
4. Logical Operators:
Examples:
```c
int score = 85, attendance = 90;
bool passed = score >= 70 && attendance >= 80; // passed will be true
(1)
char grade = 'A';
bool isExcellent = grade == 'A' || grade == 'B'; // isExcellent will
be true (1)
bool notFailing = !(score < 50); // notFailing will be true (1)
```
5. Bitwise Operators:
● Perform operations on individual bits within a variable (often used for low-level programming).
● Operators: & (bitwise AND), | (bitwise OR), ^ (bitwise XOR), ~ (bitwise NOT), << (left shift),
>> (right shift).
Example:
```c
int flags = 0x0F; // Hexadecimal representation of binary 00001111
int mask = 0x03; // Hexadecimal representation of binary 00000011
int result = flags & mask; // result will be 0x03 (binary 00000011 -
AND each bit)
```
6. Increment/Decrement Operators:
Example:
```c
int count = 0;
count++; // count becomes 1 (post-increment)
int value = count++; // value becomes 1 (uses current value of count,
then increments)
count = ++count