this is a c++ question ive been working on this problem but I can\'t get anywher
ID: 3679823 • Letter: T
Question
this is a c++ question ive been working on this problem but I can't get anywhere with it
keep in mind that i am still a beginner and its my first time working with arrays
I will give good rating if code is right
below is the function I wrote Im not sure I did it right can someone fix it and
I don't know how to test the code using assertions
#include <iostream>
using namespace std;
int search(int a[],int size, int k)
{ for (int i=0; i< size ; i++)
{
if (k==a[i])
{return i ;}
else return -1;
}
}
int main()
{
int a[6]={4,3,2,5,6,7};
int k = 0;
return 0;
}
Explanation / Answer
/*** c++ code to search element in an array ***********/
#include <iostream>
using namespace std;
int search(int a[],int size, int k)
{
for ( int i = 0; i < size ; i++)
{
if( a[i] == k) // searching k at index i
return i;
}
// if the program comes here without returning a value in loop
// that means we have no found k in the array so we will return -1
return -1;
}
int main()
{
int n;
cout <<"Give size of array: ";
cin >> n; // enter size of array
int a[n];
cout<< "Enter sleemts of array: "<< endl;
for (int i = 0; i < n; ++i)
{
cin >> a[i]; // enter elements of array
}
int k;
cout <<"Enter the element you want to search: ";
cin >> k; // enter element you want to search
int index = search(a,n,k); // calling the function and storing the return value in index
if(index == -1) cout<<"Element not present in array"<<endl;
else cout <<"Element present in array at index: "<<index<< endl;
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.