Wednesday, February 25, 2015

Pair of Numbers

C program to find presence of  pair of elements in array whose sum is equal to a given number.

#include<stdio.h>
int cmp(const void *a,const void *b)
{
return (*(int*)a-*(int*)b);
}
int main()
{
int n,i,x,j,flag=0;
printf("Enter the no. of elements in array:");
scanf("%d",&n);
int a[n];
printf("Enter the elements of array:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the sum of Numbers:"); 
scanf("%d",&x);
qsort(a,n,sizeof(int),cmp);
i=0;j=n-1;
while(i<j)
{
if((a[i]+a[j])==x)
{
flag=1;
break;
}
else if((a[i]+a[j])>x) j--;
else if((a[i]+a[j])<x) i++;
}
if(flag)
printf("\nPresent");
else
printf("\nNot Present");
return 0;
}

No comments: