Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

find pair with given sum in the array

#include <stdio.h>

void findPair(int nums[], int n, int target)
{
    // consider each element except the last
    for (int i = 0; i < n - 1; i++)
    {
        // start from the i'th element until the last element
        for (int j = i + 1; j < n; j++)
        {
            // if the desired sum is found, print it
            if (nums[i] + nums[j] == target)
            {
                printf("Pair found (%d, %d)
", nums[i], nums[j]);
                return;
            }
        }
    }
    // we reach here if the pair is not found
    printf("Pair not found");
}
 
int main(void)
{
    int nums[] = { 8, 7, 2, 5, 3, 1 };
    int target = 10;
 
    int n = sizeof(nums)/sizeof(nums[0]);
 
    findPair(nums, n, target);
 
    return 0;
}
 
PREVIOUS NEXT
Tagged: #find #pair #sum #array
ADD COMMENT
Topic
Name
5+8 =