Answer to Question #198053 in C++ for John

Question #198053

The objective of this activity is to demonstrate the linear search algorithm for arrays.

You are going to implement this as a function with the following defi nition:

string linSearch(double arr[10], double search[7]);

This function will represent the core functionality of your program. This function will

take two arrays as arguments, both of specified size. The first array will be the array that

should be searched. It will contain double values. The second array will represent a list

of values to search for in the rst array.

Your function will return a string, comma-delimited, which represents the indices of the

searched for elements in the array. The rst index in the string should correspond to the

rst element in the search array and so on. If the array is not found, it should show NA.

For example:

Consider the case of arr={1.1,1.2.1.3,1.4,1.5,1.6,1.7,1.8.1.9,1.11}

and search={1.3,2.1,1.11}

Then the return value of linSearch should be: 2,NA,9

The search array will be of size 7


1
Expert's answer
2021-05-24T16:52:48-0400
#include <bits/stdc++.h>
#include<sstream>
using namespace std;
string linSearch(double arr[10], double searchh[8])
{
    int i,j,f;
    string s="";
    for(i=0;i<8;i++)
    {
        f=0;
        for(j=0;j<10;j++)
        {
            if(arr[j]==searchh[i])
            {
                s=s+to_string(j)+",";
                f=1;
                break;
            }
        }
        if(f==0) s=s+"NA,";
    }
    return s.substr(0, s.size()-1);;
}
int main()
{
    fstream fio;
    double arr[10],searchh[8];
    string a,s;
    int j,k;
    fio.open("search.txt", ios::in);
    while(fio>>a>>s)
    {
        stringstream ss(a);
        j=0;
        while(ss.good())
        {
            string substr1;
            getline(ss, substr1, ',');
            arr[j]=stod(substr1);
            j++;
        }
        stringstream ss1(s);
        j=0;
        while(ss1.good())
        {
            string substr1;
            getline(ss1, substr1, ',');
            searchh[j]=stod(substr1);
            j++;
        }
        cout<<linSearch (arr,searchh) ;
     }
     fio.close();
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog