Find all pairs of number whose sum is equal to a given number in C++

This C++ program is able to find all the pairs of numbers in an array whose sum is equal to a specific number by using a nested loop and conditional statements. This problem is based on the application of array which is useful in many places. Following is a short and simple solution to the above task.

How to find all the pairs of number in an array whose sum is equal to a given number

Problem statement

There is an array of size n where n is the number of elements in it. Find all the pair of numbers whose sum is equal to a number given by the user.

  • The size of array is given by user.
  • Array elements cal be in any order.

Problem approach

  • Declare an array of size n.
  • Store the array elements as per the user input.
  • Take the input
  • Find the required pairs of numbers and print them on the screen.

Program/Source code

Following C++ program is able to find all the pair of numbers in an array whose sum is equal to a given number, is written and successfully compiled in CodeBlocks v16.01 .

/* C++ program to find the pairs of number present in array whose sum is equal to a given number**
 ***give different sizes for array & the their values to get different result***
 ** enter a valid number sum otherwise noting will print on screen **
 */
#include <iostream>

using namespace std;
int main()
{
    int size, num;
    cout<<"Enter the size of array: ";
    cin>>size;
    int array[size];                            // array declaration

    cout<<"Enter array elements: ";
    for(int i=0;i<size;i++)
        cin>>array[i];                          // input array values

    cout<<"Enter the number whose pairs are to be found: ";
    cin>>num;

    for(int i=0;i<size-1;i++){                  // nested for loop
        for(int j=i+1;j<size;j++){
            if(array[i]+array[j]==num)
                cout<<array[i]<<" and "<<array[j]<<endl;       // print pairs
        }
    }

    return 0;
}

Output Example

Enter the size of array: 8
Enter array elements: 5
6
4
1
5
3
9
8
Enter the number whose pairs are to be found: 9
5 and 4
6 and 3
4 and 5
1 and 8

Process returned 0 (0x0) execution time : 26.536 s
Press any key to continue.

Program explanation

  1. Initialize an array and store values in it.
  2. Take the number input from the user whose pairs are needed to find out.
  3. Use nested loop statements and conditional statements to find the pairs.
  4. Print the pairs on the screen.

Also read

Find nature of roots and actual roots of Quadratic equation in C++

Leave a Reply

Your email address will not be published. Required fields are marked *