Understanding Conditional Statements in C# with Examples

Understanding Conditional Statements in C# with Examples

Introduction

Conditional statements in C# allow programs to make decisions based on certain conditions. These statements control the flow of execution and help implement logic efficiently.

Types of Conditional Statements in C#

C# provides several types of conditional statements:

  • if statement
  • if-else statement
  • else if ladder
  • switch statement
  • switch?statement

Let's explore each with simple examples.


1. The if Statement

The if statement executes a block of code only if the condition evaluates to true.

Example:

int age = 20 ;
if (age >= 18)
 {
    Console . WriteLine ("You are eligible to vote.") ;
}        

Output:

You are eligible to vote.        

2. The if-else Statement

The if-else statement provides an alternative block of code if the condition is false.

Example:

int age = 16 ;
if (age >= 18) {
    Console . WriteLine("You are eligible to vote.") ;
}
else 
{
    Console . WriteLine("You are not eligible to vote yet.") ;
}        

Output:

You are not eligible to vote yet.        

3. The else if Ladder

When multiple conditions need to be checked, the else if ladder is useful.

Example:

int score = 85 ;
if (score >= 90) {
    Console.WriteLine ("Grade: A") ;
}
else if (score >= 80) {
    Console.WriteLine ("Grade: B") ;
} 
else if (score >= 70) {
    Console.WriteLine("Grade: C") ;
} 
else 
{
    Console.WriteLine("Grade: F") ;
}        

Output:

Grade: B        

4. The switch Statement

The switch statement is used when we need to check multiple values of a single variable efficiently.

Example:

string day = "Monday";
switch (day) {
    case "Monday":
        Console.WriteLine("Start of the week!");
        break;
    case "Friday":
        Console.WriteLine("Weekend is near!");
        break;
    default:
        Console.WriteLine("Regular day");
        break;
}        

Output:

Start of the week!        

Conclusion

Conditional statements are an essential part of programming in C#. They help in decision-making and controlling the flow of execution based on conditions. Understanding if, if-else, else if, and switch statements will allow you to write efficient and logical C# applications.

??Keep practicing, and soon you'll master control flow in C#!

Hemant Kumar

Data Administrator at a3logics, Jaipur

2 周

Very informative

回复

要查看或添加评论,请登录

Divya Soni的更多文章

社区洞察