if, else and loops
if, else and the conditional operator
if takes a bool, and the braces are optional for one statement. Two forms are worth knowing before the loops:
- if (a) { ... } else if (b) { ... } else { ... } is the chain: the first branch that is true runs and the rest are skipped.
- condition ? whenTrue : whenFalse is an expression, so it can be used where a value is expected. Both sides must have a type the compiler can reconcile.
A condition is a comparison, a method that returns bool, or a combination with &&, || and !. There is no implicit conversion from a number: if (count) does not compile in C#, while it does in C and in C++.
for, foreach, while and do
Four loops, and the difference is what decides the end:
- for (start; condition; step) counts: the condition is tested before each pass, and the step runs after it.
- foreach (var item in collection) visits every element of anything enumerable, in its own order.
- while (condition) tests before the body, so it may run zero times.
- do { ... } while (condition) tests after the body, so it runs at least once.
int[] values = { 1, -2, 3, -4 };
int total = 0;
foreach (var value in values)
{
if (value < 0)
{
continue;
}
total += value;
}
Console.WriteLine($"total: {total}");
for (int i = 0; i < 3; i++)
{
if (i == 1)
{
continue;
}
Console.WriteLine($"for {i}");
}
int n = 0;
while (n < 2)
{
Console.WriteLine($"while {n}");
n++;
}
do
{
Console.WriteLine("do runs once");
} while (false);
Console.WriteLine(total > 3 ? "big" : "small");
dotnet run
total: 4
for 0
for 2
while 0
while 1
do runs once
big
The total is 4 because the two negative values were skipped: 1 and 3 are the ones that remained. The for loop printed 0 and 2 and skipped 1, and the do body ran once even though its condition was false from the start — that is the difference from while, which would have skipped the body entirely.
break and continue
break leaves the innermost loop or switch, and continue jumps to the next pass. Neither jumps out of a nested loop on its own: a flag or a goto is what C# has for that, and a return from the enclosing method is usually clearer.
Console.WriteLine("break and step:");
foreach (var word in new[] { "alpha", "beta", "gamma" })
{
if (word == "beta")
{
break;
}
Console.WriteLine(word);
}
for (int i = 0; i < 5; i += 2)
{
Console.WriteLine(i);
}
dotnet run
break and step:
alpha
0
2
4
The break stopped the walk at beta, so gamma was never reached, and the second loop stepped by two. A for whose condition never becomes false is an infinite loop, which a program writes on purpose with for (;;) and ends with a break — the REPL of capstone B is one.
Exercises
- Write the first program with total += value > 0 ? value : 0; instead of the continue and compare the two.
- Change the do loop to a while loop with the same condition. Which line disappears from the output?
- Print the numbers from 10 down to 1 with a for loop and with a while loop.
- Write a nested loop and leave both levels at once. Which of the three ways does your code read best?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which loop always runs its body at least once?
Answer
do while
A do while tests its condition after the body, so the first pass happens whatever the condition says.
-
What does this program print?
int total = 0; for (int i = 1; i <= 4; i++) { total += i; } Console.WriteLine(total);Answer
10
The loop adds 1, 2, 3 and 4, and the sum of the first four numbers is 10.
-
What does this program print?
foreach (var n in new[] { 1, 2, 3 }) { if (n == 2) { continue; } Console.WriteLine(n); }Answer
1 / 3
continue skips the rest of the body for 2, so only 1 and 3 print, each on its own line.
-
What does this program print?
int n = 0; do { Console.WriteLine(n); n++; } while (n < 0);Answer
0
The body runs once before the condition is tested, and the condition is false at once, so only 0 prints.
-
What does break do inside a for loop?
Answer
It leaves the loop at once
break ends the innermost loop or switch; continue is the one that goes to the next pass.
-
Why does
if (count)not compile in C#?Answer
A condition must be a bool, and an int does not convert to one
C# has no implicit conversion from a number to bool, unlike C, so the comparison has to be written out.
-
What does this program print?
int i = 0; while (i < 3) { Console.WriteLine(i); i++; }Answer
0 / 1 / 2
The condition is tested before each pass, so the body runs for 0, 1 and 2 and stops when i reaches 3.
-
What does this program print?
Console.WriteLine(5 > 3 ? "yes" : "no");Answer
yes
The conditional operator is an expression that returns the branch its condition chooses.
-
What does this program print?
foreach (var n in new[] { 1, 2, 3 }) { if (n == 1) { break; } Console.WriteLine(n); }Answer
nothing
The break fires on the first element, before anything is printed, so the output is empty.
-
Which loop form visits every element of an array without an index?
Answer
foreach
foreach takes the collection and gives each element in turn, so no index or length is written by hand.
The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev