Program Discussion :: Basics
102 / 279
Given a sorted array and an item k, write a program to get a pair of items whose subtraction equal to K.
Answer:
#include
#include
using namespace std;
/* 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
Asked In ::
Language:
Nandy
7 Jul, 2017 9:30 AM
#include <stdio.h>
#include <stdbool.h>
#define TRUE 1
#define FALSE 0
/* 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 to test 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;
}
Language:
Aarav
7 Jul, 2017 9:30 AM
#include <stdio.h>
#include<iostream>
using namespace std;
/* 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)
{
cout<<"Pair Found: "<< arr[i]<<"and"<< arr[j];
return true;
}
else if (arr[j]-arr[i] < n)
j++;
else
i++;
}
cout<<"No such pair";
return false;
}
/* Driver program to test 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;
}