Decision Making C Sharp Language

Decision Making C# Language

Decision-making is a fundamental aspect of programming, allowing you to create dynamic and responsive applications. In

uage)">C#, one of the most popular programming languages, you have a variety of tools and techniques at your disposal to make informed decisions in your code. This post will explore decision-making in C# and provide examples of how to use conditional statements and other constructs to control the flow of your program.

  1. Conditional Statements:
    Conditional statements are a key component of decision-making in C#. They allow you to execute different blocks of code based on whether a certain condition is true or false. Here are some common conditional statements in C#:

a. If Statement:
The if statement is used to execute a block of code if a specified condition is true. If the condition is false, the code block is skipped.

int age = 25;
if (age >= 18)
{
    Console.WriteLine("You are an adult.");
}

b. Else Statement:
The else statement is used in conjunction with an if statement to execute a different block of code when the condition is false.

int age = 15;
if (age >= 18)
{
    Console.WriteLine("You are an adult.");
}
else
{
    Console.WriteLine("You are a minor.");
}

c. Else-If Statement:
You can use the else if statement to check multiple conditions in a sequence.

int score = 80;
if (score >= 90)
{
    Console.WriteLine("You got an A.");
}
else if (score >= 80)
{
    Console.WriteLine("You got a B.");
}
else
{
    Console.WriteLine("You got a C or lower.");
}
  1. Switch Statements:
    The switch statement is useful when you have a specific value and want to execute different code blocks based on the value.
string day = "Monday";
switch (day)
{
    case "Monday":
        Console.WriteLine("It's the start of the week.");
        break;
    case "Friday":
        Console.WriteLine("TGIF!");
        break;
    default:
        Console.WriteLine("It's an ordinary day.");
        break;
}
  1. Ternary Operator:
    The ternary operator is a concise way to make decisions in a single line of code.
int age = 22;
string message = (age >= 18) ? "You are an adult" : "You are a minor";
Console.WriteLine(message);

Discover more from PiEmbSysTech

Subscribe to get the latest posts sent to your email.

Leave a Reply

Scroll to Top

Discover more from PiEmbSysTech

Subscribe now to keep reading and get access to the full archive.

Continue reading