Answer to Question #198809 in C++ for adil

Question #198809

Take an unsorted array of size 15 and type int from the user and a number n, find if there exists a

pair of elements in the array whose difference is n.


1
Expert's answer
2021-05-26T06:23:52-0400
#include <iostream> 
#include <string>


using namespace std;




void sort(int numbers[],int size){
	for(int i=0;i<size;i++)
	{		
		for(int j=i+1;j<size;j++)
		{
			if(numbers[i]>numbers[j])
			{
				int temp  =numbers[i];
				numbers[i]=numbers[j];
				numbers[j]=temp;
			}
		}
	}
}


bool findPair(int numbers[],int size,int n){
	int i = 0, j = 1;
	while (i < size && j < size){
		if (i != j && numbers[j]-numbers[i] == n){
			cout<<"Pair Found: ( "<<numbers[i]<<", "<< numbers[j]<<" )\n";
			return true;
		}else if (numbers[j] - numbers[i] < n){
			j++;
		}else{
			i++;
		}
	}
	cout<<"No such pair";
	return false;
}


int main (){
	int numbers[100];
	int size;
	int n;


	cout<<"Enter the size of array: ";
	cin>>size;


	for(int i=0;i<size;i++){
		cout<<"Enter the value ["<<i<<"]: ";
		cin>>numbers[i];
	}
	cout<<"Enter n: ";
	cin>>n;


	sort(numbers,size);


	findPair(numbers,size,n);
	cout<<"\n\n";
	system("pause");
	return 0;
}









Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog