01: #include <iostream>
02: #include <vector>
03: #include <cstdlib>
04: #include <ctime>
06: using namespace std;
08: /**
09: Finds an element in a vector
10: @param v the vector with the elements to search
11: @param a the value to search for
12: @return the index of the first match, or -1 if not found
13: */
14: int linear_search(vector<int> v, int a)
15: { for (int i = 0; i < v.size(); i++)
17: if (v[i] == a) return i;
21: return -1;
22: }
24: /**
25: Prints all elements in a vector
26: @param a the vector to print
27: */
28: void print(vector<int> a)
29: { for (int i = 0; i < a.size(); i++)
31: cout << a[i] << " ";
32: cout << "\n";
33: }
35: /**
36: Sets the seed of the random number generator.
37: */
38: void rand_seed()
39: { int seed = static_cast<int>(time(0));
41: srand(seed);
42: }
44: /**
45: Computes a random integer in a range.
46: @param a the bottom of the range
47: @param b the top of the range
48: @return a random integer x, a <= x and x <= b
49: */
50: int rand_int(int a, int b)
51: { return a + rand() % (b - a + 1); }
54:
55: int main()
56: { rand_seed();
58: vector<int> v(20);
59: for (int i = 0; i < v.size(); i++)
60: v[i] = rand_int(1, 100);
61: print(v);
62: cout << "Enter number to search for: ";
63: int n;
64: cin >> n;
65: int j = linear_search(v, n);
66: cout << "Found in position " << j << "\n";
67: return 0;
68: }