Branching and loops in C#: if, switch, for, while and foreach

Lesson 4 of 15 · C#

A program does not always have to execute its statements in the same order. Branching chooses which part of the code will run depending on a condition, and loops repeat the same part of the code several times. The syntax is almost the same as in C, C++ and Java, and C# also adds the switch expression and the foreach loop.

Before you start: required prior knowledge – data and operators.
How to learn: type in and run every example, and solve the tasks at the end on your own first; open the hint and the solution only after that. All programs are C# console applications (.NET 8 or later, without "top-level statements"); every one has been tested and gives the output shown.

The if – else statement

The condition in brackets must be of type bool. Several conditions are chained with else if; they are checked in order and only the first branch whose condition is true is executed.

using System;

class Program
{
    static void Main()
    {
        int points = int.Parse(Console.ReadLine());
        int grade;
        if (points >= 90)
            grade = 5;
        else if (points >= 75)
            grade = 4;
        else if (points >= 60)
            grade = 3;
        else if (points >= 45)
            grade = 2;
        else
            grade = 1;
        Console.WriteLine($"Grade: {grade}");
    }
}

When a branch has several statements, you write a block in curly brackets { … }. For choosing between two values there is a shorter conditional operator: condition ? value1 : value2.

The switch statement and the switch expression

When one value is compared with several constants, switch is clearer. Every branch ends with a break statement; several case labels can share the same branch, and since C# 9 conditions such as case >= 1 and <= 5 are allowed too.

using System;

class Program
{
    static void Main()
    {
        int day = int.Parse(Console.ReadLine());
        switch (day)
        {
            case 6:
            case 7:
                Console.WriteLine("Weekend");
                break;
            case >= 1 and <= 5:             // relational pattern (C# 9)
                Console.WriteLine("Working day");
                break;
            default:                        // none of the cases matched
                Console.WriteLine("Invalid input");
                break;
        }
    }
}

A switch expression returns a value: each case has the form pattern => value, and _ means "everything else".

using System;

class Program
{
    static void Main()
    {
        int month = int.Parse(Console.ReadLine());
        string season = month switch
        {
            12 or 1 or 2 => "winter",
            3 or 4 or 5 => "spring",
            6 or 7 or 8 => "summer",
            9 or 10 or 11 => "autumn",
            _ => "no such month"
        };
        Console.WriteLine(season);
        string parity = month % 2 == 0 ? "even" : "odd";   // conditional operator
        Console.WriteLine($"The number {month} is {parity}.");
    }
}

The for, while and do-while loops

for is used when the number of repetitions is known in advance. while repeats as long as the condition is true and checks the condition before each pass. do-while checks the condition after each pass, so the body is executed at least once.

using System;

class Program
{
    static void Main()
    {
        // for: start; condition; step
        for (int i = 1; i <= 5; i++)
            Console.Write(i * i + " ");
        Console.WriteLine();

        // while: the number of digits of a number
        int n = 90210, digits = 0;
        while (n > 0)
        {
            n /= 10;
            digits++;
        }
        Console.WriteLine($"Number of digits: {digits}");

        // do-while: the body is executed at least once
        int k = 0;
        do
        {
            Console.Write(k + " ");
            k += 3;
        } while (k < 10);
        Console.WriteLine();
    }
}

Loops can be nested: the inner loop runs completely for every pass of the outer loop.

using System;

class Program
{
    static void Main()
    {
        for (int i = 1; i <= 4; i++)
        {
            for (int j = 1; j <= 4; j++)
                Console.Write($"{i * j,4}");     // every number takes 4 places
            Console.WriteLine();
        }
    }
}

The foreach loop, break and continue

foreach goes through all the elements of an array or a collection, without a counter. The continue statement skips the rest of the current pass, and break stops the loop immediately.

using System;

class Program
{
    static void Main()
    {
        int[] numbers = { 4, -2, 7, 0, 9, 12, -5 };
        int sum = 0;
        foreach (int x in numbers)
        {
            if (x < 0) continue;        // skip negative numbers
            if (x > 10) break;          // stop at the first number greater than 10
            sum += x;
        }
        Console.WriteLine($"Sum: {sum}");
    }
}

The numbers 4, 7, 0 and 9 are added; the number −2 is skipped, and at the number 12 the loop stops, so −5 is not even checked. Arrays are explained in detail in the next lesson.

Practice tasks

Each task has an example, a hint and a solution. The solutions have been checked on the examples in the text.

TASK 01Difficulty: easy

The largest and the smallest

The first line contains the number n, and the second line n integers separated by spaces. Print the largest and the smallest number.

Example

Input

5
3 -8 12 7 0

Output

Largest: 12
Smallest: -8
TASK 02Difficulty: medium

Prime numbers up to n

Read n (n ≥ 2) and print all the prime numbers from 2 to n, separated by spaces.

Example

Input

30

Output

2 3 5 7 11 13 17 19 23 29
Common mistakes and tips
  • A comparison is written with ==; a single = is an assignment and is an error in a condition.
  • In a switch statement every branch must end with break (or return).
  • Check whether the condition of a while loop ever changes – otherwise the loop never ends.
  • In a foreach loop the variable is read-only; to change the elements of an array use for.

Check your knowledge

Open the quiz

Branching and loops in C#

1. How many times is the body of the loop for (int i = 0; i < 5; i++) executed?




2. Which loop is sure to execute its body at least once?




3. What does the continue statement do?




4. What does _ mean in a switch expression?