print an index where sum of numbers from Starting index to any index in an array

in an array sum of numbers from Starting index to any index in an array to rest of the index in an array
SOURCE : FibonaciSeries.java


public class FindMiddleIndex {

public static int findMiddleIndex(int[] numbers) throws Exception {

int endIndex = numbers.length - 1;
int startIndex = 0;
int sumLeft = 0;
int sumRight = 0;
while (true) {
if (sumLeft > sumRight) {
sumRight += numbers[endIndex--];
} else {
sumLeft += numbers[startIndex++];
}
if (startIndex > endIndex) {
if (sumLeft == sumRight) {
break;
} else {
throw new Exception(
"Please pass proper array to match the requirement");
}
}
}
return endIndex;
}

public static void main(String a[]) {
int[] num = { 2, 4, 4, 5, 4, 1 };
try {
System.out
.println("Starting from index 0, adding numbers till index "
+ findMiddleIndex(num) + " and");
System.out.println("adding rest of the numbers can be equal");
} catch (Exception ex) {
// System.out.println(ex.getMessage());
}
}
}



INPUT

int[] num = { 2, 4, 4, 5, 4, 1 }



OUTPUT

Starting from index 0, adding numbers till index 2 and
adding rest of the numbers can be equal







Sandeep Kumar D

Hi, I have written and developed this post so that most of people will be benefited. I'm committed to provide easy and in-depth tutorials on various technologies.I hope it will help you a lot.

- Sandeep Kumar D

Follow Me @Google+




SHARE

    Blogger Comment
    Facebook Comment

0 comments :

Post a Comment