Linear Search code

Sir, my code is giving runtime error i don’t know why.

#include
using namespace std;
// code for linear search
int main() {
int n;
int a[n];
int key;
int i;
cout << "Enter the number of elements: " << endl;
cin >> n;
cout << "Enter key element: " << endl;
cin >> key;
for(int i=0; i<n; i++)
{
cin >> a[i];
}

for(int i=0; i<n; i++)
{
    if(key==a[i])
    {
        cout << "Element found at index " << i << endl;
        break;
    }
    if(i==n)
    cout << "Element not found";
}

return 0;
}

@akankshaanand99 hey akanksha the problem is that with your code your array taking a garbage value that means declare array after the n so that runtime error is resolved and the another thing is that do not put statement like enter the number of the elements.

thanks! fixed the code!