|
Logical Expressions and Conditional Statements
Part:
1
2
Logical Expressions
Logical expression is a way of expressing a logical condition, upon which certain parts
of the program execution flow can be altered. For example, a furniture store wants the
following delivery charges in its invoice program: if the total amount of an order is
less than $200.00, delivery is charged as $25.00; if the amount is greater than or
equal to $200.00, delivery is free. Here "amount is less than $200.00" is a logical condition
that needs to be entered in C# program as a logical express.
The most simplest logical conditions involves relational operators:
- ">": Greater than
- "<": Less than
- ">=": Greater than or equal
- "<=": Less than or equal
- "==": Equal
- "!=": Not equal
A relational operation can be entered into C# programs as a logical expression with the
following syntax:
logical_expression:
arithmetic_expression relational_operator arithmetic_express
After evaluation, a logical expression will produce a boolean value, true or false.
Examples of logical expressions are:
- "1 < 2":
This is a simple logical expression. The resulting value is true.
- "1 > 2":
This is also a simple logical expression. The resulting value is false.
- "quantity * price < 200.00":
The arithmetic expression "quantity * price" will be evaluated first. Its result
will be then compared with 200.00. The resulting value is true or false, depending on
the resulting value of arithmetic expression.
- "exam_score == 100":
If the value in exam_score is equal to 100, the resulting value will be true.
Otherwise, it will be false.
"if" Statements
The most commonly used conditional statement is the "if" statement, which has the following
syntax:
if statement:
if (logical_expression) {
embeded_statements
}
When an "if" statement is encountered in the excution flow, the logical expression will be
evaluated first. If the resulting value is true, the embeded statements that are enclosed in braces
immediately after the logical expression will be executed. If the resulting value is false,
those embeded statements will be skipped.
An "if" statement can also have an "else" clause, which will contain a block of embeded statements
to be executed only when the logical expression is evaluated to false. Here is the syntax
of "if else" statement:
if statement:
if (logical_expression) {
embeded_statements
} else {
embeded_statements
}
In the "else" clause, we could have another logical condition to separate the execution in
two more ways:
if statement:
if (logical_expression) {
embeded_statements
} else if (another_logical_expression) {
embeded_statements
} else {
embeded_statements
}
(Continued on next part...)
Part:
1
2
|