Linear Search Array

View Image

Solution

In this tutorial, we will learn how to implement a Linear Search Data Structure in C++ using some of the OOP concepts such as Classes, Methods, and also making instances (objects).
This will enable us to interact with our program via the Command-Line of the IDE to run and play around with our code sample.

What we can do with this code snippet:

  • We can insert the number of items we want to add into our Linear Search Array
  • We can insert the list of items(in this case numbers)
  • We can  search for the position of a particular number that has already been inserted by the user
  • We will be prompted whether or not we want to add more items or end the program

Code Snippet Below:

class LinearSearch{
public:
    void LinearSearchMenu(){
        cout << "You are now in the Linear Search Function" << endl;
        Linearsearch();
    }
    void Linearsearch(){
    int n,x,i,flag=0;
    cout<<"How many elements?";
    cin>>n;
    int a[n], listitems[n];
    for(i=0;i<n; i++){
        cout<<"\nEnter elements of the array at position: " << i+1 << "\n";
        cin>>a[i];
        listitems[i] = a[i];
    }
    cout << "here is your list of items: ";
    for(i=0; i<n; i++){
        cout <<listitems[i] <<" ";
    }

    cout<<"\nEnter element to search:";
    cin>>x;

    for(i=0;i<n; i++)
    {
        if(a[i]==x)
        {
            flag=1;
            break;
        }
    }

    if(flag)
        cout<<"\nElement is found at position "<<i+1;
    string userinput;
    cout << "\nDo you want to continue?\nEnter 1 to Continue\nPress anything to exit\n";
    cin >> userinput;
    if(userinput == "1"){
        Linearsearch();
    }
    else if (userinput != "1"){
        exit(0);
    }

    else{
            cout<<"\nElement not found" <<endl;;;;;;;;;
        Linearsearch();
    }

}
};

 

CSC305 Exam Focus/Materials 3/31/2021 Seth 0 Answer(s) 793 views



Author

Seth 1413

Leave a reply

Post your answer

Answers ( 0 )