Ads

Compound Assigment

COMPOUND ASSIGNMENT:

- While assigning, if an expression contains the variable itself (on RHS) then we go for compound assignment operators.
- Like, for x=x+3 we write x+=3, both expressions perform same operation.

Syntax:

<l_value> <compound_assignment_operator> <r_value>


- Angled brackets are used for demonstration purpose only and should not be used in your c program

- They are,
    +=
    -=
    *=
    /=
    %=


- Few examples
  • x+=5; is equivalent to x=x+5;
  • x-=5; is equivalent to x=x-5;
  • x*=5; is equivalent to x=x*5;
  • x/=5; is equivalent to x=x/5;
  • x%=5; is equivalent to x=x%5;
  •  but x%=0.5 is not valid since 0.5 is float and % cannot be used for float values.

- Not only on constants but compound assignment operators can also be used on variables.

EX:
x+=y;   =>  x=x+y;
we can also use them on expressions like below
x+=5*6; is equivalent to x=x+(5*6);
x+=7*y; is equivalent to x=x+(7*y);


Program:


/*A program to add and perform other basic operations using compound assignment operators.*/

#include<stdio.h>
int main()
{ 
 int x;
 x=8;
 x=x+5;
 printf ("\n value in x is % d",x);
 x=8;
 x+=5;
 printf ("\n value in x is % d",x);
 x=8;
 x=x%5;
 printf("\n value in x %d",x);
 x=8;
 x%=5;
 printf("\n value in x %d",x);

 return 0; 
}


Output:

value in x is  13
value in x is  13
value in x 3
value in x 3


No comments:

Post a Comment