Part 1
1. What is an array?
An array is a data structure that can hold multiple types of the same type of data. Each element of the arrays is like 1 variable of the type defined when the array was created. Each element is indexed from [0] upwards and can be accessed using its index position.
2. Which index would you use to access the 2nd variable in an array?
Index position [1]
3. What can you say about the size of an array?
In a fixed array, the size of the array has to be fixed at compile time. Either with a direct numerical size or by reference to a constant. A dynamic array can have a size that is calculated at run time.
Part 2
1. How can you initialize an array?
To initialise the array elements with 0:
double yearTemperatures[365] = {};
Or we can use a list:
int legs[animals::totalAnimals] = {2, 4, 4, 4, 2, 0};
2. How can you get the size of an array in bytes?
The "sizeof(array)" function can get the size in bytes of the array. Note this is not the number of elements.
3. How can you use the function size of in order to calculate the number of elements in an array?
The number of elements can be found by: sizeof(array) / sizeof(array[0])
4. What happens when you try to write outside the bounds of the array?
This will result in undefined behavior, the array will access a memory location that has not been reserved for it and may be in use by another part of the program, and in turn crash the program.
Quiz - Part 1 & 2
#include
using namespace std;
namespace animals {
enum animals {
chicken,
dog,
cat,
elephant,
duck,
snake,
totalAnimals
};
}
void printLegs (int x){
cout << “The animal " << " has " << x << " legs.” << endl;
}
int main ()
{
//Part 1
cout << "Enter a day of the year by number: ";
int dayOfYear;
double yearTemperatures[365] = {};
cin >> dayOfYear;
cout << "The temperature on your chosen day was: " << yearTemperatures[dayOfYear] << endl;
//Part 2
int legs[animals::totalAnimals] = {2, 4, 4, 4, 2, 0};
printLegs(legs[animals::elephant]);
return 0;
}