C# 05 Study Notes Compound and Iteration statements
5.Compound and Iteration statements
5.1. Compound Assignment Operator
📌What is it?
int num = 13;
num = num + 28; //this is not
num += 28; //this is compound
📌Recommend
Don't😶 | Yes!😄 |
---|---|
num = num + variable; | num += variable; |
num = num - variable; | num -= variable; |
num = num * variable; | num *= variable; |
num = num / variable; | num /= variable; |
num = num % variable; | num %= variable; |
num += 1; | num++; |
5.2. while
loop
📌while
loop in abstract
xxxxxxxxxx
initialization
while(Boolean expression)
{
statement
update sentinel variable
}
📌sentinel variable哨兵变量
The variable to end the while
loop.
xxxxxxxxxx
int i = 0; //sentinel variable
while(i < 10)
{
Console.WriteLine(i);
i++;
}
5.3. for
loop
📌for
loop in abstract
xxxxxxxxxx
for(initialization; Boolean expression; update sentinel variable)
{
statement
}
📌for
loop in real
xxxxxxxxxx
for(int i = 0; i < 10; i++)
{
Console.WriteLine(i);
}
📌Multiple variable for
loop⭐️
xxxxxxxxxx
for (int i = 0, j=10; i < j; i++, j--)
{
Console.WriteLine($"i val:{i}, j val:{j}");
}
Output:
xxxxxxxxxx
i val:0, j val:10
i val:1, j val:9
i val:2, j val:8
i val:3, j val:7
i val:4, j val:6
📌for
loop can do more!⭐️⭐️⭐️
xxxxxxxxxx
for(string line = reader.ReadLine(); line!=null; line=reader.ReadLine())
{
source.Text += line + "\n";
}
📌Variable in for
loop is local variable
xxxxxxxxxx
for (int i = 0; i < 5; i++)
{
Console.WriteLine($"Say {i}.");
}
for (int i = 20; i > 15; i--)
{
Console.WriteLine($"Yell {i}!");
}
Output:
xxxxxxxxxx
Say 0.
Say 1.
Say 2.
Say 3.
Say 4.
Yell 20!
Yell 19!
Yell 18!
Yell 17!
Yell 16!
5.4. do
statement
📌do
in abstract
xxxxxxxxxx
do
{
statement
}while(Boolean expression)
📌do
in real
xxxxxxxxxx
int i = 0;
do
{
Console.WriteLine(i);
i++;
} while (i < 10); //don't forget the ; here
📌difference between do-while
and while
In short, do-while
has to do it at least once before iterating!
📌break
and continue
Same with it in Python,
break
- it jumps out thefor
/while
loop directlycontinue
- it goes to the next iteration offor
/while
loop