Menu Close

Sum of array pairs equals given number in Java …FTC

Write a java program to find Pair of Integers in Array whose Sum is Given Number.

The Number of Inputs are as follows:
The first line denoted the number of inputs to be given by the user.

The second line denotes the input elements.

The Third Line denotes the number to find the sum of pair.

Input:
7
12 14 17 15 19 20 -11
33

Output:
14,19
import java.io.*;
import java.util.*;
public class temp {
  public static void main(String[] args){
    Scanner s=new Scanner(System.in);
    int arr[] = new int[100] ;
    System.out.println("Enter the size of array:  ");
    int n = s.nextInt();
    System.out.println("Enter the Elements of array:  ");
    for(int i=0;i<n;i++){
      arr[i]=s.nextInt();
    }
    System.out.println("Number to find find the sum of pair:  ");
    int sum=s.nextInt();
    System.out.println("Pairs: ");
    for (int i =  0; i <n; i++)
    {
      for (int j  = i+1; j <n; j++)
      {
        if(arr[i]+arr[j] ==sum)
        {
          System.out.println(arr[i]+","+arr[j]);
        }
      }
    }

  }
}

INPUT_1:
Enter the size of array:
7
Enter the Elements of array:
12  14  17  15  19  20  -15
Number to find find the sum of pair:
33

OUTPUT:
Pairs:
14,19


INPUT_2:
Enter the size of array:
5
Enter the Elements of array:
1  10  20  50  8
Number to find find the sum of pair:
60

OUTPUT:
Pairs:
10,50


INPUT_3:
Enter the size of array:
7
Enter the Elements of array:
1  20  9  0  8  1  11
Number to find find the sum of pair:
9

OUTPUT:
Pairs:
1,8
9,0
8,1


INPUT_4:
Enter the size of array:
10
Enter the Elements of array:
1  2  3  4  5  6  7  8  9  10
Number to find find the sum of pair:
6

OUTPUT:
Pairs:
1,5
2,4


INPUT_5:
Enter the size of array:
10
Enter the Elements of array:
1 2 3 4 5 6 7 8 9 10
Number to find find the sum of pair:
8

OUTPUT:
Pairs:
1,7 
2,6
3,5


INPUT_6:
Enter the size of array:
10
Enter the Elements of array:
10  9  7  6  8  5  5  2  3  1
Number to find find the sum of pair:
9

OUTPUT:
Pairs:
7,2
6,3
8,1


ILLUSTRATION

Executed using javac in ubuntu terminal

Leave a Reply

Your email address will not be published. Required fields are marked *