Skip to content

Loops

In C#, loops are used to repeatedly execute a block of code as long as a specified condition is true or for a specified number of iterations. There are several types of loops in C#: for, while, do-while, and foreach. Each type has its own use cases, and the choice of which loop to use depends on the specific requirements of your code.

For Loop

The for loop is commonly used when the number of iterations is known beforehand. It consists of an initialization statement, a condition, and an increment or decrement statement.

C#
const int Number = 10;

// Prints the first twenty multiples of the number
for(int i = 0; i < 20; i++)
{
    Console.Write("{0} ", i * Number);
}

Output:

Text Output
0 10 20 30 40 50 60 70 80 90 100 110 110 120 130 140 150 160 170 180 190

While Loop

The while loop continues to execute a block of code as long as the specified condition is true. It is often used when the number of iterations is not known beforehand.

C#
while((fileInput = file.ReadLine()) != null)
{
    Console.WriteLine(fileInput);
}

Output:

Text Output
1,Blue,Monday
2,Red,Tuesday
3,Green,Wednesday

Do While Loop

The do-while loop is similar to the while loop, but it guarantees that the block of code is executed at least once before checking the condition.

C#
int grade = -1;
int sum = 0;
int numberOfGrades = 0;

do
{
    Console.Write("Enter a grade (-1 to exit): ");

    string input = Console.ReadLine();

    grade = Int32.Parse(input);

    if (grade != -1)
    {
        sum += grade;
        numberOfGrades++;
    }

} while (grade != -1);

double average = (double)sum / numberOfGrades;

Console.WriteLine("The average grade is {0}.", Math.Round(average));

Output:

Text Output
Enter a grade (-1 to exit): 12
Enter a grade (-1 to exit): 23
Enter a grade (-1 to exit): 90
Enter a grade (-1 to exit): 89
Enter a grade (-1 to exit): 45
Enter a grade (-1 to exit): 78
Enter a grade (-1 to exit): 56
Enter a grade (-1 to exit): -1
The average grade is 56.

ForEach Loop

The foreach loop is specifically designed for iterating over elements in arrays or collections. It automatically iterates over each element in the collection without the need for an explicit counter.

C#
int[] grades = {98, 34, 78, 45, 85};
string letterGrade = "";

foreach(int grade in grades)
{
    if(grade >= 90)
    {
        letterGrade = "A+";
    }
    else if (grade >= 80)
    {
        letterGrade = "A";
    }
    else if (grade >= 75)
    {
        letterGrade = "B+";
    }
    else if (grade >= 60)
    {
        letterGrade = "B";
    }
    else if (grade >= 65)
    {
        letterGrade = "C+";
    }
    else if (grade >= 60)
    {
        letterGrade = "C";
    }
    else if (grade >= 50)
    {
        letterGrade = "D";
    }
    else
    {
        letterGrade = "F";
    }

    Console.WriteLine(letterGrade);
}

Output:

Text Output
A+
F
B+
F
A

Loop Control Statement

break Statement

The break statement is used to exit a loop prematurely, regardless of whether the loop condition is true or false.

C#
for (int i = 0; i < 10; i++)
{
    if (i == 5)
        break;

    Console.WriteLine(i);
}

continue Statement

The continue statement is used to skip the rest of the loop's code for the current iteration and move to the next iteration.

C#
for (int i = 0; i < 10; i++)
{
    if (i == 5)
        continue;

    Console.WriteLine(i);
}

Further Reading