Search code examples
c++arrayslinear-search

C++ Linear search returning just 0


So I am a newbie in C++, I do code in JS, for some reason I can't figure out the mistake here, please help me out. thanks!

#include <iostream>

using namespace std;

int search(char input, char sentence[]){
    for(int i = 2; i != '\0'; i++){
        if(sentence[i] == input){
            return i;        

        }else{ return -1; }
    }
}

int main()
{
    char key[20] = "hey my name is sid!";
    char ser = 'm';
   cout << search(ser,key);
    return 0;
}

Solution

  • Your condition in the for loop is wrong, you are not checking the string only the index. Also if your character did not match, you do not want to exit immediately.

    The correct code would be:

    for(int i = 0; sentence[i] != '\0'; i++)
    {
        if(sentence[i] == input)
        {
            return i;        
        }
    }
    return -1;
    

    If you want to start the search at the third character you should first ensure that your string has at least three elements:

    if(strlen(sentence)>=3)
    {
        for(int i = 2; sentence[i] != '\0'; i++)
        {
            ...
        }
        ...
    }