C# Foundations

Lesson 3 of 6

Control Flow and Loops

int xp = 45;

if (xp >= 50)
{
    Console.WriteLine("Level up!");
}
else
{
    Console.WriteLine($"Keep going, {50 - xp} XP to go.");
}

for (int i = 1; i <= 5; i++)
{
    Console.WriteLine($"Lesson {i}");
}

foreach (var lang in new[] { "C#", "Python", "JavaScript" })
{
    Console.WriteLine(lang);
}

The pieces

  • if / else branch on a boolean condition.
  • for (init; condition; increment) is best when you know how many times to loop.
  • foreach (var item in collection) visits every element of an array or collection without needing an index, use it whenever you don't need the index itself.

📝 Control Flow Quiz

Passing score: 70%
  1. 1.Which loop is the best fit for visiting every element of a collection without needing an index?

  2. 2.A for loop has three parts separated by semicolons: initializer, condition, and ____.

  3. 3.An if statement in C# requires its condition to evaluate to a boolean.