7 / 16

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:

aba && b
falsefalsefalse
falsetruefalse
truefalsefalse
truetruetrue

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:

aba || b
falsefalsefalse
falsetruetrue
truefalsetrue
truetruetrue

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: x and y
  • add input both x and y
  • add an If block with expression x>0 && y>0
  • add Output block in the true branch, with value "Both are positive"
  • add Output block in the false branch, with value "One of the numbers is not positive"