CO1401 Week 6 Lecture

You might also like

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 27

CO1401

Programming

Week 6
Introduction to Searching and data structures
Introduction

• Consolidation and reinforcement


• This lecture will also lead into the succeeding lecture
about searching (and later sorting). It also helps lay the
foundations for looking at data structures.
• I'm also introducing some techniques which will be
useful for classes (Object Oriented Programming), e.g.
GetName on slide is a slide 21 is a "getter" (or accessor
to be more formal.) UpdateName on slide 23 is a
"setter" (or mutator).
• This lecture will implement a very simple search. It is
possible to make the search more efficient and faster.

• Spot test - need pen or pencil.


2 Programming
Where we are in the module

• You've done structures. struct record


• You use this method to create
{
an object of multiple data
types. The data types can be int id;
different types. You define a string name;
new data type. You give it a };
name. You can then use this
name to create objects of this
new data type. record myRecord;
• Use the dot operator to select myRecord.id = 4;
a field from the structure.
• Structures are a way to create
a new data type.
3 Programming
Where we are in the module

• You've done arrays


• You use this method to create an object which has
multiple elements of the same data type. Use the
square bracket syntax to define the size of the array.
Use the square brackets to select individual elements
of the array.

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.

bool found = false;


• Use a boolean value.
• Note the way that it is set to false before the loop is
entered.
• If the value is found then the boolean is set to true.
• Otherwise it will remain false and so tell us that the
value has not been found.

5 Programming
Is a value in the array?

const int SIZE = 4;

For the moment assume that the rest of the code is in


main().

int myArray[SIZE] = { 2, 4, 6, 8 };
int searchTerm;

cout << "What value do you want to " ;


cout << "search for" << endl;
cin >> searchTerm;
6 Programming
Is a value in the array?

bool found = false;


for( int i = 0; i < SIZE; i++ )
{
if ( myArray[i] == searchTerm )
{
found = true;
}
}
if( found == true )
{
cout << searchTerm << " found" << endl;
}
7 Programming
Function for "is a value in the array?"

• I now want to put this in a function.


• Note the way that the array has been passed over in
the parameter list. Remember that an array is passed
over by name. This is a call by reference since the
name of an array is the address of the beginning of
the array.
• I'm also going to pass 'searchTerm' over to the
function.
int main()
{
ExistsInArray( myArray, searchTerm );
}
8 Programming
void ExistsInArray( int myArray[SIZE], int searchTerm )
{
bool found = false;
for( int i = 0; i < SIZE; i++ )
{
if ( myArray[i] == searchTerm )
{
found = true;
}
}
if( found == true )
{
cout << searchTerm << " found" << endl;
}
}

9 Programming
Discussion about this function

• The function works.


• However, the search is not efficient.

• Q: What is inefficient about the function?.

• Continuing to search through the array even if the


value has been found.

• Instead want to end the search as soon as the value


has been found.
• This will make the function more efficient.

10 Programming
Using a flag

• A "flag" is a variable that indicates the state of a


program.
• The existing program uses a boolean variable to
indicate whether the value has been found or not.
• It would be more efficient to stop when the value has
been found:
• so let's use the boolean as a flag and include a test
using this boolean in the loop conditition,
• in effect using the boolean as a flag to say that the
loop can finish

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

• C++ has a keyword: 'break'.


• You may see it being used in circumstances similar to
this so I'd better mention it here.
• The action of the keyword 'break' is to terminate the
nearest enclosing for, do, while or switch statement.
• It would work in this context.
• Note that it terminates "the nearest enclosing...".
• It won't take you out of a nested loop, for example,
only the inner loop.
• It would work but its limitations can lead to
unintended problems if you forget its properties.

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

• A function can send data back using the 'return'


statement.
• Specifies the value to be returned by the function.
int FunctionWithReturn()
{
int number = 7;
return number;
}
• However, 'return' also has the useful characteristic
that it causes a dynamic exit from a function.
• This can be used to simplify code.
15 Programming
return

bool ExistsInArray( int myArray[SIZE], int searchTerm )


{
for( int i = 0; i < SIZE; i++ )
{
if ( myArray[i] == searchTerm )
{
cout << searchTerm << " found" << endl;
return true;
}
}
cout << searchTerm << " not found" << endl;
return false;
}

16 Programming
Discussion about using return

• Notice how shorter, elegant and (I think) readable the


code is.
• Observe the way that 'return' causes a dynamic exit
from the function. As soon as the 'return' statement is
met, the function ends.
• The second 'return' statement (the last line of the
function) is only reached if the term has not already
been found.
• A function which returns a value should
unambiguously return one. The compiler will give you
a warning otherwise. It should be possible to reach a
return statement without it being inside a conditional
block.
17 Programming
Arrays of structures

• We're now going to use an array of structures.


Obviously the principle will be the same for any type of
array.
• An array of structures is like a database: one field is the
key and the second is the data. The key field is the id.
I'm going to search through the key field and then
return the data from the data field.
struct record
• I've given the names of the
{
fields of the structure a
preceeding 'm'. This is a int mId;
useful convention. 'm' string mName;
stands for data member. };
18 Programming
Database

• I'm going to use this structure to demonstrate a few


arrays operations. In each case I'll put the code in a
function.
• Each of the functions is an operation upon the data.
• The database is holding the id and name of a person.

• The first function will find and return the name of a


person given an id.

19 Programming
calling GetName

int main()
{
record table[SIZE] = { { 1, "fred" },
{ 3, "sue" }, { 7, "john" }, { 2, "elsie" } };

cout << GetName( 1, table ) << endl;


cout << GetName( 3, table ) << endl;
cout << GetName( 7, table ) << endl;
cout << GetName( 2, table ) << endl;
cout << GetName( 5, table ) << endl;
}

20 Programming
GetName: return name from id

string GetName( int id, record table[SIZE] )


{
for( int i = 0; i < SIZE; i++ )
{
if ( id == table[i].mId )
{
return table[i].mName;
}
}
// what to do if not found?
cout << "ERROR" << endl;
return "";
}

21 Programming
Discussion about GetName

• Notice the use of 'return' .


• The function needs to deal with the error condition.
I've chosen to output an error message and return an
empty string.
• Use of the syntax of the dot operator for the fields.
• (For future reference: cast your mind back to the use
of methods in C#. This is actually the same operation,
but pulling out a data member rather than a method).

22 Programming
UpdateName: update a name given an id

void UpdateName( int id, record table[SIZE], string


name )
{
for( int i = 0; i < SIZE; i++ )
{
if ( id == table[i].mId )
{
table[i].mName = name;
return;
}
}
// what to do if not found?
cout << "ERROR" << endl;
}

23 Programming
Discussion about UpdateName

• I'm using another property of 'return' .


• The keyword 'return' can be used just on its own. In
other words, it doesn't have to return a value.
• What this does is cause a dynamic exit from the
function.

24 Programming
PrintInRange: print all values between two indices

void PrintInRange( int start, int end,


record table[SIZE] )
{
if( start < 0 || end >= SIZE )
{
cout << "error" << endl;
return;
}
for( int i = start; i <= end; i++ )
{
cout << table[i].mName << endl;
}
}
25 Programming
Filter

• Lastly look at a filter function.


• FilterById will output all of the names where the id
is greater than or equal to the given value.

26 Programming
Filter

void FilterById( int id, record table[SIZE] )


{
for( int i = 0; i < SIZE; i++ )
{
if ( table[i].mId >= id )
{
cout << table[i].mName << endl;
}
}
}

27 Programming

You might also like