Showing posts with label Operators. Show all posts
Showing posts with label Operators. Show all posts

C++ Logical Operators: AND (&&), OR (||) and NOT (!)

In this tutorial of our C++ course, we will learn three more operators, called logical operators, that will allow us to do more complex and interesting conditional tests. They are:

  • && - AND 
  • || - OR
  • ! - NOT

Logical Operator AND: &&

The && operator serves to merge two logical expressions into one, like this:

  • expression1 && expression2

The result of this expression is true only if expression1 and expression2 are true.
If either one of them is false, the general expression becomes false as well.

The truth table of the && operator is:

Logical operators in C++

For example, for you to donate blood, there must be two conditions:
  • Be in legal age
  • Not have diseases

That is, for pain you need to be adult AND ALSO not have diseases:
  • adulthood && have no diseases

If any of these conditions are not true, you cannot donate blood.
Let's redo the program that says whether you must vote or not.

To be mandatory, it must satisfy two conditions:
  1. 21 years or older
  2. Under 65

That is, you must be 21 years old AND (AND) must be under 65 years old.
Our C++ code looks like this:

#include <iostream>
using namespace std;

int main()
{
    int age;

    cout <<"Your age: ";
    cin >> age;


    if( age>=21 && age<65 )
        cout << "Required to vote.";
    else
        cout << "Optional vote";


    return 0;
}

See that it was much more cleaner code, because we made two conditional tests at once within the IF.
If the person is under 21, the first expression will be false and the entire test will be false, going to ELSE.
If it is 65 or older, the second expression is already false, leaving the IF result false as well, going to ELSE.
In both cases, voting is optional.


Logical Operator OR: ||

The logical operator || (OR) joins two expressions like this:

  • expression1 || expression2

It returns true if any of the expressions are true.
That is, it only returns false if both are false. Check out this operator's truth table:

Truth table in C++

For example, if on a highway the maximum speed is 80 km/h, walking above and below half (40 km/h ) will give you a traffic ticket. Lets test:

  • speed> 80 || speed <40


That is: if the speed is greater than 80 km/h OR is below 40 km/h, the driver will be fined. If any of the expressions are true, the entire test is true.

Here's a program that takes the speed of a car and tells you whether it will generate a ticket or not:
#include <iostream>
using namespace std;

int main()
{
    int speed;

    cout <<"Speed: ";
    cin >> speed;


    if( speed>80 || speed<40 )
        cout << "You'll be fined.";
    else
        cout << "That's ok.";


    return 0;
}
The IF detects if you are going to get a fine, that is, not to get it needs to fall into ELSE, and only falls into ELSE if both expressions are false, so you are neither above 80 nor below 40, so you are between 40 and 80, which is the correct one. Did you get it? OR one thing OR another.

Logical Operator NOT: !

Finally, we have the negation operator.
It turns what is false into true, and what is true into false.

See his truth table:
Truth Tablet NOT Operator
That is:

  • !true is the same as false
  • !false is the same as true


Redoing the first code:
#include <iostream>
using namespace std;

int main()
{
    int age;

    cout <<"Your age: ";
    cin >> age;


    if( !(age>=21 && age<65) )
        cout << "Optional vote.";
    else
        cout << "Required to vote";


    return 0;
}
Redoing the second code:
#include <iostream>
using namespace std;

int main()
{
    int speed;

    cout <<"Speed: ";
    cin >> speed;


    if( !(speed>80 || speed<40) )
        cout << "Thats ok.";
    else
        cout << "You'll be fined.";


    return 0;
}
It may seem more complicated or the same thing, in fact it is the same thing, but often it will be more logical and it will make more sense to use the NOT operator in some conditional statements in C++. We will see this a few times over the our C ++ course.

The precedence of operators between them is from top to bottom:
!
&&
||

Logical Operators Exercise

In the last tutorial on nested IF and ELSEs, we posed a question about converting a numeric note to A, B, C ... but there is a bug there.

What if the user types less than 0 or more than 10?

It is a mistake. Arrange the program using the logical operator || if you type notes below 0 or above 10.

C++ Math: Operators of sum (+), subtraction (-), multiplication (*), division (/), and remainder of division (%)

Without too much hype or oversimplification, we can say that a computer is nothing but a mega super hyper calculator. A special, well-incremented and powerful calculator.

Doing calculations, counting ... is the basis of computing, and hence of programming.

