Java Array program to find array elements with given sum

The java array program receives the list of unsorted array elements and sum value as input to the program. The array elements will be traversed and adds the sum of array elements at respective array index to compare if that equals to the sum value received as an input. If value matches at array index, the program will print the indexes else print “Array Element Pair not found”

Example:

    int[] ArrayObjList = { 2, 8, 4, 6, 12, 17 };
    int ArrayTotal = 20;

Here , the index 1 and index 4 sum is equal to the given sum.

package core.java.oracleappshelp.array;
public class ArrayPairSumEqualToArraySum {
		private static void findPair(int[] ArrayWithAllElements, int sum) {
		{
			// Traverse for Array Object till Array length -1
			for (int outerLoop = 0; outerLoop < ArrayWithAllElements.length - 1; outerLoop++)
			{
				// Traverse for the InnerLoop till last element
				for (int innerLoop = outerLoop + 1; innerLoop < ArrayWithAllElements.length; innerLoop++)
				{
					// check if the 2 compared elements sum is equal to the Array Sum
					if (ArrayWithAllElements[outerLoop] + ArrayWithAllElements[innerLoop] == sum)
					{
						System.out.println("Element Pair found at index " + innerLoop + " and " + outerLoop);
						return;
					}
				}
			}
			// When no array element is qualified 
			System.out.println("Array Element Pair not found");
		}
		}
		public static void main (String[] args){
			int[] ArrayObjList = { 2, 8, 4, 6, 12, 17 };
			int ArrayTotal = 20;
			findPair(ArrayObjList, ArrayTotal);
		}
	}
Array Program Output: 
Element Pair found at index 4 and 1    
Java Array program to find array elements with given sum
Scroll to top
Copy Protected by Chetan's WP-Copyprotect.