Booleans
A value of type Boolean can only be true or false.
We have 3 basic operators for combining them:
!, the negation operator&&, the AND operator||, the OR operator
Negation operator
The negation operator flips the value.
Let's say we have a variable b: Boolean.
If b == true, then !b == false.
If b == false, then !b == true
AND operator
The AND operator (&&) combines 2 Boolean values with logical AND.
We use it when we want to execute some code only if both values are true.
Here is a small table with all possible combinations:
a | b | a && b |
|---|---|---|
false | false | false |
false | true | false |
true | false | false |
true | true | true |
OR operator
The OR operator (||) combines 2 Boolean values with logical OR.
We use it when we want to execute some code if any of values is true.
Here is a small table with all possible combinations:
a | b | a || b |
|---|---|---|
false | false | false |
false | true | true |
true | false | true |
true | true | true |
Let's now make a program that takes 2 numbers from user.
Then it should tell us if both numbers are positive.
Steps:
- declare 2 integers:
xandy - add input both
xandy - add an
Ifblock with expressionx>0 && y>0 - add
Outputblock in thetruebranch, with value"Both are positive" - add
Outputblock in thefalsebranch, with value"One of the numbers is not positive"