Course 3 – For and logical operators

In the previous course we discussed about the cin and cout objects.

A few things to mention about them:

std::cin

cin is a stream that ‘listens’ to the keyboard and receives the input. If we want to read more data, we can do that in only one line.

This is the equivalent of:

std::cout

cout does the same when we push data to the screen

if / elseif / else

If in the code we have two ifs, both of the conditions will be checked.

Here, conditions are independent.

If we have if-elseif:

If it’s raining we take an umbrella, otherwise, if it’s snowing, we take a jacket – but never both.

If the first condition is valid, the second one will not be executed (note the otherwise)

Therefore, we use two ifs if both conditionals are independent, and if/elseif when they are related in some way.

We enter the elseif statement if the value is less than 20.

Because we are here, we know that the condition from above was not fulfilled – so value is higher than 10.

When we use if and elseif – without a final else – we can understand that there are situations in which the code will not be executed.

If the code looks like this:

If see that we have an if-elseif, but we go through the whole set of values possible for that data.

Here, there are two conditions that are validated: if value > 0, and if value <= 0 – but we can simplify it and use just an if-else, validating only one condition.

for loop

The for instruction looks like this:

++i means we increment the value of i – similar to i++, i += 1, i = i+1.

  • The first part of for is executed only once.
  • Then, the condition is validated
  • If the condition is still true, the code is executed
  • At the end, the value is incremented

This is similar with the following code:

AND operator &&

If we want to validate multiple conditions at the same time, we use operator &&.

The result is true if both conditions are true.

This is equivalent to:

Example:

We do not want to go to the vet if we don’t have a cat, but also if we have a cat but the cat is not sick.

OR operator ||

For this operator, the result is true if only one of the conditions is valid.

Example:

In this case, if at least one of the conditions is valid, we will take a jacket 🙂

You may also like...