Informatics 2 - 4,5,6
Informatics 2 - 4,5,6
0 1 2 3 4
billy 16 2 77 40 12071
Initializing arrays
The amount of values between curly braces { } must not be larger than the number
of elements that we declare for the array between square brackets [ ].
For example, in the example of array billy we have declared that it has 5 elements
and in the list of initial values within braces { } we have specified 5 values, one for
each element.
When an initialization of values is provided for an array, C++ allows the possibility
of leaving the square brackets empty [ ]. In this case, the compiler will assume a
size for the array that matches the number of values included between braces { }:
int billy [] = { 16, 2, 77, 40, 12071 };
After this declaration, array billy would be 5 ints long, since we have provided 5
initialization values.
Accessing the values of an array.
In any point of a program in which an array is visible, we can access the value of
any of its elements individually as if it was a normal variable, thus being able to
both read and modify its value. The format is as simple as:
name[index]
Example
For example, to store the value 75 in the third element of billy, we could write the
following statement:
billy[2] = 75; billy[0] billy[1] billy[2] billy[3] billy[4]
billy
and, for example, to pass the value of the third element of billy to a variable called
a, we could write:
a = billy[2];
Examples
1. Write a C++ program that reads in 10 integers from the user and stores them
in an array. The program should then compute and output the sum and
average of the elements in the array.
2. Write a C++ program that reads in 10 integers from the user and stores them
in an array. The program should then compute and output the sum and
average of the elements in the array.
3. Write a C++ program that reads in an array of 10 integers from the user and
outputs the largest and smallest values in the array.
Pointers and arrays
The concept of array is very much bound to the one of pointer.
In fact, the identifier of an array is equivalent to the address of its first element, as
a pointer is equivalent to the address of the first element that it points to, so in fact
they are the same concept.
int numbers [20];
int * p;
It is possible to do
p = numbers;
2. Create an integer array of size 6 and initialize it with some random values.
Declare two pointers 'ptr1' and 'ptr2', and make 'ptr1' point to the first
element of the array and 'ptr2' point to the last element of the array. Then,
using these pointers, calculate and display the sum of the elements they
point to.
Homework
Declare a five-element integer array with numbers 101, 102, 103, 104, 105, and
a pointer variable 'p'. Display the elements of the array using the variable 'p'.