Conditional statements in C# allow you to execute different blocks of code based on certain conditions. This makes your programs more dynamic and responsive to user input or other factors. In this guide, we will explore three diverse examples of C# conditional statements: if, else, and switch. Each example will provide a clear context, a code snippet, and some notes to help deepen your understanding.
This example demonstrates how to use an if statement to check a person’s age and determine if they are eligible to vote. This is a common scenario in many applications where user input is involved.
using System;
class Program
{
static void Main()
{
Console.WriteLine("Enter your age:");
int age = Convert.ToInt32(Console.ReadLine());
if (age >= 18)
{
Console.WriteLine("You are eligible to vote.");
}
else
{
Console.WriteLine("You are not eligible to vote yet.");
}
}
}
Convert.ToInt32
method is used to convert the user input from a string to an integer.This example illustrates how to implement a grading system based on a student’s score using if-else if-else statements. This is useful in educational applications to categorize student performance.
using System;
class Program
{
static void Main()
{
Console.WriteLine("Enter your score:");
int score = Convert.ToInt32(Console.ReadLine());
if (score >= 90)
{
Console.WriteLine("Grade: A");
}
else if (score >= 80)
{
Console.WriteLine("Grade: B");
}
else if (score >= 70)
{
Console.WriteLine("Grade: C");
}
else if (score >= 60)
{
Console.WriteLine("Grade: D");
}
else
{
Console.WriteLine("Grade: F");
}
}
}
In this example, we will use a switch statement to display the name of the day based on a number input (1 for Sunday, 7 for Saturday). This is a great example of how switch statements can simplify code when dealing with multiple conditions.
using System;
class Program
{
static void Main()
{
Console.WriteLine("Enter a number (1-7) for the day of the week:");
int day = Convert.ToInt32(Console.ReadLine());
switch (day)
{
case 1:
Console.WriteLine("Sunday");
break;
case 2:
Console.WriteLine("Monday");
break;
case 3:
Console.WriteLine("Tuesday");
break;
case 4:
Console.WriteLine("Wednesday");
break;
case 5:
Console.WriteLine("Thursday");
break;
case 6:
Console.WriteLine("Friday");
break;
case 7:
Console.WriteLine("Saturday");
break;
default:
Console.WriteLine("Invalid input. Please enter a number between 1 and 7.");
break;
}
}
}