Center Elements
Write program that uses sizeof to print the center element of an array, or 2 center elements if the array has an even number of elements.
Expected Output:
Example Array
int iarray[30] = {
47, 129, 85, 16, 199, 34, 75, 140, 58, 102,
21, 167, 93, 186, 31, 120, 64, 150, 3, 112,
49, 178, 26, 134, 81, 158, 6, 173, 42, 190
};
Center elements: 31 & 121
Answer
#include <iostream>
using namespace std;
int main() {
int array[] = {
47, 129, 85, 16, 199, 34, 75, 140, 58, 102,
21, 167, 93, 186, 31, 120, 64, 150, 3, 112,
49, 178, 26, 134, 81, 158, 6, 173, 42, 190
};
int arraySize = sizeof(array) / sizeof(array[0]);
if (arraySize % 2 == 0) {
// Array has an even number of elements
cout << "Center elements: " << array[arraySize / 2 - 1] << " and " << array[arraySize / 2] << endl;
} else {
// Array has an odd number of elements
cout << "Center element: " << array[arraySize / 2] << endl;
}
}
We first check if the number of elements is odd or even. For an even number of elements, it prints the two central elements. For an odd number of elements, it prints the single central element.
Since we are doing integer division, we don't have to worry about casting
arraySize/2tointbefore using it for the index.