Instrukcja warunkowa w C#
Instrukcja warunkowa pozwala wykonać blok kodu po spełnieniu określonych warunków
Console.Write("Pin: ");
string input = Console.ReadLine();
if (input == "1234")
{
Console.WriteLine("Pin accepted.");
}
Instrukcja else if
Console.Write("Pin: ");
string input = Console.ReadLine();
if(input == "1234")
{
Console.WriteLine("Pin accepted");
}
else if(input == "0000")
{
Console.WriteLine("Hello my master");
}
else
{
Console.WriteLine("Pin incorrect");
}
Instrukcja if z losową liczbą
Random rand = new();
int result = rand.Next(0, 20);
int mark;
if(result >= 17)
{
mark = 5;
}
else if(result >= 15)
{
mark = 4;
}
else if(result >= 10)
{
mark = 3;
}
else
{
mark = 2;
}
Console.WriteLine(mark);
Operatory porównania (Comparison operators)
== | Equal to | x == y |
!= | Not equal | x != y |
> | Greater than | x > y |
< | Less than | x < y |
>= | Greater than or equal to | x >= y |
<= | Less than or equal to | x <= y |
Operatory logiczne (Logical operators)
&& | Logical and | Returns true if both statements are true |
|| | Logical or | Returns true if one of the statements is true |
! | Logical not | Reverse the result, returns false if the result is true |
Przykłady programu z użyciem operatorów logicznych
Console.Write("Pin: ");
string input = Console.ReadLine();
if (input == "1234" || input == "0000")
{
Console.WriteLine("Pin accepted");
}
Console.Write("UserId: ");
string userID = Console.ReadLine();
Console.Write("Password: ");
string password = Console.ReadLine();
if (userID == "Matt" && password == "1234")
{
Console.WriteLine("Login and password correct. Hello!");
}
Console.Write("UserId: ");
string userID = Console.ReadLine();
Console.Write("Password: ");
string password = Console.ReadLine();
if (!(userID == "Matt" && password == "1234"))
{
Console.WriteLine("Login and password incorrect. Bye!");
}