Advertisement
zoltanvi

Middle index finder

May 23rd, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.13 KB | None | 0 0
  1. // Program: Find out middle index where sum of both ends are equal.
  2. //
  3. // Description:
  4. // You are given an array of numbers. Find out the array index or position
  5. // where sum of numbers preceeding the index is equals to sum of numbers
  6. // succeeding the index.
  7.  
  8.  
  9.  public class JavaFiddle
  10.   {
  11.      
  12.     public static void main(String[] args)
  13.     {
  14.         JavaFiddle jf = new JavaFiddle();
  15.         int[] numbers = {1, 2, 10, 4, 1, 5, 6, 5, 1, 10, 6, 3, 2, 6, 1, 9, 3, 7, 5, 8, 2, 10, 4, 5, 1, 0, 1, 3, 5, 7, 9, 3, 2};  
  16.        
  17.         jf.index(numbers);
  18.     }
  19.    
  20.     private void index(int[] array){
  21.         int leftsum;
  22.         int rightsum;
  23.         for(int i = 1; i < array.length; i++){
  24.             leftsum = 0;
  25.             rightsum = 0;
  26.             for(int l = 0; l < i; l++){
  27.                 leftsum += array[l];
  28.             }
  29.            
  30.             for(int r = array.length-1; r > i; r--){
  31.                 rightsum += array[r];
  32.             }
  33.            
  34.             if(leftsum == rightsum){
  35.                 System.out.println("The index: " + i);
  36.             }
  37.            
  38.         }
  39.        
  40.     }
  41.    
  42.   }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement