TwoSum Example in C#: Print and Count Pairs with Given Sum

Given an array of integers and target number ‘target sum' then print all pairs and their count in the array whose sum is equal to ‘target sum’.

Example

Input: arr[] = { 3, 5, 7, 1, 5, 9 }
               target = 10

Output: (3,7)   (5,5)   (1, 9)
               Count: 3

public void TwoSum(int[] arr, int target)
{
  int count = 0;
  for (int i=0; i<arr.Length; i++)
  {
   for(int j=i+1; j<arr.Length; j++)
    {
     if ((arr[i] + arr[j]) == target)
     {
        // For print Pairs
        Console.WriteLine("(" + arr[i] + "," + arr[j]+")");    

  
        // For print Count of pairs
        count++;   
     }   
   } 
  }
Console.WriteLine("Count of Pairs : " + count);
}

public static void Main(String[] args)
{
    int[] arr = new int[] { 3, 5, 7, 1, 5, 9 };

    int target = 10;

    TwoSum(arr, target);
}

Output

Output


Similar Articles