2.1 Programming With C#
2.1 Programming With C#
float f=i;
Explicit casting
Narrowing conversion
Casts data from a more precise data type to a less precise data type
(type) expression
E.g
int mark = (int)85.25;
Console.WriteLine(11 / 3); // 3
Console.WriteLine(11 % 3); // 2
Console.WriteLine(12 / 3); // 4
The operators |, & and ^ behave like ||, && and ^ for boolean expressions but bit by bit
statements;
true
}
statement
if (number % 2 == 0)
{
Console.WriteLine("This number is even.");
}
else
{
Console.WriteLine("This number is odd.");
}
07/31/2024 Event Driven Programming with C# 67
Nested if Statements
if and if-else statements can be nested, i.e. used inside another if or else statement
Every else corresponds to its closest preceding if
if (expression)
{
if (expression)
{
statement;
}
else
{
statement;
}
}
else
statement;
07/31/2024 Event Driven Programming with C# 68
Nested if Statements > Example
if (first == second)
{
Console.WriteLine("These two numbers are equal.");
}
else
{
if (first > second)
{
Console.WriteLine("The first number is bigger.");
}
else
{
Console.WriteLine("The second is bigger.");
}
}
07/31/2024 Event Driven Programming with C# 69
Multiple if-else-if-else-…
Sometimes we need to use another if-construction in the else block
Thus else if can be used:
int ch = 'X';
if (ch == 'A' || ch == 'a')
{
Console.WriteLine("Vowel [ei]");
}
else if (ch == 'E' || ch == 'e')
{
Console.WriteLine("Vowel [i:]");
}
else if …
else …
07/31/2024 Event Driven Programming with C# 70
The switch-case Statement
Selects for execution a statement from a list depending on the value of the switch
expression
switch (day)
{
case 1: Console.WriteLine("Monday"); break;
case 2: Console.WriteLine("Tuesday"); break;
case 3: Console.WriteLine("Wednesday"); break;
case 4: Console.WriteLine("Thursday"); break;
case 5: Console.WriteLine("Friday"); break;
case 6: Console.WriteLine("Saturday"); break;
case 7: Console.WriteLine("Sunday"); break;
default: Console.WriteLine("Error!"); break;
}
do
{
factorial *= n;
n--;
}
while (n > 0);
Consists of
Initialization statement
Executed once, just before the loop is entered
Boolean test expression
Evaluated before each iteration of the loop
If true, the loop body is executed
Update statement
Executed at each iteration after the body of the loop is finished
Loop body block
Question!