# Compound Assignment

Can you guess the value of variable i here.

int i = 10;
1

10, right? Say, I add 5 to it.

int i = 10;
i = i + 5;
1
2

Now the value of i is 15.

I add 25 to it?

int i = 10;
i = i + 5;
i = i + 25
1
2
3

What is the value of i? It is 40.

Notice the line i = i + 5? It means

  1. Take value of variable i
  2. Add 5 to the value
  3. Assign the result to the variable i

What is the value of i in the following code?


 


int i = 10;
int j = i + 5;
i = i + 25
1
2
3

What is your guess? 40? Wrong. It is 35. In line 2, we assigned the result of i + 5 to the variable j.

# += operator

See this code,

int i = 10;
i = i + 5;
1
2

C# has operator += that is a shorter version of i = i + 5.

int i = 10;
i += 5;
1
2

i += 5 means i = i + 5, i.e

  1. Take value of variable i
  2. Add 5 to the value
  3. Assign the result to the variable i

# Exercise 1

int i = 10;     // What is the value of i
i += 20;        // What is the value of i
int j = 30;     // What is the value of j
j += i;         // What is the value of i and j
j += 100;       // What is the value of j
1
2
3
4
5

# -= operator

Just like += operator, -= is a shorter version of i = i - 5.

It means you can write following code,

int i = 10;
i = i - 5;
1
2

in this way,

int i = 10;
i -= 5;
1
2

# Exercise 2

int i = 90;     // What is the value of i
i -= 30;        // What is the value of i
int j = 30;     // What is the value of j
j -= i;         // What is the value of i and j
j -= 100;       // What is the value of j
1
2
3
4
5

# *= , /= and %= operators

*= is the shorter version of i = i * 5.

/= is the shorter version of i = i / 5.

%= is the shorter version of i = i % 5.

# Exercise 3

int i = 0;
int j = 25;
int k = 200;
i += 4; 		// What is the value of i
i *= j; 		// What is the value of i and j
i /= 50; 		// What is the value of i
k %= i; 		// What is the value of i and k
j *= k; 		// What is the value of j and k
1
2
3
4
5
6
7
8
Last Updated: Apr 21, 2020, 10:37 PM