- In this video we will see how to initialize
an array with data once we declared it.
We have essentially two choices.
Either stating the size of the array.
For example, number of classrooms being five,
we declare an array of int
that can hold a maximum of five elements,
all integers.
Notice the use of curly brackets
on the right-hand side of the array declaration.
A second alternative, without an explicit size.
For example, we want to have an array of heights
that is float and we're not committing
to a particular size of that array or length of that array,
meaning the number of elements.
The number of elements is going to be preset
depending on the number of data points we are entering.
We will see the applications of that later on in code
when we looking at different problems
that necessitate the use of an array.
For now, let's switch to code and see
those alternatives in the context of a program.
Just as before, I am defining three arrays
and it's very similar to what you saw in the example.
It is perfectly normal to have different types of arrays
and different types of initialization,
whether you are using a predefined constant
in line 19 like MAX_LETTERS
or an explicit number five in line 17 for int classrooms.
It is all up to you in what the particular needs
of your particular problem at hand are.
One thing to note is that whatever you do,
you have to ensure that you always allocate
the necessary number of elements for an array
so you don't run out of space.
For example, it is okay to go a little bit over,
let's say, you think you might need
50 or 60 data points.
It is perfectly fine to go a little bit over
and declare an array of length 80 or even 100.
It is much more memory efficient to commit yourself
in advance to a specific length of the array
because it instructs a program
to allocate that much memory to it
and it prevents potential problems later on
should you have very large arrays for which you didn't
request a specific size right in the beginning.
One last thing to notice, is that
the array on line 19 MAX_LETTERS for lastName
has been allocated 20 but "Mr. Johnson", clearly,
is less than 20 letters.
This is an example where we could allocate
more than we needed but we don't use all of them.
Since this is actually a string,
the initialization of an array of strings,
it's a little bit different than the initialization
of the array of numbers.
In the upcoming videos, we will start using arrays
in computations and solving problems.