Professional Documents
Culture Documents
CO1401 Week 6 Lecture
CO1401 Week 6 Lecture
CO1401 Week 6 Lecture
Programming
Week 6
Introduction to Searching and data structures
Introduction
int myArray[SIZE] = { 2, 4, 6, 8 };
record myRecords[AMOUNT];
4 Programming
Calculating whether a value is in an array.
• Consider an array.
• Find whether a particular value exists in the array.
• Need to examine every element of the array: so use a
loop.
5 Programming
Is a value in the array?
int myArray[SIZE] = { 2, 4, 6, 8 };
int searchTerm;
9 Programming
Discussion about this function
10 Programming
Using a flag
11 Programming
void ExistsInArray( int myArray[SIZE], int searchTerm )
{
bool found = false;
for( int i = 0; i < SIZE && found == false; i++ )
{
if ( myArray[i] == searchTerm )
{
found = true;
}
}
if( found == true )
{
cout << searchTerm << " found" << endl;
}
}
12 Programming
break
13 Programming
break
void ExistsInArray( int myArray[SIZE], int searchTerm )
{
bool found = false;
for( int i = 0; i < SIZE; i++ )
{
if ( myArray[i] == searchTerm )
{
found = true;
break; // terminate the loop
}
}
if( found == true )
{
cout << searchTerm << " found" << endl;
}
}
14 Programming
return
16 Programming
Discussion about using return
19 Programming
calling GetName
int main()
{
record table[SIZE] = { { 1, "fred" },
{ 3, "sue" }, { 7, "john" }, { 2, "elsie" } };
20 Programming
GetName: return name from id
21 Programming
Discussion about GetName
22 Programming
UpdateName: update a name given an id
23 Programming
Discussion about UpdateName
24 Programming
PrintInRange: print all values between two indices
26 Programming
Filter
27 Programming