You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
8.5 KiB
8.5 KiB
marp | paginate | math | theme | title |
---|---|---|---|---|
true | true | mathjax | buutti | 3. Conditionals |
Conditionals
Overview
- Conditionals
if
andelse
- Logical Operators
Comparison operators
- Comparison operators are used to compare two variables
- They return either
true
orfalse
- They return either
- Two variables of any type can be compared with equality operators
- Equal to:
a == b
- (Do not mix with the assignment operator, see Lecture 2!)
- Not equal to:
a != b
- Equal to:
- Two numbers can be further compared with less than/greater than operators:
- Less than:
a < b
- Less than or equal:
a <= b
- Greater than:
a > b
- Greater than or equal:
a >= b
- Less than:
bool
data type
- As shown in Lecture 2,
bool
is a data type for storing truth valuestrue
orfalse
- Because conditionals return
true
orfalse
, the result can be stored in a variableint a = 4; int b = 3; bool areEqual = a == b; // outputs False bool biggerOrNot = a > b; // outputs True
- Useful for making multiple comparisons at once
if
, else if
and else
statements
if
checks truthfulness of a given statement- If it results in
false
, we can check if another condition is met withelse if
- Multiple
else if
can be chained indefinitely - If no statement returns
true
, theelse
block is executed - The statements are checked in order, and the first
true
condition is executed- No other block is executed
- (You can also have just
if
andelse
without theelse if
, or just a singleif
.)
int a = 2
if (a > 4)
{
// do something
}
else if (a < 2)
{
// do something else
}
else if (a < 3)
{
// do something else
}
else
{
// a is 4??
}
Conditionals: An example
double temperatureInOulu = 2.3;
double temperatureInIvalo = -10.9;
if (temperatureInOulu > temperatureInIvalo)
{
Console.WriteLine("Oulu is warmer than Ivalo");
}
else if (temperatureInOulu < temperatureInIvalo)
{
Console.WriteLine("Ivalo is warmer than Oulu");
}
else
{
Console.WriteLine
("Oulu and Ivalo have the same temperature");
}
This outputs Oulu is warmer than Ivalo
.
Not operator !
- The
!
("not") operator flips the boolean value.
Console.WriteLine(!true); // Outputs false
bool itsColdOutside = true;
if (!itsColdOutside) // same as checking if (itsColdOutside == false)
{
Console.WriteLine("It's warm outside.");
}
The switch
statement
- The
switch
statement compares the given expression (in this example, thepath
variable) with the value of eachcase
- Only the matching code is executed
- If no match is found, the default code block is executed
- This example outputs
Here's the catalogue!
break
ends each case (the code will not compile if omitted!)
string path = "/browse";
switch (path)
{
case "/browse":
Console.WriteLine("Here's the catalogue!");
break;
case "/contact":
Console.WriteLine("Here's our contact info.");
break;
default:
Console.WriteLine("Given path doesn't exist!");
break;
}
Scope of Variables
- Variables declared inside of blocks
{}
are local to that scope; they are only accessible inside of that blockif (true) { int b = 1; // b is only accessible in this block b = 2; // This works } b = 3; // This throws an error
- Similarly, classes are only defined inside their
namespace
, and have to be imported to be accessible elsewhere - Note: Some languages have
global
variables that are accessible everywhere — as an object-oriented language, C# doesn't have such feature.
Logical Operators
&&
,||
and!
are the logical AND, OR and NOT operators- These are useful when writing complex
if
statements
int a = 1;
int b = 3;
int c = 5;
if (a < 10)
{
if (b < 10)
{
if (c < 10)
{
Console.WriteLine
("All are smaller than 10!")
}
}
}
int a = 1;
int b = 3;
int c = 5;
if (a < 10 && b < 10 && c < 10)
{
Console.WriteLine
("All are smaller than 10!")
}
- Same functionality achieved in fewer lines!
Common logical operators
Operator | Name | Usage | Description |
---|---|---|---|
&& |
AND | a && b |
Returns true if both variables are true.b is not evaluated if a == false . |
|| |
OR | a || b |
Returns true if one or both variables are true.b is not evaluated if a == true . |
! |
NOT | !a |
Negates the boolean value. ( true becomes false and vice versa). |
Less common logical operators
Operator | Name | Usage | Description |
---|---|---|---|
^ |
XOR | a ^ b |
Exclusive OR ("joko tai"): returns true if only either of a or b are true , but not both! |
& |
Logical AND | a & b |
Returns true if both variables are true .Both variables are always evaluated. |
| |
Logical OR | a | b |
Returns true if one or both variables are true .Both variables are always evaluated. |
Logical operators: An Example
int uppercaseLetters = 2;
uppercaseLetters += 4; // is now 6
int specialCharacters = 2;
specialCharacters *= 2; // is now 4
if (uppercaseLetters >= 6 && specialCharacters >= 2)
{
Console.WriteLine("Strong password!");
}
else
{
Console.WriteLine("Weak password...");
}
This outputs Strong password!
Extra: Single statement if
- If a code block following a statement only has one line of code, it is possible to write the block without curly brackets:
int baa = 49; if (baa > 20) Console.WriteLine("Baa"); else Console.WriteLine("Not baa!"); if (baa > 20) Console.WriteLine("Baa"); else Console.WriteLine("Not baa!");
- You may encounter code like this — however, we highly recommend to refrain from using this syntax as it is highly prone to errors.
- Can you guess how this syntax can lead to bugs?
Exercise 1
- Create a console application that asks the user which weekday it is and assigns the answer to a string variable.
- Using a switch-case expression, calculate the days remaining until next Monday.
- If the result is more than 3, print
Have a nice week!
. Otherwise, printHave a nice weekend!
.
Exercise 2
- Create a console application that lets the user input a note as a string.
- If the length of the note is less than 30, the program prints the current time and the note separated by a tab. Otherwise, the date and the note are printed to a separate line.
Tip: Use DateTime.Now.ToString()
for current time. Use .Length
after your message variable to get the length of the message.
Reading
Basics covering the syntax in C# are covered here: