# Thread: Working on the following problem !

1. Senior Member
Join Date
Nov 2011
Posts
165
Rep Power
9

## 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:

Java 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?

2. Senior Member
Join Date
Nov 2012
Posts
257
Rep Power
8

## 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:
Java 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:

Java 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

3. Senior Member
Join Date
Nov 2011
Posts
165
Rep Power
9

## Re: Working on the following problem !

I see. Thanks for your valuable input.
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:
Java 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:

Java 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

4. ## 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

5. Senior Member
Join Date
Nov 2012
Posts
257
Rep Power
8

## Re: Working on the following problem !

Ah yes, i do apologize, rookie mistake to make. Sorry :(

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•