Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find middle elements from an array

Tags:

c++

arrays

In C++ how can i find the middle 'n' elements of an array? For example if n=3, and the array is [0,1,5,7,7,8,10,14,20], the middle is [7,7,8].

p.s. in my context, n and the elements of array are odd numbers, so i can find the middle. Thanks!

like image 989
qwerty Avatar asked May 04 '26 05:05

qwerty


1 Answers

This is quick, not tested but the basic idea...

const int n = 5;

// Get middle index
int arrLength = sizeof(myArray) / sizeof(int);

int middleIndex = (arrLength - 1) / 2;
// Get sides
int side = (n - 1) / 2;

int count = 0;

int myNewArray[n];

for(int i = middleIndex - side; i <= middleIndex + side; i++){
     myNewArray[count++] = myArray[i];
}
like image 93
Gabe Avatar answered May 05 '26 19:05

Gabe