Boolean logic#
The questions we had previously are in fact Boolean expressions.
- Boolean expression
an expression that produces a Boolean value. Such a value is either true or false.
Type is bool
, which stands for Boolean.
These operators create a Boolean expression from other datatypes. Technically they input other datatypes and output a bool
>
,>=
<
,<=
==
,!=
These operators combine Boolean expressions. Technically they input bool
variables and output a bool
.
&&
||
We use Boolean logic in branching (if-else
, switch
) and loops (while
, for
).
Examples#
// Defining a Boolean variable
var iAmHavingFun = true;
// Simple boolean comparisons
var isEqual = 5 == 5; // true
var isNotEqual = 5 != 5; // false
var isGreater = 10 > 5; // true
var isLess = 5 < 10; // true
var isGreaterThanEqual = 5 >= 5; // true
var isLessThanEqual = 10 <= 5; // false
// Combination operators
var andCondition = 5 > 3 && 10 < 20; // true (both must be true)
var orCondition = 5 > 10 || 3 < 4; // true (at least one must be true)
var notCondition = !(5 == 5); // false (negation)
// Functions can also return Boolean values
List<string> fruits = ["apple", "banana", "cherry"];
var containsApple = fruits.Contains("apple"); // true
var containsOrange = fruits.Contains("orange"); // false
// Practical example: Check if a number is within a range
var number = 7;
var isInRange = number > 5 && number < 10; // true
// The last compound expression beautified using the `is` operator:
var isInRange2 = number is > 5 and < 10;
Activity 12
Which of the following are Boolean expressions and evaluate to false
, assuming the following initialization code? The statements in the choices do not affect others.
var t = true;
var f = false;
var c = 3;
var i = 9;
var k = 11;
Choices:
t == f
t = f
i >= c && k > i
!t
k != 11
10 < c || c <= 20
Activity 13 (Creating Boolean variables for user access check)
You are implementing the user access logic for a program. Create Boolean expressions for the following sentences:
The user is an administrator if the user id is larger than
65536
the username has at least three characters.
password must contain at least one of the characters
$
,|
and@
.password must be at least 20 characters long for an admin and 16 characters long for a non-admin
Use the variables:
// Inputs
string username;
string password;
uint userId;
// Outputs
var userIsAdmin = false;
var usernameValid = false;
var passwordValid = false;
User the following string functions:
if
u
is astring
:u.Length
gives the lengthu.Contains('s')
returntrue
ifs
is in the string
Activity 14
Create a program for Activity 13 that:
asks the user to enter the input variables
username
,password
etc.prints a meaningful message if both username and password are valid.
prints a meaningful message/s if username or password are not valid.