HOME HTML EDITOR C JAVA PHP

C Operators: Performing Calculations and Logic

**Operators** are symbols that operate on values or variables (called operands). For example, in the expression 10 + 5, the + is the operator and 10 and 5 are the operands. C provides a rich set of operators to handle everything from basic math to complex bitwise manipulation.

1. Types of Operators in C

To make learning easier, C operators are classified into several groups based on the type of operation they perform:

2. Arithmetic Operators

These are used to perform common mathematical operations. Most of these are familiar from basic algebra, but the Modulus operator is unique to programming.

Operator Name Example
+ Addition x + y
- Subtraction x - y
* Multiplication x * y
/ Division x / y
% Modulus x % y (Returns the remainder)
++ Increment Increases value by 1
-- Decrement Decreases value by 1

3. Assignment Operators

The assignment operator (=) is used to assign a value to a variable. C also supports Compound Assignment Operators, which perform an operation and an assignment in one step.

int x = 10;
x += 5; // Same as x = x + 5 (Result: 15)
x -= 3; // Same as x = x - 3 (Result: 12)
x *= 2; // Same as x = x * 2 (Result: 24)

4. Comparison Operators

Comparison operators compare two values and return either **1 (true)** or **0 (false)**. These are essential for decision-making in programs (like if statements).

5. Logical Operators

Logical operators are used to determine the logic between variables or values. They are usually used to combine multiple comparisons.

[Image of logical operators truth table: AND, OR, NOT]
Operator Name Logic
&& Logical AND Returns true if both statements are true.
|| Logical OR Returns true if one of the statements is true.
! Logical NOT Reverse the result (returns false if result is true).

6. Operator Precedence

In an expression with multiple operators, C follows a specific order called **Operator Precedence** to decide which operation happens first. For example, multiplication (*) has higher precedence than addition (+).

int result = 5 + 2 * 10;
// Result is 25, not 70, because * is done before +.

int result2 = (5 + 2) * 10;
// Result is 70, because parentheses have the highest precedence.

7. Practical Example: Increment and Modulus

Let's see how the modulus and increment operators work in a real scenario:

#include <stdio.h>

int main() {
    int a = 10, b = 3;
    int remainder = a % b; // 10 divided by 3 leaves remainder 1

    printf("Remainder: %d\n", remainder);

    a++; // a becomes 11
    printf("New value of a: %d", a);

    return 0;
}
Pro Tip: Always use parentheses () when writing complex expressions. Even if you know the precedence rules, using parentheses makes your code much easier to read for others and prevents accidental logic errors.