# Working on the following problem !

• 05-13-2013, 12:35 AM
Jack_Tauson_Sr
Working on the following problem !
Hello,

I have written a code to find a middle element from a sorted array. Here is some part of my code:

Code:

``` int[] a = {1,2,3,4,5}; int x = a.length;                 if (x % 2 != 0){                                                 int mid = 0 + x/2;                                                 System.out.println("The Middle Element is : " + a[mid]);                 }```
I'm getting the output properly but wondering what should I write in the else condition of the code above? In other words, what should I do to find a middle element if a.length is even? Is this possible?
• 05-13-2013, 12:42 AM
monkeyjr97
Re: Working on the following problem !
you could either:

Display the elements either side of the middle point, so use the same code you have but add this:
Code:

```int mid = 0 + x/2; int beforMid = mid - 1; int afterMid = mid +1;                         System.out.println("The Middle Elements are : " + a[beforeMid] + a[afterMid]);```
Or you can add the 2 "middle" values together and divide by 2:

Code:

``` int mid = 0 + x/2; int beforMid = mid - 1; int afterMid = mid +1; double m = (a[beforeMid]+a[afetrMid]) / 2             System.out.println("The average of middle elements is : " + m)[B][/B]```
up to you how you want to do it,

You could even just print an error message saying there is no exact middle value This isnt very user friendly though :D
• 05-13-2013, 01:07 AM
Jack_Tauson_Sr
Re: Working on the following problem !
I see. Thanks for your valuable input.
Quote:

Originally Posted by monkeyjr97
you could either:

Display the elements either side of the middle point, so use the same code you have but add this:
Code:

```int mid = 0 + x/2; int beforMid = mid - 1; int afterMid = mid +1;                         System.out.println("The Middle Elements are : " + a[beforeMid] + a[afterMid]);```
Or you can add the 2 "middle" values together and divide by 2:

Code:

``` int mid = 0 + x/2; int beforMid = mid - 1; int afterMid = mid +1; double m = (a[beforeMid]+a[afetrMid]) / 2             System.out.println("The average of middle elements is : " + m)[B][/B]```
up to you how you want to do it,

You could even just print an error message saying there is no exact middle value This isnt very user friendly though :D

• 05-13-2013, 08:52 AM
JosAH
Re: Working on the following problem !
That code is not correct; example: there are 6 (even) elements in your array; you should consider the elements 2 and 3 (not elements 2 and 4).

kind regards,

Jos
• 05-13-2013, 06:55 PM
monkeyjr97
Re: Working on the following problem !
Ah yes, i do apologize, rookie mistake to make. Sorry :(