Control Structures: Conditional Statements and Loops
Control structures in C# allow you to control the flow of code execution based on certain conditions. They are a fundamental part of the language and include conditional statements and loops.
Conditional Statements
Conditional statements allow your code to make decisions and execute a different set of statements based on whether a condition is true or false. The primary conditional statements in C# are if, else if, else, and switch.
If-Else
The if statement evaluates a condition, and if it's true, the block of code inside the if statement is executed. The else clause is optional and contains the code that is executed if the condition is false.
csharpCopy codeint number = 10; if (number > 5) { Console.WriteLine("The number is greater than 5"); } else { Console.WriteLine("The number is 5 or less"); }
Reference: https://www.tutorialsteacher.com/csharp/csharp-if-else
Switch
The switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable is checked for each switch case.
csharpCopy codeint dayOfWeek = 3; switch (dayOfWeek) { case 1: Console.WriteLine("Monday"); break; case 2: Console.WriteLine("Tuesday"); break; case 3: Console.WriteLine("Wednesday"); break; // and so on... default: Console.WriteLine("Invalid day"); break; }
Reference: https://www.tutorialsteacher.com/csharp/csharp-switch
Loops
Loops in C# allow a block of code to be executed repeatedly. The main types of loops in C# are for, while, do-while, and foreach.
For
The for loop is used when you know the number of times the loop should run. It has three parts: initialization, condition, and iteration.
for (int i = 0; i < 10; i++) { Console.WriteLine(i); }
Reference: https://www.tutorialsteacher.com/csharp/csharp-for-loop
While
The while loop keeps executing a block of code as long as a condition remains true.
int i = 0; while (i < 10) { Console.WriteLine(i); i++; }
Reference: https://www.tutorialsteacher.com/csharp/csharp-while-loop
Do-While
The do-while loop is similar to the while loop but checks the condition after the loop has executed, ensuring that the loop gets executed at least once.
int i = 0; do { Console.WriteLine(i); i++; } while (i < 10);
Reference: https://www.tutorialsteacher.com/csharp/csharp-do-while-loop
Foreach
The foreach loop is used to iterate over collections such as arrays, lists, and others.
string[] days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}; foreach (string day in days) { Console.WriteLine(day); }