Decision-making is a fundamental concept that allows programs to execute different paths of code based on certain conditions. This is primarily achieved through conditional statements such as if, else if, else, switch, and the conditional (ternary) operator. Here’s a detailed overview of these constructs:
1. If Statement
The if statement is used to evaluate a condition. If the condition is true, the block of code inside the if statement is executed.
csharp1int number = 10; 2 3if (number > 0) 4{ 5 Console.WriteLine("The number is positive."); 6}
2. If-Else Statement
The if-else statement allows you to define an alternative block of code that will execute if the condition is false.
csharp1int number = -5; 2 3if (number > 0) 4{ 5 Console.WriteLine("The number is positive."); 6} 7else 8{ 9 Console.WriteLine("The number is not positive."); 10}
3. Else If Statement (Ladder If)
The else if allows you to check multiple conditions. If the first condition is false, it checks the next condition, and so on.
csharp1int number = 0; 2 3if (number > 0) 4{ 5 Console.WriteLine("The number is positive."); 6} 7else if (number < 0) 8{ 9 Console.WriteLine("The number is negative."); 10} 11else 12{ 13 Console.WriteLine("The number is zero."); 14}
4. Switch Statement
The switch statement is an alternative to multiple if-else statements. It is often used when you have a variable that can take on multiple discrete values.
csharp1int day = 3; 2 3switch (day) 4{ 5 case 1: 6 Console.WriteLine("Monday"); 7 break; 8 case 2: 9 Console.WriteLine("Tuesday"); 10 break; 11 case 3: 12 Console.WriteLine("Wednesday"); 13 break; 14 default: 15 Console.WriteLine("Invalid day"); 16 break; 17}
5. Ternary Operator
The ternary operator is a shorthand way of writing an if-else statement. It takes three operands: a condition, a result for true, and a result for false.
csharp1int number = 5; 2string result = (number > 0) ? "Positive" : "Not Positive"; 3Console.WriteLine(result);
6. Nested If Statements
You can also nest if statements within each other. This allows for more complex decision-making.
csharp1int number = 10; 2 3if (number != 0) 4{ 5 if (number > 0) 6 { 7 Console.WriteLine("The number is positive."); 8 } 9 else 10 { 11 Console.WriteLine("The number is negative."); 12 } 13} 14else 15{ 16 Console.WriteLine("The number is zero."); 17}
7. Logical Operators
You can combine multiple conditions using logical operators such as && (AND), || (OR), and ! (NOT).
csharp1int age = 20; 2 3if (age >= 18 && age < 65) 4{ 5 Console.WriteLine("You are an adult."); 6} 7else if (age < 18) 8{ 9 Console.WriteLine("You are a minor."); 10} 11else 12{ 13 Console.WriteLine("You are a senior."); 14}
