Tuesday, 24 January 2017

Program-To find find all pairs of  elements from an array whose sum is equal to given number  


  1. class SumIsEqualTo
  2. {
  3. public static void main(String args[])
  4. {
  5. int array[]={18,4,6,12,20,16};

  6. sumEquals(array,22);
  7. }
  8. public static  void sumEquals(int arr[],int X)
  9. {
  10. if(arr.length<2)
  11.     return;

  12.    System.out.println("the set or pairs of number whose sum is equals to 22 are :");

  13. for(int i=0;i<arr.length;i++)
  14. {
  15. for(int j=1+i;j<arr.length;j++)
  16. {
  17. int temp=arr[i] + arr[j];
  18. if(temp==X)
  19. {
  20. System.out.println(arr[i] +","+arr[j]);
  21. }
  22. }
  23. }
  24. }
  25. }    

     For example:

                                            Given a  array,we need to find all pairs whose sum is equal to number X (In           above program X=22)                         
  1. array[]={18,4,6,12,20,16};
  2. Pair of elements whose sum is equal to 22 :  18, 4 and 6,16.
     

No comments:

Post a Comment