In: Computer Science
In this task you will implement a C++ function with arguments: a sorted integer array, size of the array, and a target integer value. Find all combinations of two elements in the sorted array which sum up to the target value. When found, add the combinations into an array, and print it. Where there is greater than one combination, you may use the number 200 as a separator for the combinations in the output array. Do not use more than one loop. Use pointer notation of arrays to do this question.
Function for your combinations is provided below. As you have asked it uses pointers for traversing array passed in function. The whole code is explained in the code comments. I have tested the function and it runs smoothly. For your better understanding i have a made main method also in the last part of answer, and tested this function. i have attached the screenshot of test in the last.
#################################################################################
FUNCTION DEFINITION:--
//function taking 3 parameters void combinationFinder(int a[],int length,int target) { int combination[length]; //array of combination int c=0; //iterator for array for(int i=0;i<length;i++) //for each element { for(int j=i+1;j<length;j++) //check with all the rest elements { if((*(a+i)+*(a+j))==target) //if sum is equal to target { if(c==0) //if array is empty { combination[c++]=*(a+i); //add first no combination[c++]=*(a+j); //add second no } else //if array is not empty { combination[c++]=200; //add 200 as separator combination[c++]=*(a+i); //add first no combination[c++]=*(a+j); //add second no } } } } if(c>0) //if there are elemnts in array { for(int i=0;i<c;i++) cout<<" "<<combination[i]; //print each elemnt } }
##############################################################################
WHOLE CODE WITH TESTING AND OUTPUT
#include <iostream> using namespace std; //function taking 3 parameters void combinationFinder(int a[],int length,int target) { int combination[length]; //array of combination int c=0; //iterator for array for(int i=0;i<length;i++) //for each element { for(int j=i+1;j<length;j++) //check with all the rest elements { if((*(a+i)+*(a+j))==target) //if sum is equal to target { if(c==0) //if array is empty { combination[c++]=*(a+i); //add first no combination[c++]=*(a+j); //add second no } else //if array is not empty { combination[c++]=200; //add 200 as separator combination[c++]=*(a+i); //add first no combination[c++]=*(a+j); //add second no } } } } if(c>0) //if there are elemnts in array { for(int i=0;i<c;i++) cout<<" "<<combination[i]; //print each elemnt } } int main() { int a[]={-1,1,2,3,4,5,6,7,8,9,10}; //array declaration combinationFinder(a,11,8); //calling function for target 8 return 0; }