Csharp Control Structures
Csharp Control Structures
STATEMENT
OBJECTIVES
The expression number < 5 will return false, hence the code inside if block won't be
executed.
EXAMPLE
OUTPUT
IF…ELSE STATEMENT
Use the if..else statement to specify a block of code to be executed if the condition is False.
Syntax:
if (condition)
{
// block of code to be executed if the condition is True
}
else
{
// block of code to be executed if the condition is False
}
If the boolean-expression returns true, the first statements inside the body of if ( inside {...} )
will be executed.
If the boolean-expression returns false, the second statement inside the body will be executed.
IF…ELSE EXAMPLE
• The expression number < 5 will return true, hence the code inside if
block will be executed.
IF…ELSE EXAMPLE
OUTPUT
Example explained
In the example above, time (20) is greater than 18, so the condition is False.
Because of this, we move on to the else condition and print to the screen "Good
evening". If the time was less than 18, the program would print "Good day".
THE ELSE IF STATEMENT
• Use the else if statement to specify a new condition if the first condition is
False.
Syntax
if (condition1)
{
// block of code to be executed if condition1 is True
}
else if (condition2)
{
// block of code to be executed if the condition1 is false and condition2 is True
}
else
{
// block of code to be executed if the condition1 is false and condition2 is False
}
IF…ELSE IF…EXAMPLE
OUTPUT
Example explained
In the example, time (22) is greater than 10, so
the first condition is False. The next condition,
in the else if statement, is also False, so we
move on to the else condition
since condition1 and condition2 is both False -
and print to the screen "Good evening".
However, if the time was 14, our program
would print "Good day."
NESTED IF...ELSE STATEMENT
An if...else statement can exist within another if...else statement. Such
statements are called nested if...else statement.
The general structure of nested if…else statement is:
NESTED IF..ELSE EXAMPLE
When we run the program, the
output will be:
C# SWITCH STATEMENTS
• Use the switch statement to select one of many code blocks to be executed.
Syntax:
switch(expression)
{
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
break;
}
• https://www.programiz.com/csharp-programming/if-else-statement
• https://introprogramming.info/english-intro-csharp-book/read-online/
chapter-5-conditional-statements/
• https://www.w3schools.com/cs/cs_conditions.asp