
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find All Pairs (A, B) in an Array Such That A - B = K in C++
Suppose we have an array A, from that array, we have to get all pairs (a, b) such that the a%b = k. Suppose the array is A = [2, 3, 4, 5, 7], and k = 3, then pairs are (7, 4), (3, 4), (3, 5), (3, 7).
To solve this, we will traverse the list and check whether the given condition is satisfying or not.
Example
#include <iostream> using namespace std; bool displayPairs(int arr[], int n, int k) { bool pairAvilable = true; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (arr[i] % arr[j] == k) { cout << "(" << arr[i] << ", "<< arr[j] << ")"<< " "; pairAvilable = true; } } } return pairAvilable; } int main() { int arr[] = { 2, 3, 4, 5, 6, 7 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; if (displayPairs(arr, n, k) == false) cout << "No paira found"; }
Output
(3, 4) (3, 5) (3, 6) (3, 7) (7, 4)
Advertisements