-
What is an array?
– An array is an aggregate data type that lets us access many variables of the same type through a single identifier. -
Which index would you use to access the 2nd variable in an array?
– In C++, arrays are 0-indexed based so I would use index 1 to access the 2nd variable in an array. -
What can you say about the size of an array?
– For the size of an array of length N, the array elements are numbered 0 through N-1. This is called the array’s range. The size of an array is the range of the array multiplied by the size of each element -
How can you initialize an array?
– An array can be initialized element by element but this approach is not efficient. Fortunately, an array can be initialized using an initializer list as shown in the following example: int prime[5]{ 2, 3, 5, 7, 11 }; // use initializer list to initialize the fixed array
NOTE: Even if the length of the array is omitted the compiler will use the number of elements in the initializer list to determine the length.
NOTE: If the initializer list is omitted, the elements are uninitialized, unless they are a class-type. -
How can you get the size of an array in bytes?
– The sizeof() function from the header can be used to determine the size of an array. -
How can you use the function sizeof in order to calculate the number of elements in an array?
– You can divide the sizeof the array by the size of an element (usually the first element which should exist) to determine the number of elements in an array. -
What happens when you try to write outside the bounds of the array?
– Undefined behavior - such as overwriting the value of another variable, or causing the program to crash - could result if an attempt is made to write outside the bounds or range of the array.
**** QUIZ ****
double temperatures[365}{};
#include
namespace Animals {
enum Animals {
chicken,
dog,
cat,
elephant,
duck,
snake,
max_animals
};
}
int main() {
int legs[Animals::max_animals]{ 2, 4, 4, 4, 2, 0 };
std::cout << "An elephant has " << legs[Animals:elephant] << "legs.\n";
return 0;
};