Assignment Operators in C





Assignment operators are used to assign values to variables and perform operations simultaneously. Here are some commonly used assignment operators:



Operator Description Example
= Assigns the value on the right to the variable on the left. x = 5;
+= Adds the value on the right to the variable on the left. x += 3;
-= Subtracts the value on the right from the variable on the left. x -= 4;
*= Multiplies the variable on the left by the value on the right. x *= 2;
/= Divides the variable on the left by the value on the right. x /= 4;
%= Takes the modulus of the variable on the left with the value on the right. x %= 3;


Here are some examples of how these assignment operators work in C:


int x = 5;     // Assigns the value 5 to the variable x
x += 3;        // Equivalent to x = x + 3, assigns 8 to x
x -= 4;        // Equivalent to x = x - 4, assigns 4 to x
x *= 2;        // Equivalent to x = x * 2, assigns 8 to x
x /= 4;        // Equivalent to x = x / 4, assigns 2 to x
x %= 3;        // Equivalent to x = x % 3, assigns 2 to x (remainder of 8 / 3)



Sample C Program Using Assignment Operators

#include <stdio.h>

int main() {
    int x = 10;
    x += 5;
    printf("The value of x is %d\n", x);

    return 0;
}

This program initializes an integer variable 'x' to 10 and then uses the '+=' assignment operator to add 5 to 'x'. The final value of 'x' is printed, which will be 15.


output:
The value of x is 15


One more program for assignment operator

#include <stdio.h>

int main() {
    int x = 5, result;

    result = x;
    printf("result = %d \n", result);

    result += x; // result = result + x
    printf("result = %d \n", result);

    result -= x; // result = result - x
    printf("result = %d \n", result);

    result *= x; // result = result * x
    printf("result = %d \n", result);

    result /= x; // result = result / x
    printf("result = %d \n", result);

    result %= x; // result = result % x
    printf("result = %d \n", result);

    result = result << x; // result = result << x
    printf("result = %d \n", result);

    result >>= x; // result = result >> x
    printf("result = %d \n", result);

    result &= x; // result = result & x
    printf("result = %d \n", result);

    result ^= x; // result = result ^ x
    printf("result = %d \n", result);

    result |= x; // result = result | x
    printf("result = %d \n", result);

    return 0;
}
Output:
result = 5
result = 10
result = 5
result = 25
result = 5
result = 0
result = 0
result = 0
result = 0
result = 5
result = 5