Download presentation
Presentation is loading. Please wait.
2
Rossella Lau Lecture 4, DCO10105, Semester B,2005-6 DCO10105 Object-Oriented Programming and Design Lecture 4: Basic containers Array: fundamental processing on arrays, parameter passing with array, static and dynamic array String: C++ string and former C-style string Vector: a template class in the STL Separate compilation and header file.h Good programming practice: constant identifier & documentation -- By Rossella Lau
3
Rossella Lau Lecture 4, DCO10105, Semester B,2005-6 The problem Define variables which can store each student’s score for DCO10105 300 students ==> 300 variables Variables: score1, score2,..., score300 To find the average score of all students: (score1 + score2 +... + score300) / 300 Too long to code
4
Rossella Lau Lecture 4, DCO10105, Semester B,2005-6 Array and array index Same as Java, C++ supports arrays, to allow for multiple occurrences of variables Elements (slots) of an array are consecutive An array cannot be processed directly, but the elements can be To identify each element, an index or subscript is used. In C++, the index is counted from 0, 1, until number of element -1 N-13210
5
Rossella Lau Lecture 4, DCO10105, Semester B,2005-6 The array for the problem array id: scores number of elements: 300 To declare such an array in C: int scores[300]; To identify each element: scores[0] -- the first student’sscore scores[1] -- the second student’s score … scores[299] -- the last student’s score scores: scores[0]scores[1]scores[299]
6
Rossella Lau Lecture 4, DCO10105, Semester B,2005-6 Array declaration type arrayName[constIntExp] Examples: int scores[300]; int const NO_STUDENT = 300; int scores[ NO_STUDENT ];
7
Rossella Lau Lecture 4, DCO10105, Semester B,2005-6 Validity of referencing array elements For the above example scores’ indexes can be in the range 0 through 299 The index value of 300 or a larger number are illegal In C++, no array boundaries are checked Unlike Java, there is not an error message when scores[300] is used scores[300] may result in incorrect values and even crash the computer system CARE MUST BE TAKEN to prevent illegal references
8
Rossella Lau Lecture 4, DCO10105, Semester B,2005-6 Initialization of arrays An array must be initialized before using Compile-time initialization full initialization: int scores[5] = {70, 85, 65, 90, 80}; partial initialization: int scores[5] = {70, 85}; The third to fifth elements will also be initialized to 0 another way to declare and initialize int scores[] = {70, 85, 65, 90, 80}; This declaration defines and initializes array scores in which there are 5 elements Run-time initialization for (int i = 0; i<NO_STUDENT; i++) scores[i]=0;
9
Rossella Lau Lecture 4, DCO10105, Semester B,2005-6 Traversal of an array The loop for the run-time initialization of an array traverses the array once for (int i = 0; i<NO_STUDENT; i++) …scores[i]… // process on an element To traverse means to visit each element of the array once Be careful, although i has the same data type as the elements in the array in this example, they do not need to have the same data type The loop control variable, i, is also called an iterator which leads the loop to traverse elements one after the other This pattern of loop is useful whenever we need to traverse the array for other processes: e.g., load data and print data
10
Rossella Lau Lecture 4, DCO10105, Semester B,2005-6 Load and print To load (fill or input) data into an array for (size_t i = 0; i < NO_STUDENT; i++) { cerr << “Enter score for student” << i+1 << “:”; cin >> scores[i]; } To print data from an array for (size_t i=0; i < NO_STUDENT; i++) { cout << “The score for student ” << i+1; << “ is: “ << scores[i] << endl; } Sometimes, data type size_t is used to separate its data type from the type of an int array; size_t is unsigned int
11
Rossella Lau Lecture 4, DCO10105, Semester B,2005-6 Array as a parameter When we write in modular programs, the processes of fillData() and printData() require an array as a parameter To declare an array as a formal parameter, e.g., fillData( int array[], size_t sizeOfArray); printData(int array[], size_t sizeOfArray); [] indicates the id before it is an array; No.length, as in Java, is associated with an array To call the function, an array id should pass to it e.g., fillData(scores, NO_STUDENT);
12
Rossella Lau Lecture 4, DCO10105, Semester B,2005-6 Coding for fillData() and printData() void fillData( int array[], size_t sizeOfArray ) { for (size_t i = 0; i < sizeOfArray; i++) { cerr << “Enter value of element ” << i+1 << “:”; cin >> array[i]; } void printData( int array[], size_t sizeOfArray ) { for (size_t i = 0; i < sizeOfArray; i++) { cout << “The score for student ” << i+1 << “ is: “ << array[i] << endl; }
13
Rossella Lau Lecture 4, DCO10105, Semester B,2005-6 Other popular processes on arrays Other than initializing, filling, and printing data, there are many popular processes: searching finding relationships among data on an array sum average max (maximum) min (minimum) ……
14
Rossella Lau Lecture 4, DCO10105, Semester B,2005-6 search() To search the index for student id = 50006789 The data type of target and elements of the array must be the same To call this function: index = search(studentID, NO_STUDENT, 50006789); int search(int array[],size_t sizeOfArray,int target) { int index = -1; // not found; // note that size_t cannot store -1 for (size_t i = 0; i < sizeOfArray; i++) { if (array[i] == target ) { index = i; break; // found } return index;}
15
Rossella Lau Lecture 4, DCO10105, Semester B,2005-6 Refine of search() I The previous search() is not good as it has a “break” statement int search(int array[],size_t sizeOfArray,int target){ for (size_t i = 0; i < sizeOfArray; i++) { if (array[i] == target ) { return i; // found } return -1; // not found } However, there are two return statements – seems that we have two exits for search()
16
Rossella Lau Lecture 4, DCO10105, Semester B,2005-6 Refine of search() II int search(int array[],size_t sizeOfArray,int target) { int i = 0; for (; i < sizeOfArray && array[i] != target ; i++); return i == sizeOfArray ? -1 : i; } The loop continues when it is not at the end of the array nor when the traversed element is the target it stops when the traversed element is the target (found) or the loop reaches the end of the array (not found) i should be declared outside the loop in order to allow it to be referenced outside the loop ; after the loop indicates there is an empty loop body
17
Rossella Lau Lecture 4, DCO10105, Semester B,2005-6 finding relationships among data I int sum( int array[], size_t sizeOfArray ) { int total = 0; for (size_t i = 0; i < sizeOfArray; i++) total += array[i]; return total; } int average( int array[], size_t sizeOfArray ) { return sum (array, sizeOfArray) / sizeOfArray; }
18
Rossella Lau Lecture 4, DCO10105, Semester B,2005-6 finding relationships among data II Every time the computer can only compare two data To allow for finding the maximum, the strategy is to compare the current element with the maximum of the previous elements and see which is the real maximum, similarly: int max( int array[], size_t sizeOfArray ) { int max = array[0]; // at least 1 element for (size_t i = 1; i < sizeOfArray; i++) if (array[i] > max) max = array[i]; return max; } int min( int array[], size_t sizeOfArray ) { int min = array[0]; // at least 1 element for (size_t i = 1; i < sizeOfArray; i++) if (array[i] < min) min = array[i]; return min; }
19
Rossella Lau Lecture 4, DCO10105, Semester B,2005-6 Sample coding on exercises Malik’s programming exercise: 2:8 – using array to store the five numbers …… int main() { const size_t SIZE = 5; double decimals[SIZE]; fillData(decimals, SIZE); int sum = sumWithRound(decimals, SIZE); displayResult(sum); } int sumWithRound(double decimals[], size_t sizeOfArray) { return sum (decimals, sizeOfArray) +.5; } ……
20
Rossella Lau Lecture 4, DCO10105, Semester B,2005-6 Parallel arrays An array usually does not independently exist E.g., scores[], comes along with other arrays, e.g., studentID[], studentName[] The same index for these arrays store data for the same student scores[], studentID[], and studentName[] are called parallel arrays
21
Rossella Lau Lecture 4, DCO10105, Semester B,2005-6 Sample of processes on parallel arrays …… const size_t NO_STUDENT = 300; int studentID[NO_STUDENT]; string studentName[NO_STUDENT]; int scores[NO_STUDENT]; … … // load data into arrays and other processes … int index = search(studentID, NO_STUDENT, inputID); if (index != -1) cout << “The score for student “ << studentName[index] << “ (“ << studentID[index] << “) is: “ << scores[index] << endl; else cout << “Student “ << inputID << “ not found”;
22
Rossella Lau Lecture 4, DCO10105, Semester B,2005-6 Constant identifier The size of the array in the previous example uses an identifier, instead of literal value Literal value is just whatever you see, whatever it represents; e.g., 5 means numeric 5 It is a good habit to name literal value in a program whenever possible to allow for better maintenance and readability; e.g., when changing the size of the array, you don’t need to change 5 everywhere in the program It is clear to a reader the meaning of 5
23
Rossella Lau Lecture 4, DCO10105, Semester B,2005-6 User-defined “library” In the sample coding, one can see if there is another program using arrays, we need to re-write (or copy and paste) all the respective functions into the new program But all the fundamental functions can be re-used for different programs using arrays Why not pack all the fundamental array functions into a “library”: array.cpp
24
Rossella Lau Lecture 4, DCO10105, Semester B,2005-6 array.cpp and array.h It includes all the functions of fundamental array processes It does not have main() since it provides services to other application programs To use the functions inside array.cpp, a program must declare the function prototypes of the functions in array.cpp in order to get the compiler to pass through Function prototypes of array.cpp : array.h Program using functions can simply add #include “array.h” in the program header: ch2PEx8.cpp (v 3.1) – Note that functions not in array.h are still defined in the program
25
Rossella Lau Lecture 4, DCO10105, Semester B,2005-6 Types of header file To include the header file coming from the system libraries: #include <> is the indicator .h is not required to be specified inside <> in C++ A prefix of “ c ” is for former C library header file To include the header file defined by a programmer: #include “myHeaderFile” “” is the indicator
26
Rossella Lau Lecture 4, DCO10105, Semester B,2005-6 Separate compilation To compile the program ch2PEx8.cpp, one may do: g++ chPEx8.cpp array.cpp However, it causes the compiler to compile array.cpp once for each different program C++ compiler allows a user to compile a program without generating the executable code: g++ -c array.cpp then every application program can save the compilation time for array.cpp by doing: e.g., g++ -c ch2PEx8.cpp g++ ch2PEx8.o array.o
27
Rossella Lau Lecture 4, DCO10105, Semester B,2005-6 Make The above process seems to involve a lot of typing Usually, the separate compilation goes along with a make file which pre-types all the necessary commands to compile the set of programs In Dev-C++, the make file is automatically generated when you create a project
28
Rossella Lau Lecture 4, DCO10105, Semester B,2005-6 Good programming practice: Documentation As we are having more and more sources as a program set, we should at least provide some comments, or documentation, to indicate the basic information of a source: Program Header: Program id and its purpose Author’s information Version number Example: The header comments in cirArea.cpp (all versions) Description for functions in the program Description for identifiers, when necessary
29
Rossella Lau Lecture 4, DCO10105, Semester B,2005-6 C++ comment indicators Comments inside a program will not be compiled but are just for the purpose of documenting a program In C++, comments are allowed in two styles: Comments after the symbol of “ // ” on a line Comments blocked by a pair of “ /* ” and “ */ ” no matter how many lines across it has
30
Rossella Lau Lecture 4, DCO10105, Semester B,2005-6 Javadoc In java, when comments are blocked by “ /** ” and “ */ ”, the comments are treated as Javadoc Javadoc has its format and style It allows a utility in Java, javadoc, to automatically generate API documentation and greatly reduce a programmer’s work in documentation outside a program Nowadays, some C++ environments also adopt Javadoc style to allow for API documentation automatic generation It is recommended to use Javadoc style to document the program header and optionally, all function headers
31
Rossella Lau Lecture 4, DCO10105, Semester B,2005-6 Javadoc for a function A description for the function @param is a javadoc tag to indicate the documentation of a parameter; each parameter should have a single @param tag on a separated line @return is a javadoc tag to indicate what value is returned by the function; it should exist after @param Without a utility like javadoc, we can simply provide the description of a function but practicing on @param and @return are welcome! /** * Sum all double numbers of an array * and round it to the nearest integer * @param decimals[] a double array for calculation * @param sizeOfArray the size of an array * @return a nearest integer of the decimal sum */ int sumWithRound(double decimals[],size_t sizeOfArray){ return sum (decimals, sizeOfArray) +.5; }
32
Rossella Lau Lecture 4, DCO10105, Semester B,2005-6 Documenting identifiers Old style of documentation comment identifiers declared in a program However, size_t sizeOfArray; //stores the size of an array The comment is quite redundant when sizeOfArray can express the same meaning Though, size_t s; // stores the size of an array The comment is necessary but the problem is a reader must remember the meaning of s in order to understand the subsequent codes! Why not just name identifiers as meaningfully as possible to avoid documentation on identifiers!
33
Rossella Lau Lecture 4, DCO10105, Semester B,2005-6 Dynamic array The examples we saw before define static arrays The size of the array is fixed The size of the array must be a constant (or the result from a constant expression) The size of the array must be known C++ allows definition of a dynamic array as follows: int *array = new int[sizeTVariable]; However, at the end of a function declaring the array, one must have the statement delete[] array; Example: ch2PEx8.cpp (v3.2)
34
Rossella Lau Lecture 4, DCO10105, Semester B,2005-6 Array overflow When available slots are full and there is still data going to store in the array, an overflow occurs! To handle overflow: Static array Dynamic array can define an additional new array with larger size (usually double of the original) copy the contents of the original array to the new one Throw away the original and make the new one as the original The current array will increase the number of empty slots
35
Rossella Lau Lecture 4, DCO10105, Semester B,2005-6 Vector As O-O concept was matured and there were O-O languages, class Vector usually comes with a language’s library A vector encapsulates not only the fundamental array processes but also all the related housekeeping work e.g., in taking care of the overflow In C++, it supports a class called vector<> which is a template class in the STL A template class allows a user to specify the data type of its element
36
Rossella Lau Lecture 4, DCO10105, Semester B,2005-6 Using C++ Vector To declare an int vector instance: vector scores; To declare a string vector instance: vector studentName; A vector instance can have the same coding “style” of an array, e.g., same scores[i], studentName[i] In addition to an array, scores.size() can return the number of elements in scores
37
Rossella Lau Lecture 4, DCO10105, Semester B,2005-6 Some functions of vector<> Malik’s Table 10-2
38
Rossella Lau Lecture 4, DCO10105, Semester B,2005-6 Examples of using vector<> Example programs for vector<>: ch2PEx8.cpp (v3.3), Malik: Example 10-7 vector<> in parameter passing To declare it as a formal parameter, e.g., fillData( vector & intVector); printData(vector const & intVector); & should be used when the parameter is not in basic data type sizeOfArray is omitted since intVector.size() can be used const is declared if the parameter is not being modified inside the function – a good practice to minimize debugging effort To call the function, a vector id should pass to it; e.g., fillData(scores);
39
Rossella Lau Lecture 4, DCO10105, Semester B,2005-6 String in C++ In C++, there are two types of strings, class string and C-style string which is supported in the C generation before C++ A C-style string is defined as an array of characters with the last byte valued binary zero in order to use function provided in the library of
40
Rossella Lau Lecture 4, DCO10105, Semester B,2005-6 C-style string, a case of array of characters To define a string: char aString[10]; // can store up to 9 characters To refer to a string, use aString Literal values representation: “C Programming Language” “This string exceeds \ over two lines ” “The string with a newline\n” Popular C-string functions (Malik’s Table 9-1): strcmp(), strcpy(), strlen(), and strcat() Example: Malik’s Example 9-8
41
Rossella Lau Lecture 4, DCO10105, Semester B,2005-6 C++ string as a case of vector Class string encapsulates the process on array of characters and no more care in taking on the last binary zero byte in C-style string Note that the header file should be and the class name is string The first character is not capitalized Some compilers may allow for using String and string as the same Two strings can be concatenated by simply doing an “add” (+) operation List of string functions: http://www.cppreference.com/cppstring/
42
Rossella Lau Lecture 4, DCO10105, Semester B,2005-6 Summary An array is a multiple occurrence of an element and each element is identified by a subscript An array must be initialized before use The basic array processes include fillData, printData, search an element, and find relations among elements (e.g., average, sum, maximum, and minimum) Vector encapsulates the array processes into a templated class When passing a vector as a parameter, & is a must and const is useful String is a frequently used class and is a case of vector C++ allows for separate compilation Good naming of identifiers serves as good documentation
43
Rossella Lau Lecture 4, DCO10105, Semester B,2005-6 Reference Malik: 9.1-3, 10.2 Programming styles: http://personal.cityu.edu.hk/~dcrosela/teaching/04- 05/dco10105/help/style_docu.htm -- END --
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.