COMP2113
COMP2113_ENGG1340 Programming technologies and Computer programming II [Section 2BC] [2023]
Loading...
Searching...
No Matches
search.cpp File Reference
#include <iostream>
#include <iomanip>
Include dependency graph for search.cpp:

Go to the source code of this file.

Functions

int linearSearch (const int[], int, int)
 
int main ()
 
void print_array (const int[], int)
 

Function Documentation

◆ linearSearch()

int linearSearch ( const int array[],
int sizeOfArray,
int key )

Definition at line 50 of file search.cpp.

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}

Referenced by main().

Here is the caller graph for this function:

◆ main()

int main ( void )

Definition at line 8 of file search.cpp.

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}
int linearSearch(const int[], int, int)
Definition search.cpp:50
void print_array(const int[], int)
Definition search.cpp:35

References linearSearch(), and print_array().

Here is the call graph for this function:

◆ print_array()

void print_array ( const int array[],
int sizeOfArray )

Definition at line 35 of file search.cpp.

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}

Referenced by main().

Here is the caller graph for this function: