Question:
Given an input array, find the distinct pairs of elements whose sum equals to a given number
ie arr[i]+arr[j]=sum (i!=j)
Input:
9
1 2 3 4 5 6 7 8 9
10
Output:
Found at indices 0 8 with values (1,9).
Found at indices 1 7 with values (2,8).
Found at indices 2 6 with values (3,7).
Found at indices 3 5 with values (4,6).
Total pairs :4
Explanation:
Starting from the first element , add the elements that are next(to right of) to it.
If the sum equals to required number, increase the count and print them.
If no pairs are found, then the count remains zero.
In the above example:
1+9=10 Count=1
2+8=10 Count=2
3+7=10 Count=3
4+6=10 Count=4
Code:
#include<stdio.h>
int main()
{
int n,sum;//size of array,sum
scanf("%d",&n);
int a[n],count=0,i,j;
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
scanf("%d",&sum);
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]+a[j] == sum)
{
count++;
printf("Found at indices %d %d with values (%d,%d).\n",i,j,a[i],a[j]);
}
}
}
if(count==0)
{
printf("No such pair was found\n.");
}
else
{
printf("Total pairs :%d\n",count);
}
return 0;
}
No comments:
Post a Comment