- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to find all pairs of elements in Java array whose sum is equal to a given number?
To find all pairs of elements in Java array whose sum is equal to a given number −
- Add each element in the array to all the remaining elements (except itself).
- Verify if the sum is equal to the required number.
- If true, print their indices.
Example
import java.util.Arrays; import java.util.Scanner; public class sample { public static void main(String args[]){ //Reading the array from the user Scanner sc = new Scanner(System.in); System.out.println("Enter the size of the array that is to be created: "); int size = sc.nextInt(); int[] myArray = new int[size]; System.out.println("Enter the elements of the array: "); for(int i=0; i<size; i++){ myArray[i] = sc.nextInt(); } //Reading the number System.out.println("Enter the number: "); int num = sc.nextInt(); System.out.println("The array created is: "+Arrays.toString(myArray)); System.out.println("indices of the elements whose sum is: "+num); for(int i=0; i<myArray.length; i++){ for (int j=i; j<myArray.length; j++){ if((myArray[i]+myArray[j])== num && i!=j){ System.out.println(i+", "+j); } } } } }
Output
Enter the size of the array that is to be created: 8 Enter the elements of the array: 15 12 4 16 9 8 24 0 Enter the number: 24 The array created is: [15, 12, 4, 16, 9, 8, 24, 0] indices of the elements whose sum is: 24 0, 4 3, 5 6, 7
Advertisements