In: Computer Science
Please use Java eclipse
Find pair in an array with given sum
Given an array of integers A and an integer S, determines whether there exist two elements in the array whose sum is exactly equal to S or not.
Display 1 a pair is found in an array with matching sum S else 0.
Input
6
5
1 -2 3 8 7
Where,
Output
1
For the given array, A[1] + A[3] = -2 + 8 = 6 which is equal to the given number S=6
Java Program: Change the class name as per your convenient
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Sum S : ");
int S = sc.nextInt();
System.out.print("Enter Size of Array : ");
int N = sc.nextInt();
System.out.print("Enter Elements of Array : ");
int A[] = new int[N];
for (int i=0; i<N; i++)
{
A[i] = sc.nextInt();
}
int flag = 0;
for (int i=0; i<N; i++)
{
for (int j=i+1; j<N; j++)
{
if((A[i] + A[j]) == S)
{
flag = 1;
}
}
}
if (flag == 1)
{
System.out.println("Your Output : 1");
}
else{
System.out.println("Your Output : 0");
}
}
}
Output:
Thumbs Up Please !!!