Control flow statements in C# allow you to make decisions in your code. The if, else if, and else statements are fundamental constructs for controlling the flow of your program. Let's explore how to use these statements in various scenarios.
1. Basic if Statement:
The if statement is used to execute a block of code only if a specified condition is true. Here's a simple example:
In this example, the message "You are eligible to vote" will be displayed only if the age is 18 or older.
2. if-else Statement:
The if-else statement allows you to execute one block of code if the condition is true and another block if it is false.
In this example, if the age is 18 or older, the first message is displayed; otherwise, the second message is displayed.
3. if-else if Statement:
When you have multiple conditions to check, you can use else if to specify additional conditions.
In this example, the program checks three conditions and executes the block of code associated with the first true condition.
4. Nested if Statements:
You can also nest if statements within other if statements to create more complex conditions.
In this example, the program checks if the person is eligible to vote and, if so, whether they are a student eligible for a discount.
5. Run and Experiment:
Press F5 or click the "Start Debugging" button to build and run your program. Experiment by changing the values of variables and see how the program responds to different conditions.
Congratulations! You've learned how to use if, else if, and else statements for controlling the flow of your C# program. In the next tutorial, we'll explore loops for repetitive tasks.