Program-To find find all pairs of elements from an array whose sum is equal to given number
- class SumIsEqualTo
- {
- public static void main(String args[])
- {
- int array[]={18,4,6,12,20,16};
- sumEquals(array,22);
- }
- public static void sumEquals(int arr[],int X)
- {
- if(arr.length<2)
- return;
- System.out.println("the set or pairs of number whose sum is equals to 22 are :");
- for(int i=0;i<arr.length;i++)
- {
- for(int j=1+i;j<arr.length;j++)
- {
- int temp=arr[i] + arr[j];
- if(temp==X)
- {
- System.out.println(arr[i] +","+arr[j]);
- }
- }
- }
- }
- }
For example:
Given a array,we need to find all pairs whose sum is equal to number X (In above program X=22)
- array[]={18,4,6,12,20,16};
- Pair of elements whose sum is equal to 22 : 18, 4 and 6,16.
No comments:
Post a Comment