Conditionals in C#
Conditionals are used to perform different actions based on different conditions.
Example: Using if-else Statements
using System;
namespace NationalParks
{
class ParkStatus
{
static void Main(string[] args)
{
string parkName = "Yosemite National Park";
bool isOpen = false;
if (isOpen)
{
Console.WriteLine($"{parkName} is open to visitors.");
}
else
{
Console.WriteLine($"{parkName} is currently closed.");
}
}
}
}
Example: Using switch Statements
using System;
namespace NationalParks
{
class ParkSwitch
{
static void Main(string[] args)
{
string parkCode = "YNP"; // Yosemite National Park
switch (parkCode)
{
case "YNP":
Console.WriteLine("Yosemite National Park");
break;
case "ZNP":
Console.WriteLine("Zion National Park");
break;
case "GNP":
Console.WriteLine("Glacier National Park");
break;
default:
Console.WriteLine("Unknown park code");
break;
}
}
}
}
xplanation:
if-else statement evaluates a boolean condition and executes corresponding code blocks.
switch statement selects a code block to execute based on the value of a variable.
Loops
Loops in C#
Loops are used to execute a block of code repeatedly.
Example: Using for Loop
using System;
namespace NationalParks
{
class ParkLoop
{
static void Main(string[] args)
{
string[] parks = { "Yellowstone", "Yosemite", "Zion", "Grand Canyon" };
for (int i = 0; i < parks.Length; i++)
{
Console.WriteLine(parks[i]);
}
}
}
}
Example: Using while Loop
using System;
namespace NationalParks
{
class ParkWhile
{
static void Main(string[] args)
{
string[] parks = { "Yellowstone", "Yosemite", "Zion", "Grand Canyon" };
int index = 0;
while (index < parks.Length)
{
Console.WriteLine(parks[index]);
index++;
}
}
}
}
Example: Using do-while Loop
using System;
namespace NationalParks
{
class ParkDoWhile
{
static void Main(string[] args)
{
string[] parks = { "Yellowstone", "Yosemite", "Zion", "Grand Canyon" };
int index = 0;
do
{
Console.WriteLine(parks[index]);
index++;
} while (index < parks.Length);
}
}
}
Example: Using foreach Loop
using System;
namespace NationalParks
{
class ParkForeach
{
static void Main(string[] args)
{
string[] parks = { "Yellowstone", "Yosemite", "Zion", "Grand Canyon" };
foreach (var park in parks)
{
Console.WriteLine(park);
}
}
}
}
Explanation:
for loop iterates a specific number of times.
while loop continues as long as the condition is true.
do-while loop executes at least once and continues as long as the condition is true.
foreach loop iterates through each element in a collection.