Menu Close

C Programming : Assignment Operators

Posted in C Programming

C Assignment Operators

An assignment operator is used for assigning a value to a variable. The most common assignment operator is =

Operator Description Example
= Simple assignment operator. Assigns the right operand to the left operand. int x = 10;
int y;
y = x; // y is assigned the value of x ( 10 )
+= Addition assignment operator. Adds the right operand to the left operand and assigns the result to the left operand. int a = 5;
a += 3; // a is incremented by 3
-= Subtraction assignment operator. Subtracts the right operand from the left operand and assigns the result to the left operand. int b = 8;
b -= 4; // b is decremented by 4
*= Multiplication assignment operator. Multiplies the left operand by the right operand and assigns the result to the left operand. int c = 3;
c *= 2; // c is multiplied by 2
/= Division assignment operator. Divides the left operand by the right operand and assigns the result to the left operand. int d = 12;
d /= 4; // d is divided by 4
%= Modulus assignment operator. Calculates the modulus of the two operands and assigns the result to the left operand. Not applicable to floating-point numbers. int e = 10;
e %= 3; // e is assigned the remainder of e divided by 3

Assignment operators support basic data types in the C language, including char, int, and double. However, strings (character arrays) cannot be directly assigned using assignment operators.

Operators in C Program
Operators in C Program

Example 1 )Assignment operators

#include <stdio.h>

int main()
{
   int C=0; 
   int A=21; 

   printf("C=0; A=21\n");
   C=A;
   printf("C=A; C=%d\n",C);

   C+=A; // C=C+A;
   printf("C+=A,C=%d\n",C);

   C-=A; // C=C-A;
   printf("C-=A,C=%d\n",C);

   C*=A; // C=C*A;
   printf("C*=A,C=%d\n",C);

   C/=A; // C=C/A;
   printf("C/=A,C=%d\n",C);

   C=200;
   printf("C=200\n");
   C%=A; // C=C%A;
   printf("C%=A,C=%d\n",C);

   return 0;
}

results:

C=0; A=21
C=A; C=21
C+=A,C=42
C-=A,C=21
C*=A,C=441
C/=A,C=21
C=200
C=A,C=11

Process returned 0 (0x0) execution time : 1.185 s
Press any key to continue.
Related:   C Programming Operators

Leave a Reply