Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

Java Array Exercises: Find all Pairs of elements in an array whose sum is equal to a specified number

Java Array: Exercise-22 with Solution

Write a Java program to find all pairs of elements in an array whose sum is equal to a specified number.

Pictorial Presentation:

Java Array Exercises: Pairs of elements in an array whose sum is equal to a specified number

Sample Solution:

Java Code :

public class Exercise22 {
static void  pairs_value(int inputArray[], int inputNumber)
  {
  System.out.println("Pairs of elements and their sum : ");
 
  for (int i =  0; i < inputArray.length; i++)
  {
  for (int j  = i+1; j < inputArray.length; j++)
  {
  if(inputArray[i]+inputArray[j] == inputNumber)
  {
  System.out.println(inputArray[i]+" + "+inputArray[j]+" =  "+inputNumber);
  }
  }
  }
  }
  
  public static void  main(String[] args)
  {
  pairs_value(new int[] {2, 7, 4, -5, 11, 5, 20}, 15);
  
  pairs_value(new int[] {14, -15, 9, 16, 25, 45, 12, 8}, 30);
  
  }
}

Sample Output:

Pairs of elements and their sum :                                                                             
4 + 11 = 15                                                                                                
-5 + 20 = 15                                                                                                
Pairs of elements and their sum :                                                                             
14 + 16 = 30                                                                                                
-15 + 45 = 30 

Flowchart:

Flowchart: Java exercises: Find all pairs of elements in an array whose sum is equal to a specified number

Visualize Java code execution (Python Tutor):

Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to convert an ArrayList to an array.
Next: Write a Java program to test the equality of two arrays.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Java: Tips of the Day

How to sort an ArrayList?

Collections.sort(testList);
Collections.reverse(testList);

That will do what you want. Remember to import Collections though!

Ref: https://bit.ly/32urdSe