In: Computer Science
C language only please
and please make a simple code
Write a function that will find whether there exist two integers that sum to the target integer. The function is to “return” three values.First, return “1” if the integers were found,return “-1” if your search was not successful.If you find two integers which add up to the target value, you should return their respective index position inside the array. Suggested prototype:int TwoSumFunction(int arr[], int size, int target, int*index1, int* index2);Inside TwoSumFunction:
•Pass the sorted array to the function. Set two pointers at the beginning and the end of thearray, then start moving the pointers inward while checking their sum. If it’s exactly the “target”, then we are done, and you can return 1. If it exceeds the “target”value, then any sum using the larger element is too large, so move the pointer corresponding to that element inward. If the sum is less than “target” value, then any sum using the lower element is too small, so move the pointer corresponding to that element inwards. If you are done with scanning the array and cannot find any two elements that sum up to “target” value, return -1.
#include<stdio.h>
int TwoSumFunction(int arr[], int size, int target, int*index1,
int* index2)
{
*index1 = 0;
*index2 = size-1;
while((*index1)<(*index2))
{
int sum =
arr[*index1]+arr[*index2];
if(sum==target)//means such pair found
return 1;
else
if(sum<target)
(*index1) =
(*index1 )+ 1;
else
(*index2) =
(*index2 )-1;
}
return 0;//if not found
}
int main()
{
int a[] ={1,2,3,4,5,6,7,8,9};
int t1 = 9;
int t2=22;
int l,r;
if(TwoSumFunction(a,9,t1,&l,&r))//if
found
printf("Such pair found: %d,%d\n",a[l],a[r]);
if(!TwoSumFunction(a,9,t2,&l,&r))//if not
found
printf("Not found\n");
return 0;
}
output:
Such pair found: 1,8
Not found
Process exited normally.
Press any key to continue . . .