Thứ Hai, 25 tháng 8, 2014

Java program to find sum of pairs of an array.

You have given an array of some elements  say{a1,a2,a3,.......,an}.and you also given a sum to check 'k' .Now you need to find pairs like (a1,a2,....,an)is equal to k
Example:

int arr[]={0,1,2,3,4,5,6}; and sum is 5;
solution is :
pairs are(1,4)   ,(2,3) , (0,5)

----------------------------------------------------------------------------------
Here is the solution for above problem in JAVA.



package logics;


public class sumArray
{
    public static void main(String []ar)
    {
        sumArray m=new sumArray();
        int data[]=new int[]{0,1,2,3,4,5,6};
        m.checkSum(data,5);
      
    }
   

public void checkSum(int a[],int num)
{

    System.out.print("pairs are \n");
    for(int i=0;i<a.length;i++)
    {
        int first=a[i];
        for(int j=i+1;j<a.length;j++)
        {
            int second=a[j];
            int sum=first+second;
            if(sum==num)
            {
                System.out.printf("(%d,%d)\n",first, second);
            }
        }
    }
   
}
}//class


output:
----------------
pairs are
(0,5)
(1,4)
(2,3)
 

Không có nhận xét nào:

Đăng nhận xét