In this tutorial, we will write a program to find a pair of elements from an array whose sum equals a given number in java. Before that, you may go through the following topic in java.
Algorithm to check the pair of similar numbers present in an array whose sum is a given number
Step 1: Start
Step 2: Initiate new Array arr[]
Step 3: Declare n, value
Step 4: Take user input for:
n: number of elements in an array
arr: elements of an array
value: for the number to be checked
Step 5: Loop the entered array:
for 0 to n-1
for 0 to n
if(arr[i] + arr[j] == value)
print “arr[i] and arr[j]”
Step 6: Stop
How to Find all Pairs of Elements in an Array whose sum is equal to a given Number
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
int[] arr = new int[10];
int n, value;
Scanner sc = new Scanner(System.in);
System.out.print("How many elements: ");
n = sc.nextInt();
System.out.println("Enter the elements: ");
for (int i = 0; i < n; i++)
arr[i] = sc.nextInt();
//user input for the value to be checked
System.out.print("Enter the value to be checked: ");
value = sc.nextInt();
//Display the sum of pairs
System.out.println("The pairs are:");
for (int i = 0; i < (n - 1); i++)
for (int j = (i + 1); j < n; j++)
if (arr[i] + arr[j] == value)
System.out.println("Arr(" + arr[i] + ", " + arr[j] + ")");
}
}
Output:
How many elements: 5
Enter the elements:
1
2
5
3
4
Enter the value to be checked: 6
The pairs are:
Arr(1, 5)
Arr(2, 4)