In: Computer Science
c++ please
2. Write and test a function search ( ) that searches for an integer s in an array of n elements. If s is found to match an element in the array, the function returns the address of that element; otherwise it returns NULL. The function must use the travelling pointer notation (version-1) to traverse the array. The function has the following prototype.
int* search ( int *p , int s, int n)
#include <iostream>
using namespace std;
int* search ( int *p , int s, int n){
//loop to iterate
for(int i=0;i<n;i++){
//checking if element is exist
//return address
if(*(p+i)==s)
return p+i;
}
//return NULL if the value does not exist
return NULL;
}
int main()
{
//declaring array of 6 elements
int arr[6];
int i,target;
//pointer to store result
int *r;
//reading 6 numbers from user
cout<<"Enter 6 numbers : ";
for(i=0;i<6;i++)
cin>>arr[i];
//reading target element
cout<<"Enter target element: ";
cin>>target;
//calling search to find the target element
r=search(arr,target,6);
//if return value is null than element not found
if(r==NULL){
cout<<"the element target not found";
}
else{
cout<<"Adress of element : "<<r;
}
return 0;
}
Note : If you like my answer please rate and help me it is very Imp for me