# How to find the middle element of a bulk array?

• 04-18-2009
void_mehboob
How to find the middle element of a bulk array?
Hi,

this is an interesting question a professor asked me in a viva exam.

How can I get the middle element of a bulk array without using a division operator?

It means if my array is of size 100, i will get the 50th element without using the following code snippets .....
Code:

```#include<stdio.h> main() {  int anArr[100]={5};  printf("%d\n",anArr[(sizeof(anArr)/2)/2]); // using division operator  return 0; }```
please suggest me how to get the middle element without using a division operator.
If someone know more then a solution please do let us know ....

• 04-18-2009
EVOEx

First of all, there is no middle element in an array with 100 elements. There needs to be an odd number of elements for there to be a middle element. The example divides by 2 twice. Why?
Now, for the worst part, there are loads of ways to do this. Not dividing but casting to a double, multiplying by a half, converting it to an int (don't do this, this would be the worst solution). Or by shifting the number to do the same as divide by two (I'm not going to give you the answer, so find it out by yourself). Or by creating pointers to the first and last element and increasing/decreasing them until they point to the same element.

Whatever you want...
• 04-18-2009
half1 is set equal to the total
and half2 = 0

Now, while half1 > half2, subtract one from half1, and add one to half2.
• 04-18-2009
iMalc
Move towards the middle from each end, and stop when meeting up or crossing over, is one simple way.
• 04-19-2009
nonoob
Quote:

Originally Posted by EVOEx
The example divides by 2 twice. Why?...

Because the example obfuscates the need to scale the result of sizeof() down by the element size.

(sizeof(anArr)/2)/2 should be better expressed as

sizeof(anArr) / sizeof(int) / 2