+ 1

# invalid types 'int[int]' for array subscript

can someone help i can't figure out the probleam. you will understand what i am trying to do by these steps 1> take size of array as input 2>tale numbers of arrays 3>take int key as input 4>create a function then use a for loop to check if key and array a number is same. #include <iostream> int linear(int n , int arr , int key) { for (int i = 0; i < n; i++) { if (key==arr[i]) { std::cout <<i; } else{ return -1; } } } int main() { int n; std::cin>>n; int arr[n]; for (int i = 0;i<n;i++) { std::cin>>arr[i]; } int key ; std::cin >> key ; std::cout << linear(n , arr , key); return 0; } i am getting two errors 1> mention on question 2> invalid conversion from int to int .

4 Answers

+ 3

firstly variable length arrays (VLA) like <int arr[n];> is not a standard C++ feature.
however C++ offers many standard-library facilities (see std::vector or std::array) that makes programmer life easier in cases like this compared to the built-in array intrinsic low-level concepts.
std::vector -> https://en.cppreference.com/w/cpp/container/vector
std::array -> https://en.cppreference.com/w/cpp/container/array
secondly the function declaration is incorrect. the second parameter is declared as having the type int and you are using it as an array.
int linear(int n, int arr, int key)
you need to declare the function the following way
int linear(int n, int arr[], int key)
or equivalently
int linear(int n, int*arr, int key)
and thirdly has already answered by @lpang.

+ 4

So here we try to find and return first presence of <key> in <arr>. But why the return value was 2 or -1? If you meant to return -1 when <key> isn't present in <arr>, then you should do so once the loop completed; with no match found.

+ 3

thanks string x,
both of your answers have been very helpful.

+ 1

got it ! sir, sorry for any misconduct i might have made.