# 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
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
2
3
What is the value of i
? It is 40.
Notice the line i = i + 5
? It means
- Take value of variable
i
- Add 5 to the value
- 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
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
2
C# has operator +=
that is a shorter version of i = i + 5
.
int i = 10;
i += 5;
1
2
2
i += 5
means i = i + 5
, i.e
- Take value of variable
i
- Add 5 to the value
- 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
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
2
in this way,
int i = 10;
i -= 5;
1
2
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
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
2
3
4
5
6
7
8