in C; 6. (10 bonus pts): Write a function that returns the number of integer pai
ID: 3713742 • Letter: I
Question
in C;
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: CountPairsWithSum (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(-1,2, 2,5,6], 4)-2 // (array(0, array[3), (array[1], array 2)Explanation / Answer
Hi Dear,
Please find my implementation in C.
#include <stdio.h>
// Returns number of pairs in arr[0..n-1] with sum equal
// to 'sum'
int CountPairsWithSum(int arr[], int n, int sum)
{
int count = 0; // Initialize result
int i, j;
// Consider all possible pairs and check their sums
for (i=0; i<n; i++)
for (j=i+1; j<n; j++)
if (arr[i]+arr[j] == sum)
count++;
return count;
}
// Driver function to test the above function
int main()
{
int arr[] = {1, 5, 7, -1, 5} ;
int n = 5;
int sum = 6;
printf("Count of pairs is %d ", CountPairsWithSum(arr, n, sum));
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.