Introduction
If-else helps your program make choices. It runs different code depending on conditions.
If-else helps your program make choices. It runs different code depending on conditions.
if (condition) { // code runs if condition is true } else { // code runs if condition is false }
condition is a true or false question your program asks.if part or the else part.age is 18 or more. It prints a message based on that.int age = 18; if (age >= 18) { Console.WriteLine("You can vote."); } else { Console.WriteLine("You are too young to vote."); }
number is positive or not and prints accordingly.int number = -5; if (number > 0) { Console.WriteLine("Positive number"); } else { Console.WriteLine("Zero or negative number"); }
This program asks the user for their age. It then uses if-else to print if they are an adult or a minor.
using System; class Program { static void Main() { Console.Write("Enter your age: "); int age = int.Parse(Console.ReadLine() ?? "0"); if (age >= 18) { Console.WriteLine("You are an adult."); } else { Console.WriteLine("You are a minor."); } } }
Make sure the condition inside if is something that results in true or false.
You can have many if statements, but only one else per if.
If-else lets your program choose between two paths.
The if block runs when the condition is true.
The else block runs when the condition is false.
else block do in an if-else statement in C#?if block runs when its condition is true.else block runs only when the if condition is false.if condition is false -> Option Delse runs if if is false [OK]int x = 5;
if (x > 10) {
Console.WriteLine("Greater");
} else {
Console.WriteLine("Smaller or equal");
}int num = 7;
if num > 5 {
Console.WriteLine("Big");
} else {
Console.WriteLine("Small");
}num > 5, causing a syntax error.num. Which if-else structure correctly implements this?num is positive, negative, or zero.Pass the test and this pattern moves unknown