ADS

Check Sum Of Two Numbers To Sasaran In Array

In this i'll be discussing about checking whether any 2 numbers in an array can add up to give a target number. For this, i have written a method which returns an ArrayList<String> which contains the expression that the two numbers can sum up to give the target. The logic is very simple that we need to check every element whether it can sum up with the every other element in the array. Now all those elements which can be summed to the sasaran are added to the ArrayList. See how it works.

 import java.util.*;
class TwoCanSum
{
public static void main(String args[])
{

// Create Scanner object
Scanner s=new Scanner(System.in);

// Take no.of elements
System.out.println("Enter the no.of elements");
int n=s.nextInt();

// Create an array of size n
int[] a=new int[n];

// Read the array
System.out.println("Enter the elements");
for(int i=0;i<n;i++)
{
a[i]=s.nextInt();
}

// Enter the sasaran number
System.out.println("Enter the sasaran number");
int target=s.nextInt();

// Check whether any two can sum
ArrayList<String> list=canSum(a,target);

// Get the size, don't call in loop
int size=list.size();

// Print the elements
for(int i=0;i<size;i++)
{
System.out.println(list.get(i));
}


}

public static ArrayList<String> canSum(int[] a,int target)
{
ArrayList<String> list=new ArrayList<String>();

for(int i=0;i<a.length;i++)
{
for(int j=i+1;j<a.length;j++)
{
if(a[i]+a[j]==target) list.add(a[i]+"+"+a[j]+"= "+target);
}
}
return list;
}
}

Sample output of the program

 Enter the no.of elements
5
Enter the elements
9
6
7
2
8
Enter the sasaran number
15
9+6= 15
7+8= 15

Explaining the logic of TwoCanSum

ArrayList<String> list=new ArrayList<String>(); Create an ArrayList<String>.

for(int i=0;i<a.length;i++) Loop a.length times where a is the array given as parameter. This loop gets the element at i.

for(int j=i+1;j<a.length;j++) The value of j will be i+1 and this loop is rotated until j equals a.length. When j equals length of the array, the loop breaks. This loop gets every element other than the element at i.

if(a[i]+a[j]==target) Check whether the element at index i and the element at index j sum up to give the sasaran number. Enter the if block if this condition is satisfied else skip if-block.

list.add(a[i]+"+"+a[j]+"= "+target); Add the string which contains the value of the elements which can be summed to the sasaran along with the sasaran number preceded by an =.

Consider 5 elements, then the elements are checked for sum like,

a[0] checked with a[1],a[2],a[3],a[4]
a[1] checked with a[2],a[3],a[4]
......

return list; Returns the array list.

In this way, we can check whether two elements in an array can be summed to give the sasaran number.

Subscribe to receive free email updates:

ADS