Write a program to find index where sum are equal from both ends in Java

We are using an array of numbers and Printing both the index(start and end index position) where we find out that sum of numbers from both the ends are equal.

Code :
 public class FindEqualSum {  
      public static void main(String args[])  
      {  
           int a[]={4,4,6,7,4,3};  
           findIndex(a);  
      }  
      public static void findIndex(int[] a)  
      {  
           int startindex=0;  
           int endindex=a.length-1;  
           int startsum=0;  
           int endsum=0;  
           while (true) {  
                if (startsum > endsum) {  
                     endsum = endsum + a[endindex--];  
                } else {  
                     startsum = startsum + a[startindex++];  
                }  
                if(startindex > endindex)  
                {  
                     if (startsum == endsum) {  
                          System.out.println("Match found on Start Index:"+ startindex);  
                          System.out.println("Match found on End Index:"+ endindex);  
                          break;  
                     } else {  
                          System.out.println("no match found");  
                          break;  
                     }  
                }  
           }  
      }  
 }  
Output:
Match found on Start Index:3
Match found on End Index:2

No comments: