Find unique pairs such that each element is less than or equal to N in C++


In this tutorial, we are going to learn how to find the unique pairs that are less than the given number n.

Let's see the steps to solve the problem.

  • Initialize the number.

  • Iterate from i = 1 to i < n.

    • Iterate from j = i + 1 to j < n.

      • Print the (i, j).

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void uniquePairs(int n) {
   for (int i = 1; i < n; ++i) {
      for (int j = i + 1; j < n; j++) {
         cout << "(" << i << "," << j << ")" << endl;
      }
   }
}
int main() {
   int n = 5;
   uniquePairs(n);
   return 0;
}

Output

If you execute the above program, then you will get the following result.

(1,2)
(1,3)
(1,4)
(2,3)
(2,4)
(3,4)

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

Updated on: 29-Dec-2020

76 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements