Java Program to Find Two Elements whose Sum is Equal to a Given Number
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This is the Java Program to Find Two Elements whose Sum is Equal to a Given Number.
Given an array of n integers and a value, say m. Find out the pairs of elements from the array, whose sum values m.
Example:
Array = [ 1, 2, 4, 5, 8, 10, 11] m = 13
Output :
{8, 5}
{11, 2}
Iterate through the array and in a temporary variable, say x, store the difference of the current array element and the value m. Search for value x, in the map, if x is present in the map, then the pair of elements x and the current array element, sums to m, else store x in the map.
Here is the source code of the Java Program to Find Two Elements whose Sum is Equal to a Given Number. The program is successfully compiled and tested using IDE IntelliJ Idea in Windows 7. The program output is also shown below.
//Java Program to Find Two Elements whose Sum is Equal to a Given Number.
// Function to print the pair of elements having a given sum
{
}
else
{
}
}
}
// Main function to read the input
}
{
}
}
{
i--;
}
}
}
{
}
}
}
1. In function printPairs(), firstly a hashmap is created HashMap<integer,integer> obj=new HashMap<>().
2. The loop for(i=0; i<array.length; i++), sets the value search to sum – array[i] in each iteration.
3. The condition if(obj.containsValue(search)) looks for the variable search in the hashmap.
4. If it is present, then the present element and the element search has the given sum in the array.
5. Otherwise, the value search is added to the hashmap.</integer,integer>