
Posted On: Feb 22, 2018
Basic method to find a pair whose sum matches with given sum:
C program:
#include <iostream>
#include <algorithm>
// Function to find a pair using Sorting in an array with given sum
void findPair(int arr[], int n, int sum){
std::sort(arr, arr + n); // sort the array in ascending order
int i = 0;
int j = n - 1;
while (i < j) { // loop till i is less than j
if (arr[i] + arr[j] == sum){ // sum found
std::cout << "Pair found"<<”\n”<< arr[i]<<arr[j];
return;}
// decrement j if total is more than the sum
// increment i if total is less than the sum
(arr[i] + arr[j] < sum)? i++: j--;}
// No pair exists in an array with the desired sum
std::cout << "Pair not found";}
// Main function from which find pair function is called
int main()
{ int arr[] = { 8, 7, 2, 5, 3, 1};
int sum = 10;
int n = sizeof(arr)/sizeof(arr[0]);
findPair(arr, n, sum);
return 0;}
Never Miss an Articles from us.
There is a number of ways to reverse a string in programming. Here we going to see how to reverse a string in C language. Note: Below programs are written in C language. It takes a string a...