The sequential search algorithm searches a list for a given item, starting with
ID: 3703510 • Letter: T
Question
The sequential search algorithm searches a list for a given item, starting with the first element in the list. It continues to compare the search item with the other elements in the list until either the item is found or the list has no more elements left to be compared with the search item. Implement a program that search for a value that is entered by the user in an array. The program should print a success message and tell the user the location of the value in the array in case it finds that value. Otherwise, should state that the value does not exist in the array. Then, extend the problem so that it searches for a value in a fileExplanation / Answer
// Implementing Linear search in an array using C++ Program(using Class )
// This program is error free and compiled on compiler.
#include<iostream>
using namespace std;
class arraysearch
{
private:
int arr[100];
int num_of_elements;
public:
arraysearch()
{
}
arraysearch(int num)
{
num_of_elements=num;
cout<<"enter elements in an array";
for(int iterator=0;iterator<num_of_elements;iterator++)
{
cin>>arr[iterator];
}
}
void linear_search(int);
};
void arraysearch::linear_search(int number)
{
int iterator=0;
for(iterator=0;iterator<num_of_elements ; iterator++)
{
if(arr[iterator]==number)
{ cout<<"Elements found at postion "<<iterator<< "of array";
cout<<endl;
break;
}
}
if(iterator==num_of_elements)
{
cout<<" element not found"<<endl;
}
}
int main()
{
arraysearch obj(10);
obj.linear_search(5);
}
//Till here this is the solution for finding number in an array using Linear Search.
//Now following is the program to read numbers from file and search a number in it.
//When we search a number in a file, we need to pass this number as a string.
int searching_number_file(char *numstring)
{
FILE *fp; // File pointer to point to File.
int flag=0;
char tempstring[100];
fp=fopen("numbersearch.txt","r"); // opening file in read mode
if(fp==NULL)
{
cout<<"Not able to open file";
return 0;
}
while(fgets(temp,100,fp)!=NULL) // we are reading line by line in chunk of 100
{
if(strstr(temp,numstring)
{
cout<<"Number found";
flag=1;
}
} // end of while loop
if(flag==0)
{cout<<"Element not found";}
}
fclose(fp);
return 1;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.