in the program when you're writing, you have to make choices that do not know, you can only predict responses to be included in a program and implement its education program. choice, for example, can be done through the "if" statement.
the logical operators are used, for example, when to implement a procedure in the program, there are more cases to predict.
For example if we use education
cin >> x;
we can not know a priori the choice of the user of the program, then insert an "if" statement:
in the example that follows, we will assume that the variable "x", to be useful to the program must have values between 0 and 10, then there are two conditions to be met (x> = 0) and (x <= 10), these two conditions must be met simultaneously in the program, then you should write
1 2 3 4
|
if (x> = 0)
{
if (x <= 10)
{Statement 1 ....
|
all this is shortened by using the && (and and) and as the name suggests works if the first statement is true "and" at the same time the second statement:
1 2
|
if ((x> = 0) && (x <= 10))
{Statement 1 ...
|
we take
x = 5;
when that occurs (x> = 0), the assignment is to have a bool value "true" is equivalent to "1", while if the same statement is not verified, it takes a Boolean value of "false" which is equivalent to the value "0 ".
the same goes for the second statement (x <= 10).
then the computer when you run the program, the comparison is "logic" of the values taken by the two instructions. the possibilities are:
instruction1 statement2 comparison result &&
true (1) ----- true (1) --------- true (1)
false (0) ----- true (1) ----------false (0)
false (0) ------- false (0) ------- false (0)
true (1) -------- false (0) ------- false (0) |
therefore the conditional statement
1 2 3
|
if ((x> = 0) && (x <= 10))
{
instruction1 ....
|
will be executed if and only if the two conditions are true then (1) && (1) = (1)
etc etc. ..