In: Computer Science
In Java, a set of integers is given. write a function to find 2 integers in this set that sums upto a target value.
i.e [1,5,2,0,11,3] target = 7
result [5,2]
i.e [1,5,4,0,14,-7] target = 9
result [5,4]
NOTE: THE SAME INTEGER CANNOT BE USED TWICE !!!
Code:
import java.lang.*;
import java.util.*;
public class sum{
   public static void main(String[]args){
       ArrayList<Integer> list=new
ArrayList<Integer>();
       System.out.println("Enter length of
the list");
       Scanner s= new
Scanner(System.in);
       int i=s.nextInt();
       while(i!=list.size()){
          
System.out.println("Enter a number: ");
           int
input=s.nextInt();
          
list.add(input);
       }
      
       System.out.println("Enter target
number: ");
       int target=s.nextInt();//take input
and store in target
       for (int
a=0;a<list.size()-1;a++){
           for (int
b=a+1;b<list.size();b++){
          
    if (list.get(a)+list.get(b)==target &&
list.get(a)!=list.get(b)){
          
        System.out.println("result
["+list.get(a)+","+list.get(b)+"]");
          
    }
           }
       }
   }
}
Code in the image:

Output:

