Hi, my name is Mateo,
and welcome back to the course about pointers and arrays in C++.
Now that we are familiar with pointers,
I will dedicate this module to introduce you to the concept of arrays.
But before we learn how arrays work,
let's see why there was a need to invent them.
I created a simple program which you can download from the exercise files.
As you can see,
this program is a really simple and primitive implementation of a calculator.
First, we ask the user to input three numbers, which will act as operands.
We store each of these numbers in their dedicated variables.
Then we ask the user to pick an operator.
To keep things simple, we only allow addition and multiplication.
Operator itself will be stored as a simple
character inside of this char variable.
Once we have the selected operator,
we can use switch case to check which calculation needs to be executed.
For example, if the user input was a plus character,
we will add all of the operands and output the result to the terminal.
And that's it.
Let's compile this program to see if it works.
I will input three random numbers and choose multiplication,
and it seems that our calculator works just fine.
But what if I suddenly have the need to input four operands instead of three?
That means that my calculator needs to store one additional number.
Well, this seems simple enough.
I will change this number 3 from the message to 4 and declare another variable,
num4.
And of course, now I need to also allow the user to input this number.
Since we have four operands now,
we need to add this new operand to every case, every possible operator.
If we had more operators, we would have to add this
number to each one of them manually.
As you can see, a lot of hard coding needs to be done to add just
one more operand. We need to modify the program and at this
variable manually in multiple places.
This is very error prone and also not really flexible.
And what if I decide that I need to add 50 numbers? You can see how it
would take a lot of time to declare 46 new variables and add them in all
of the required places throughout the code.
Not only will this make the code basically unreadable,
it is also a maintenance nightmare.
It would be great if we could use something like a for loop to loop
through all of the variables, but this is simply impossible because you
cannot loop through variable identifiers.
How would this code even look like? As you can see, we have a
need for some kind of a collection data structure. Now that we
are familiar with the problem, join me in the next lesson to discuss the solution