Find Pairs in Array with given Sum in C

Find Pairs in Array with given Sum in C Language

 

In this page we will look into a coding question where we will learn how to Find Pairs in Array with given sum in C Programing Language.
There might be different approach to solve this question, one you will find here. If your approach is bit different post it onto the comment section.

Pairs in Array with Sum

Problem Statement

Write a Program in C Programming Language where you need to find the pairs in Array with given sum.

Input Format
    -First line contains the value of n that is the total number of elements in the array
    -Second line contains the elements of array
    -Third line contains the Sum to be checked.

Output Format
    -Output contains as many lines as number of pairs with each pair written in each line
    -Last line of output contains the total count of pairs.

Find Pairs in Array with given Sum in C

Sample Test Case : 1

Input
7
5 2 3 4 1 6 7
7

Output
[5 2]
[3 4]
[1 6]
Total Number of Pairs : 3

Sample Test Case : 2

Input
99
10 15 20 25 30 35 40 45 50
50

Output
[10 40]
[15 35]
[20 30]
Total Number of Pairs : 3

Code in C Programming Language

#include <stdio.h>
int main()
{
    int n;
    scanf("%d",&n);
    int array[n];
    int check;
    int sumcount = 0;
    for(int i=0i<ni++)
    {
        scanf("%d",&array[i]);
    }
    scanf("%d",&check);
    for(int i=0i<ni++)
    {
        for(int j=i+1j<nj++)
        {
            sum = array[i] + array[j];
            if(sum == check)
            {
                printf("[%d %d]\n",array[i],array[j]);
                count ++;
            }
        }
    }
    printf("Total Number of Pairs : %d",count);
    return 0;
}

Learn About Arrays in C

Click on the below button to learn about in C Programming Language

Learn Arrays in C

Learn Data Structures

Click on the below button to study more Data Structure

Learn Data Structures