# [Solved] Program to Find Pairs that have Desired Sum in Java

**Problem Statement:** Consider an array of integers that may contain both positive and negative integers, called numbers. Write a program that finds all the pairs of integers whose sum is equal to a given value called the desired sum.

This question has been asked in interviews of many product-based companies like Amazon, Flipkart, Adobe, …

### Java Program

**Prerequisite:**

- Understanding of generics in Java
- Understanding of ArrayLists in Java
- Knowledge of classes and objects in Java

**Code:**

Let’s write a program to find pairs that have desired sum in Java.

import java.util.*; class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); // Enter the size of the array int n = sc.nextInt(); int[] = arr = new int[n]; for (int i = 0;i < arr.lenght;i++) { arr[i] = sc.nextInt(); } // enter the desired sum int sum = sc.nextInt(); System.out.println(findNumberOfPairs(arr, sum)); } public static int fndNumberOfPairs(int[] arr, int sum) { Arrays.sort(arr); // sort the array // using two pointer algorithm int left = 0, right = arr.lenght - 1, count = 0; currentSum = arr[left] + arr[right]; while (left < right) { if (currentSum == sum) { count ++; left++; right--; } else if (currentSum < sum) left++; else right--; } return count; } }

**Output:**

Sample Input :n = 5, arr = [1, 2, 3, 4, 5], sum = 4Sample Output :1 as only (1, 3) pair has the sum equal to 4

You can use any programming language (C/C++, Python, etc.) of your choice to solve this competitive coding challenge to find pairs that have desired sum.

## Comments

## parth

currentSum = arr[left] + arr[right]; this line should be inside the while loop.