Showing posts with label Mathematical Operations. Show all posts
Showing posts with label Mathematical Operations. Show all posts

Pointers, Arrays and Arithmetic

Continuing the study of pointers, we will see their important relationship with arrays, as well as learn how to manipulate pointers arithmetically, with mathematical operations.

Arrays and Pointers, Pointers and Arrays

Just for curiosity, let's declare an array of integers, named 'numbers', initialize and then simply print the value '*numbers':
#include <iostream>
using namespace std;

int main()
{
    int numbers[]={1, 2, 3, 2112};

    cout << *numbers << endl;

    return 0;
}
Look how interesting the result:
Curso de C++ online grátis, com apostila para download

That is: the name of the array works like a pointer.
And where does it point? For the first element of the array.

So, whenever we have an array named: arr
If we use the name of the array variable, it will behave like an array that points to: arr[0]

And to point to the other members of the array?
Remember the following rule:
  • arr[index] = *(arr + index)
Thus:
arr[0] can be referenced by *(arr + 0)
arr[1] can be referenced by *(arr + 1)
arr[2] can be referenced by *(arr + 2)
...
arr[n] can be referenced by *(arr + n)

We can make a pointer named 'ptr' point to the first element of an array in the following ways:
  1. int *ptr = numbers;
  2. int *ptr = &numbers[0];

Let's print an entire array, using just one pointer:
#include <iostream>
using namespace std;

int main()
{
    int numbers[6]={1, 2, 3, 4, 5, 2112},
        *ptr = numbers;

    for(int aux=0 ; aux<6 ; aux++)
        cout << *(ptr+aux) << endl;

    return 0;
}

Pointer Arithmetic

In the previous C++ code example, you saw that we did an add operation with pointers several times: ptr + aux, where aux is an integer variable from 0 to 5, to go through the array.

We could have done the same program with the ++ operator, see:
#include <iostream>
using namespace std;

int main()
{
    int numbers[6]={1, 2, 3, 4, 5, 2112},
        *ptr = numbers;

    for(int aux=0 ; aux<6 ; aux++){
        cout << *ptr << endl;
        ptr++;
    }

    return 0;
}
That is, each time we add a unit to the pointer (++), it points to the next element in the array. We can do the reverse, point to the last element of the array and go on decrementing:
#include <iostream>
using namespace std;

int main()
{
    int numbers[6]={1, 2, 3, 4, 5, 2112},
        *ptr = &numbers[5];

    for(int aux=5 ; aux>=0 ; aux--){
        cout << *ptr << endl;
        ptr--;
    }

    return 0;
}
We could also use the operators -= or +=

The logic is as follows.
When we point the pointer to the array, it will point to the memory address of the first element. Let's assume that it is the 1000 memory block.

When we do: ptr++
It does not increment the memory address by one, it does not go to 1.
It goes to: 1000 + sizeof(int)

As the array is of integers, each block of the array occupies 4 Kbytes, so ptr will point to address 1004. Then to block 1008, then 1012 ...

If the array were double, it would point to the addresses: 1000, 1008, 1016, 1024 ... every time we incremented, since the double variable occupies 8 Kbytes ( sizeof(double) ).

See how is the code of the program that prints only the elements of even index, of the array (0, 2 and 4):
#include <iostream>
using namespace std;

int main()
{
    int numbers[6]={1, 2, 3, 4, 5, 2112},
        *ptr = numbers;

    for(int aux=0 ; aux<3 ; aux++){
        cout << *ptr << endl;
        ptr += 2;
    }

    return 0;
}
This is the logic and mathematics of the pointers. That is why it is so important to define the type of pointer (int, char, double ...), since the pointers point to entire blocks of memory, the size of these blocks varies according to the type of data.

Operator Precedence and Grouping Expression with Parentheses

Now that you have learned everything from the last tutorial on mathematical operations in C++, answer, head on, for us how much the following expressions are worth:
  • 1 + 6*3
  • (1+6)*3
  • 1+6/2
  • (1+6/2)

Order of Mathematical Operators

Let's take the first and third expressions.
In the first one, we have two solutions you can find:
  • 1 + 6*3 = 1 + 18 = 19
Or:
  • 1 + 6*3 = 7 * 3 = 21
In the first calculation, we did the multiplication first and then the sum.
In the second calculation, we first summed 1 to 6, and then multiplied by 3.
Which one is right?

Already the third expression, can be resolved like this:
  • 1+6/2 = 1 + 3 = 4
Some might calculate like this:
  • 1+6/2 = 7 / 2 = 3.5
In the first case, we did the division operation first. In the second case, first we add 1 to 6, only then do the division.

Let's put both expressions in a program, so C ++ will tell us which one is correct.
But first, think about which one you think is right.

Then make a program to calculate both expressions and see the result.
Our code looks like this:

#include <iostream>
using namespace std;

int main()
{
    cout << "1 + 6*3 =  "<< 1 + 6*3 <<endl;
    cout << "1+6/2 =  "<< 1+6/2<<endl;

    return 0;
}

And the result:
Curso de C++ online grátis com apostila para download

Precedence of Mathematical Operators in C++

Imagine if NASA simulates a rocket launch and a calculation results in the value 21.
But then, during the official release, another machine does the same calculation and results in a value of 12?
Damn!

Therefore, C ++ has established an order to do the calculations, a precedence between operators.
As we can see, the multiplication and division calculation was first performed before the addition.

Order of operators is as follows:
  1. *  /  %
  2. + -
That is, C++ saw a mathematical expression, the first thing you will see is whether it has a division, multiplication or module operator. If you have one, solve it first.

If you have more than one of these, resolve from left to right.

Only then will you check for any addition or subtraction.
If you have more than one? It's going from left to right too, ok?

Parentheses () - Organization and Precedence

If we enclose an operation in parentheses, it will always be performed first.
It is as if the () had a higher precedence than the mathematical operators.

For example, on account: 1 + 6 * 3
If we want the sum to be done first, we do: (1 + 6) * 3
If we want to make sure that the multiplication is done first: 1 + (6 * 3)

Suppose we want to calculate the arithmetic mean of 5 numbers, in mathematics this is given by:

How calculate average in C++

A person who has not well learned operator precedence can do:
m = a + b + c + d + e / 5;


The mistake is that only the variable e will be divided by 5, can you understand that?
The correct thing is to use parentheses:
m = (a + b + c + d + e) / 5;

So, besides getting the bill right, it gets more organized too.
Do you agree?

C ++ Exercises

1. The equation of a line is given by: y = mx + c
Write this equation in C ++ using the operators correctly.

2. Write the following algebraic equations in the correct form in C ++:

Free and complete C++ tutorial for download PDF

3. An equation of the second degree is given by: ax² + bx + c = 0
Write it in C ++ language.

4. Still in the previous equation, how would we calculate the delta?

5. And the roots of the equation of the second degree?

Study References

Complete list of precedence of other operators as well:
https://en.cppreference.com/w/cpp/language/operator_precedence

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