COMP2113
COMP2113_ENGG1340 Programming technologies and Computer programming II [Section 2BC] [2023]
Loading...
Searching...
No Matches
search.cpp
Go to the documentation of this file.
1#include <iostream>
2#include <iomanip>
3using namespace std;
4
5int linearSearch( const int [], int, int );
6void print_array( const int[], int );
7
8int main()
9{
10 const int arraySize = 10; // size of array
11 int a[ arraySize ]; // declare array a
12 int searchKey; // value to locate in array a
13
14 // fill in some data to array
15 for ( int i = 0; i < arraySize; ++i )
16 a[i] = 2 * i;
17
18 print_array( a, arraySize );
19
20 cout << "Enter an integer to search: ";
21 cin >> searchKey;
22
23 // try to locate searchKey in a
24 int element = linearSearch( a, arraySize, searchKey );
25
26 // display search results
27 if ( element != -1 )
28 cout << "Value found in element " << element << endl;
29 else
30 cout << "Value not found" << endl;
31
32 return 0;
33}
34
35void print_array( const int array[], int sizeOfArray )
36{
37 for ( int i = 0; i < sizeOfArray; ++i )
38 cout << "[" << setw(2) << i << "] ";
39 cout << endl;
40
41 for ( int i = 0; i < sizeOfArray; ++i )
42 cout << setw(3) << array[i] << " ";
43 cout << endl;
44}
45
46
47// linear search of key value in array[]
48// return the index of first occurrence of key in array[]
49// return -1 if key is not found in array[]
50int linearSearch( const int array[], int sizeOfArray, int key )
51{
52 for ( int j = 0; j < sizeOfArray; ++j )
53 if ( array[ j ] == key ) // if found,
54 return j; // return location of key
55 return -1; // key not found
56}
int linearSearch(const int[], int, int)
Definition search.cpp:50
void print_array(const int[], int)
Definition search.cpp:35
int main()
Definition search.cpp:8