Answer to Question #226374 in C++ for Shivangi malakar

Question #226374

 

1.      Write a C++ program for function template to linear and binary search of an array.

1
Expert's answer
2021-08-16T01:04:17-0400
#include <iostream>
using namespace std;
template <class T>
int LinearSearch(T arr[], int num, T a) {


	for (int i = 0; i < num; ++i) {


		if (arr[i] == a)
			return i;


	}


	return -1;


}


int main() {


	int arr[] = { 6 , 43 ,23 ,6, 12 ,43, 3, 4, 2, 6 };
	int num, index, x;
	num = sizeof(arr) / sizeof(int); // size of arr


	cout << "Integer Array: ";
	for (int i = 0; i <num; ++i)	cout << arr[i] << ' ';
	cout << endl;


	cout << "Enter Value you want to search: ";
	cin >> x;


	index = LinearSearch(arr, num, x);


	if (index != -1)
		cout << x << " is present in the array at position " << index << endl;
	else
		cout << x << " is not present in the array \n" << endl;


	char charArr[] = { 'A', 'v', 'D', 'R', 'T','u', 'j', 'o' };
	char c;
	num = sizeof(charArr) / sizeof(char);


	cout << "Char Array: ";
	for (int i = 0; i < num; ++i)	cout << charArr[i] << ' ';
	cout << endl;


	cout << "Enter character you want to search: ";
	cin >> c;


	index = LinearSearch(charArr, num, c);


	if (index != -1)
		cout << c << " is present in the array at position " << index << endl;
	else
		cout << c << " is not present in the array " << endl;


}

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
APPROVED BY CLIENTS