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.
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:
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.
Output:
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.
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:
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.
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:
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.
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.