Linear Search - WA

Here, my code:
using namespace std;

int main(){
    int a,b,i;
    int array[a];
    cin >> a >> b >> i;
    for (i=1;i<a;i++){
        cin >> array[i];
    for (i=0;i<a;i++){
        if (array[i]==b){
            cout << i;
            cout << "-1";

Why is it showing WA? Someone please help.

Code : here

That doesn’t mean anything at all, so please, can you tell me how, in C++, you can input the values in a single line with spacing for an array?

I’ve uploaded the code.

Yeah sure, but is there a much simpler solution to this, by tweaking my code, despite me understanding your code?

your code is failing to print the last index of the desired number it it just printing all the occurance of M.

Oh okay, but is there any way we can change my code, by tweaking it?

In the input format in first line they have provided 2 value but you have scanned 3 value. In first for loop you have populated from index 1 . array[0] contains a gerabage value. Lastly check the output format there they asked you to print only one integer last occurrence of key .But you are printing for each index if that element present then that index else -1. So read the question and input output format carefully.

check the code
using namespace std;
int main()
    int n,m;
    int a[n] ;
    for(int i=0;i<n;i++)
    int i; 
    //travarse from last index as last occurance required
        if(a[i]==m) // m found so break it.
    // converting to 1 base indexing
1 Like

yeah correct, thanks !!!