In C#, control structures are used to control the flow of execution in a program. Here are some of the key control structures in C#:
1. If statements: If statements are used to test a condition and execute a block of code if the condition is true. The basic syntax for an if statement is:
if (condition) { // code to execute if condition is true }
For example:
int x = 10; if (x > 5) { Console.WriteLine("x is greater than 5"); }
2. Else statements: Else statements are used with if statements to execute a block of code if the condition is false. The basic syntax for an else statement is:
if (condition) { // code to execute if condition is true } else { // code to execute if condition is false }
For example:
int x = 3; if (x > 5) { Console.WriteLine("x is greater than 5"); } else { Console.WriteLine("x is less than or equal to 5"); }
3. Switch statements: Switch statements are used to test a variable against a series of values and execute a block of code if the value matches. The basic syntax for a switch statement is:
switch (variable) { case value1: // code to execute if variable == value1 break; casevalue2: // code to execute if variable == value2 break; default: // code to execute if variable does not match any of the cases break; }
For example:
int x = 2; switch (x) { case 1: Console.WriteLine("x is equal to 1"); break; case 2: Console.WriteLine("x is equal to 2"); break; default: Console.WriteLine("x is not equal to 1 or 2"); break; }
4. While loops: While loops are used to execute a block of code repeatedly while a condition is true. The basic syntax for a while loop is:
while (condition) { // code to execute while condition is true }
For example:
int x = 1; while (x <= 10) { Console.WriteLine(x); x++; }
This code will print the numbers 1 through 10 to the console.
5. For loops: For loops are used to execute a block of code a fixed number of times. The basic syntax for a for loop is:
for (initialization; condition; increment) { // code to execute each iteration }
For example:
for (int i = 0; i < 10; i++) { Console.WriteLine(i); }
This code willprint the numbers 0 through 9 to the console.
6. Foreach loops: Foreach loops are used to iterate over the elements of a collection, such as an array or a list. The basic syntax for a foreach loop is:
foreach (type variable in collection) { // code to execute for each element in the collection }
For example:
int[] numbers = { 1, 2, 3, 4, 5 }; foreach (int number in numbers) { Console.WriteLine(number); }
This code will print the numbers 1 through 5 to the console.
Control structures are fundamental to writing effective and efficient C# code. By using the right control structures, you can control the flow of execution in your program and perform complex operations with ease.