// Example 1
// Declare and initialize an array called myArray that holds 5 elements of type int
int myArray[5] = {10, 20, 30, 40, 50};
// To find the length of the array (pretend you didn't know it, btw it's 5)
// An integer is 4 bytes, so we take the size of the array which is a total of 20 bytes,
// then we divide it by one element in the array which is 4 bytes
// thus: 20/4 = 5 so this means that the array has a size of 5 elements
int arraySize = sizeof(myArray)/sizeof(int);
// Counter to keep track of how many positions we are moving
// We want to move four back from the end because you want the last
// four items of the array.
int j = 0;
//Loop through the array starting at the last position of the array
//arraySize-1 = position 4
//(Don't forget that we have an array of 5 elements where the first element is at position 0).
//Each time we decrement the position and increment our j counter
for(int i = arraySize-1; j < 4; i--)
{
j++;
cout << myArray[i] << endl;
}
Program output:
50
40
30
20
Or, if you know the size of the array already (which you should, since arrays are declared and initialized statically in C++ and you, yourself have created it.) In this case you can just literally print out the last four positions of the array (i.e. the last four elements)
1 2 3 4 5 6 7 8
//Example 2
int myArray[5] = {10, 20, 30, 40, 50};
//Start at the last position and literally print out the last four elements in the array
for(int i = 4; i > 0; i--)
{
cout << myArray[i] << endl;
}