In this tutorial, we will learn how to do C ++ accounts.

C++ sum: + operator

To perform the addition operation, we use the + operator between two values.
It can be in literal form: 1 + 1

Or values stored in variables: value1 + value2

A program that shows the sum of the numbers 21 and 12:

#include <iostream>
using namespace std;

int main()
{
    cout << 21 + 12;
    return 0;
}


Sum + operador in C++

These values could be previously stored in variables, var1 and var2, for example and summed later, see:

How to sum in C++

Notice how we declare the variables var1 and var2.
Since both are integers, we do not need to do:
int var1=1;
int var2=2;

We can 'summarize', write less and do:
int var1=1,
     var2=2;

Much more fancy, isn't it?

C++ Subtraction: - operator

As we add, we can subtract, and for that, just use the - (minus) operator.
Let's subtract 21 from 12, and then do 1 minus 2:

#include <iostream>
using namespace std;

int main()
{
    int var1=1,
        var2=2;

    cout << "21 - 12 = " << 21-12 << endl;
    cout << "1 - 2 = " << var1-var2;
    return 0;
}

See the resulto:
Minus operation in C++

Here we use strings:
"21 - 12 = "
"1 - 2 = "

Here, numbers, math values:
21 - 12
var1 - var2

It's two different things, it's two different data types.

We did this and put everything together in the cout command (simple C++ output), to make the output very cute and neat.

C++ multiplication: * operator

In our day to day, to describe the multiplication operation, we use the x symbol, sometimes, true?
However, in C++ programming, 'x' is a letter.

To identify the product operator, we use the asterisk: *

So to multiply 2 by 2, or 21 by 12, we do:

#include <iostream>
using namespace std;

int main()
{
    int var1=2, var2=2;

    cout << "2*2 = " << var1 * var2 <<endl;
    cout << "21 * 12 = " << 21*12;
    return 0;
}

Compilation result:
How to calculate product in C++

Note that we declare the variables all on the same line. We did this because they are the same type, the integer type, and separated by comma.

We could also have done:
int var1 = 2;

And then: var1 * var1

After all, are of equal values, agree?

C++ division: / operator

In daily life, the division operator is also different, it is the “÷”.
In programming, the symbol is: /

Let's divide 4 by 2, and then 1 by 3.
The code is:

#include <iostream>
using namespace std;

int main()
{
    float var1, var2;
    var1=1;
    var2=3;

    cout << "4 / 2 = " << 4/2 <<endl;
    cout << "1 / 3 = " << var1/var2;
    return 0;
}

The compilation results in:
How to divide in C++ programming language

Note that we first declare the variables:
float var1, var2;

And only then we initialize with the values 1 and 3:
var1 = 1;
var2 = 3;

It is another way of declaring and initializing variables.

In the first cout, we divided 4 by 2. Two integers, with results of integer division, and C++ showed the resulting integer: 2.

But by dividing 1 by 3, the result is decimal. So we declared the variables var1 and var2 as float, because we knew we would need the decimal places to represent the division operation.

Change the float declaration to double, what happened? Say it in the comments.
Change the float declaration to int, what happened? Say it in the comments.

Remainder: % operator


Finally, let's use the% arithmetic operator, called the modulus or remainder of the division.
Let's go back to school and remember how we used to contain:

Rest of division in C++

See that 'remainder'? It is the rest of the division of 17 by 2.

To get this result, do:

  • 17 % 2 = 1
This operator is special because it's only used with integers, ok?
In the future, in our C++ course, we will use the module operator (or remainder of the division) for some specific algorithms, such as finding prime numbers and working with multiples.


Math exercises in C++

01. Write a program that adds the numbers 10, 20 and 30
02. Write a program that divides 21 by 12
03. What is the module, or remainder of the division, of number 21 by 12?
04. What is the error of the code below?


#include <iostream>
using namespace std;

int main()
{
    number = 2112;
    int number;

    cout << "Number: "<< number <<endl;
    return 0;
}

05. Store in the 'sum' variable the result exercise 1. Then divide by 3 to find the average, what value did you find?
06. Redo the previous exercise, but without using any variables, that is, print the value of the direct result in cout.
07. If you do: 10 + 20 + 30/3, what is the result? Is it the average? If not, why did it go wrong?

Soon, still in our Introduction to C++ section, let's return to the operators in relation to their precedence.

Study resources