Conditional statements:
In C#, conditional statements are used to control the flow of execution based on certain conditions.
Types:
1.if
2.if-else
3.else if
4.switch
1.if statement:
The if statement is used to execute a block of code if a specified condition is true.
*Single Statement
if (condition)
{
// Code to be executed if the condition is true
}
2.if-else statement:
The if-else statement allows you to execute one block of code if the condition is true and another block if the condition is false.
*Two Statements
if (condition)
{
// Code to be executed if the condition is true
}
else
{
// Code to be executed if the condition is false
}
3.else if statement:
The else if statement is used when you have multiple conditions to check.
*Multiple Statements
if (condition1)
{
// Code to be executed if condition1 is true
}
else if (condition2)
{
// Code to be executed if condition2 is true
}
else
{
// Code to be executed if none of the conditions are true
}
4.switch statement:
The switch statement is used to select one of many code blocks to be executed.
switch (variable)
{
case value1:
// Code to be executed if variable equals value1
break;
case value2:
// Code to be executed if variable equals value2
break;
// ... more cases ...
default:
// Code to be executed if none of the cases match
break;
}
Here's a simple example using if and else:
using System;
class Program
{
static void Main()
{
int number = 10;
if (number > 0)
{
Console.WriteLine("The number is positive.");
}
else if (number < 0)
{
Console.WriteLine("The number is negative.");
}
else
{
Console.WriteLine("The number is zero.");
}
}
}
Comments
Post a Comment