In: Computer Science
1) Write a function searchValue that accepts an array of integers, the size of the array, and an integer. Find the last occurrence of the integer passed in as an input argument in the array. Return the index of the last occurrence of the value. If the value is not found, return a -1
2) Write the line of code to call the previous function assuming you have an array vec with length n, and are looking for the number 20, and want the index stored in an integer called idx.
C++ Coding. thank you!
C++ code:
#include <iostream>
using namespace std;
//1)
//initializing seachValue function
int seachValue(int vec[],int n,int num){
//initializing index to return as -1
int index=-1;
//looping from 0 to n
for(int i=0;i<n;i++){
//checking if the
current number in the list is the required number
if(vec[i]==num){
//assigning current value of i as index
index=i;
}
}
//returning index
return index;
}
int main()
{
//2)
//initializing vec array
int vec[] {10,20,30,40,50,20};
//initializing n as 6
int n=6;
//calling seachValue function and saving the
returned value to idx
int idx=seachValue(vec,n,20);
//printing idx
cout<<idx<<endl;
return 0;
}
Screenshot:
Output: