Conditionals
Explore how to use conditional statements in C# to control program flow based on logical conditions. Learn the syntax and purpose of if-else, else if, switch, and ternary operators. Understand how to apply comparison and logical operators for dynamic boolean expressions, and implement nested conditions in practical examples like checking adult age and leap years.
Conditional statements are a basic component of many programming languages. They control program flow depending on given conditions.
The if-else statement
Consider the following scenario. We want to determine if a user is an adult based on their age. A user is an adult if they are 18 or older
Let’s first create a variable to obtain the user’s age.
Console.Write("What is your age? ");int age = Convert.ToInt32(Console.ReadLine());
We now perform a check. If age is greater than or equal to 18, we print "You are an adult!". Otherwise, we print "You are not yet an adult.".
Such checks can be done using the if-else statement in C#. The basic syntax is as follows:
if (condition){// Actions to be executed if the condition is true}else{// Actions to be executed if the condition is false}
The condition must be a boolean expression that evaluates to either true or false.
Line 1: Declares a boolean variable
isAdultand initializes it totrue.Line 3: Checks if
isAdultis true.Line 5: Executes this line because the condition is true.
Lines 8–10: The
elseblock is skipped because the condition was met.
Change the value of ...