Create a text file in your usual directory called \"data.txt\" containing the fo
ID: 3676012 • Letter: C
Question
Create a text file in your usual directory called "data.txt" containing the following numbers, one per line: 35.3, 17.4, 34.9, 44, 36.1, 34.75, 38.3, 40, 35.05, 47, 34.97, 35.
In a main program, read all of the data from data.txt and store it in an array. Once you've done so, as a check to make sure input was successful, write a loop to display everything.
Then write a function that takes as input an array and a search key. (There's implicitly another parameter you need here!) Your function should implement linear search and return the index where the first instance of your search key is found, or -1 if it is not found.
Call your function in main a few times to test that it works.
Finally, now just working in main, prompt the user to input a search key and a tolerance. Display all values that are within the tolerance of the key. In other words, should we use a search key of 35 on the data above and a tolerance of 0.1, we would get all of those values that within 0.1 below the search key (34.9, 34.97) the search key and all of those values that are within 0.1 above the search key (35.05), as well as the search key itself. Should we expand the tolerance to 0.5, we would also get 35.3 and 34.75
Explanation / Answer
#include <iostream>
#include <fstream>
#include <math.h>
using namespace std;
//search function
int linearSearch(double arr[], int n, double key){
for(int j=0; j<n; j++){
if(arr[j] == key)
return j;
}
return -1;
}
// search and print with tolerance
void searchAndPrint(double arr[], int n, double key, double tolerance){
for(int j=0; j<n; j++){
if(fabs(arr[j]-key) <= tolerance)
cout<<arr[j]<<" ";
}
cout<<endl;
}
int main ()
{
double arr[20]; // max 20 elements
ifstream infile("data.txt");
int size;
double ele;
int i=0;
while (infile >> ele)
{
arr[i++] = ele;
}
size = i;
//displaying numbers
for(int j=0; j<size; j++){
cout<<arr[j]<<" ";
}
cout<<endl<<endl;
//searching number
int index = linearSearch(arr,size,44);
if(index !=-1)
cout<<"Element 44 is at index "<<index<<endl;
else cout<<"Element 44 is not present in array ";
//searching with tolerance 0.1:
double key;
cout<<"Enter a element to be search: ";
cin>>key;
cout<<"Elements with tolerance 0.1 and search key "<<key<<endl;
searchAndPrint(arr, size, key, 0.1);
return 0;
}
/*
Input: data.txt
35.3
17.4
34.9
44
36.1
34.75
38.3
40
35.05
47
34.97
35
35
Output:
35.3 17.4 34.9 44 36.1 34.75 38.3 40 35.05 47 34.97 35 35
Element 44 is at index 3
Enter a element to be search: 35
Elements with tolerance 0.1 and search key 35
35.05 34.97 35 35
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.