Finding Pair of elements in C



Finding Pair of elements in C
Given an unsorted array and a number D,
write a program to find if there exists a pair of elements in the array whose difference is D.

Example:
Input: arr[] = {5, 20, 3, 2, 50, 80},
D = 78

Output: true Pair found is (2, 80) and the difference is 78.

Business Rules: Input Array must contain positive integer values only,
else display "Invalid Input".
The value of D should be greater than zero.
If negative, display "Invalid Input".
Display "No Such Pair" message on the screen if there is no pairs exist in the given input array

Function specification for C is the following.
Name:-findPair 
Return Type:- bool 
Parameter(s):- int *arr,int size,int d;

Image result for find pairs

Solution:


Alternative Solution when "d" can be negative digit also.
#include < stdio . h  >
#include < stdbool . h  >
// The function assumes that the array is sorted
bool findPair(int arr[], int size, int n)
{
// Initialize positions of two elements
int i = 0;
int j = 1;

// Search for a pair
while (i  <  size  & &  j  <  size )  
{
if (i != j && arr[j]-arr[i] == n)
{
printf("Pair Found: (%d, %d)", arr[i], arr[j]);
return true;
}
else if (arr[j]-arr[i] < n)
j++;
else
i++;
}

printf("No Such Pair");
return false;
}

// Driver program for testing above function
int main()
{
int arr[] = {1, 8, 30, 40, 100};
int size = sizeof(arr)/sizeof(arr[0]);
int n = 60;
findPair(arr, size, n);
return 0;
}


If you have a better solution, please let us know in comment box.
You can now request a solution by submitting your problem. We are please to help you.
                                                          Happy Learnings!!!

No comments