Control Flow
Control flow is an important concept in programming that allows you to control the flow of execution based on certain conditions or loops. In C#, there are several control flow statements that you can use to achieve this.
Conditional Statements
Conditional statements are used to perform different actions based on different conditions. The most common conditional statements in C# are if
, else if
, and else
.
Here's an example:
1int num = 10;
2
3if (num > 0)
4{
5 Console.WriteLine("The number is positive.");
6}
7else if (num < 0)
8{
9 Console.WriteLine("The number is negative.");
10}
11else
12{
13 Console.WriteLine("The number is zero.");
14}
The output of the above code will be:
1The number is positive.
Loops
Loops are used to repeat a set of statements multiple times. In C#, there are three types of loops: for
, while
, and do-while
.
Here's an example of a for
loop:
1for (int i = 1; i <= 5; i++)
2{
3 Console.WriteLine("The value of i is: " + i);
4}
The output of the above code will be:
1The value of i is: 1
2The value of i is: 2
3The value of i is: 3
4The value of i is: 4
5The value of i is: 5
Conclusion
Control flow statements such as conditional statements and loops are essential for controlling the flow of execution in a program based on certain conditions or for repeating a set of statements multiple times. Mastering these concepts will greatly enhance your ability to write efficient and effective C# code.