6. (10 bonus pts): Write a function that returns the number of integer pairs fro
ID: 3715526 • Letter: 6
Question
6. (10 bonus pts): Write a function that returns the number of integer pairs from an array that sum to a specified number. The input array is sorted in ascending order and can have repeated numbers Your solution must use a single loop. Solutions with nested loops will not be counted. The function must have the following properties: (a) Name: CountPairs WithSum (b) Return type: int - number of pairs that satisfy the target sum. (c) Argument 1 Input type: Const pointer to the first integer in the sorted array. (d) Argument 2 Input type: Const pointer to the last integer in the sorted array. (e) Argument 3 - Input type: Const integer specifying the sum that the pair must satisfy. Examples: CountPairsWithSum(l-1,2,2,5,6), 4)2// (array[0], array 3), (array[1], array 2]) Count PairsWithSum([1,2,3,4, 5], 6) - 2 // (array[O] array4]), (array[1], array3]) Note that an index must not be used twice in a pair. For instance, a pair (array0 array0]) or (array[1], array]) are not valid, and thus not counted.Explanation / Answer
#include<iostream>
using namespace std;
//method that find the number of pairs..in the array
//with given sum
int CountParisWithSum(int *start,int *end,int sum)
{
//start : pointer to the starting of the array
//end : pointer to the ending of the array
//sum : sum to find the pairs
int n=0;//to count the number of pairs///
int m=0;
if(start>end)
m=1;
//using only single loop
while(start!=end)
{
if(end<start)break;
if(((*start)+(*end))==sum)
{
n++;//if such pair found
//then incrementing count
start++;
end--;
}
else if(((*start)+(*end))<sum)
{
start++;
}
else if(((*start)+(*end))>sum)
{
end--;
}
}
return n;//returnining number of paris..
}
int main()
{//testing..
int a[5]={-1,2,2,5,6},b[5]={1,2,3,4,5};
cout<<CountParisWithSum(a,&a[4],4)<<" "<<CountParisWithSum(b,&b[4],6)<<endl;
return 0;
}
output:
2 2
Process exited normally.
Press any key to continue . . .
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.