copyright © 2002 w. a. tucker1 chapter 9 lecture notes bill tucker austin community college cosc...
TRANSCRIPT
Copyright © 2002 W. A. Tucker 1
Chapter 9 Lecture Notes
Bill Tucker
Austin Community College
COSC 1315
Copyright © 2002 W. A. Tucker 2
Multiple Values
• Recall that every value stored in memory needs an identifier (name) to refer to the contents of the memory location
• What if you have multiple values of the same data type
• EX: Five Integers– int num1, num2, num3, num4, num5;
Copyright © 2002 W. A. Tucker 3
Processing Multiple Values
• If you wanted to read in the five values and average them, here is the code:
int num1, num2, num3, num4, num5;int sum, avg;cout << “Enter 5 integers “;cin >>num1>>num2>>num3>>num4>>num5;sum = num1+num2+num3+num4+num5;avg = sum / 5;cout << “Sum is “<<sum<<“ Avg is “<<avg<<endl;
• Note that there is a unique identifier for each• Now what if you had fifty values?? Or 500??
Copyright © 2002 W. A. Tucker 4
Arrays
• An Array is a collection of data elements
• What is a collection?– A stamp collection is a collection of stamps– A coin collection is a collection of coins– A doll collection is a collection of dolls
• They all have something in common
• Thus an Array is a collection of data elements of the same data type
Copyright © 2002 W. A. Tucker 5
Array Declarations
• Arrays are declared as follows:– To declare an array (collection) of data types use:
int num [50]; // arrray of integers
double value [10]; // array of doubles char letter [26]; // array of characters bool test [15]; // array of boolean values string name [25]; // array of strings
• Thus you only have one identifier to represent 50 different values
• How does the compiler know which entry in the array you want to use??
Copyright © 2002 W. A. Tucker 6
Array Subscripts
• Array subscripts are used to indicate specific elements of an array
• In mathematics, X 2 is read as “X sub 2”
• In C++, x [ 2 ] is read as “X sub 2”
• A subscript may even contain expressions X [ y + 3]
• Array subscripts MUST be an integer value
Copyright © 2002 W. A. Tucker 7
Array Addressing
• Elements refer to the number of different values that may be in an array
• Subscripts refer to a specific addressable value• An array declared as: int num [5];
contains 5 elements
num[0] num[1] num[2] num[3] num[4]
The valid subscripts are 0 through 4• Note for an array of “SIZE”, the valid subscripts
are “ZERO” through “SIZE – 1”
Copyright © 2002 W. A. Tucker 8
Array Addressing Example
• Given the array int num [5];• num[3] = 6; // will assign a 6 to subscript 3• num[4] = 2; // will assign a 2 to subscript 4• num[0] = 8; // will assign an 8 to subscript 0• num[1] = 3; // will assign a 3 to subscript 1• num[2] = 5; // will assign a 5 to subscript 2
Elements 1 2 3 4 5 Size ElementsValue 8 3 5 6 2Subscript 0 1 2 3 4 0 - (Size-1) sub
Copyright © 2002 W. A. Tucker 9
Subscript Range
• C++ does not do error checking on the value of a subscript
• Valid subscripts are zero though size-1• If you try to address a subscript outside the
range of zero through size-1 you will not get an error message from C++
• BUT you may create a catastrophic error and get “this program has performed an illegal operation and will be shut down”
• The statement num[-1] = 0; will store a zero in the location BEFORE the start of array num
Copyright © 2002 W. A. Tucker 10
Subscript = Memory Address
• Normally the compiler knows the memory address of a variable name
• An array uses subscripts to determine which element in the array is being addressed– This subscript may be the result of a
calculation, there is no way the compiler may determine the location
– The compiler generates code that computes the memory location during execution
Copyright © 2002 W. A. Tucker 11
Array Memory Mapping
• Since an array is a collection of elements of the same data type, the size (number of bytes) of each element is known by the compiler
• The name of the array equates to a specific memory address (the address where the array starts)
• The value of the subscript is used to calculate a “displacement” or “offset” from the array address to determine the exact memory address
Copyright © 2002 W. A. Tucker 12
Memory Mapping Example
• An integer usually occupies 4 bytes • Given: int num[5];Element Subscript Offset Memory
1 0 0 * 4 30016
2 1 1 * 4 30416
3 2 2 * 4 30816
4 3 3 * 4 30C16
5 4 4 * 4 31016
Copyright © 2002 W. A. Tucker 13
Accessing Array Elements
• Repetition logic is well suited to access array values since they only have one identifier
• Read and average 5 integer values int num[5], avg, sum = 0;for (int i=0; i<5; i++){
cout << “Enter an integer “;cin >> num[i];sum = sum + num[i];
}avg = sum / 5;cout << “Sum is “<< sum << “ Avg is “ << avg << endl;
Copyright © 2002 W. A. Tucker 14
More on Declaring Arrays
• Note that the for loop used the array size of 5 in the test
• If we write a program for a particular array size, then need to change the size, there are many places to change code
• An easier way is to declare a constant integer called SIZE and use that in both the declaration and loop
Copyright © 2002 W. A. Tucker 15
Example of Averaging Array Values
const int SIZE = 5;int num[SIZE];int avg, sum = 0;for (int i=0; i < SIZE; i++){
cout << “Enter an integer “;cin >> num[i];sum = sum + num[i];
}avg = sum / SIZE;cout << “Sum is “ << sum << “ Avg is “ << avg << endl;
Copyright © 2002 W. A. Tucker 16
Initializing Arrays
• Recall that declaration statement have the option to initialize values
• This is also true when declaring arrays• int num[5] = {8, 3, 5, 6, 2};• int num[5] = {0, 0, 0, 0, 0};• What will the following do? a) int num[5] = {0}; // declaration b) for (int i=0; i<5; i++)// execution
num[i] = 0;
Copyright © 2002 W. A. Tucker 17
Passing Arrays to Functions
• An array name passed as an argument to a function is automatically passed by reference– To pass by value would require making a copy of the
entire array
• This is indicated with the addition of square braces [ ] in both the prototype and function header, but NOT in the function call
• Since the function needs to know the size of the array, passing the array size makes it possible to write generic functions that process arrays
Copyright © 2002 W. A. Tucker 18
Function to Sum an Array
• Prototype: int sumArray (int [ ], int); • Declaration: int num[10], result;
Call: result = sumArray (num, 10);• Definition:
int sumArray (int a[ ], int size} {
int sum = 0;for (int i = 0; i < size; i++)
sum = sum + a[i];return sum;
}
Copyright © 2002 W. A. Tucker 19
Passing One Value of an Array
• You can also pass just one value of an array to a function, just like it was a single identifier
• Prototype: void display (int);• Declaration: int num[10];
Call: display (num[3]);• Definition
void display (int x){
cout <<“Value is “ << x << endl;}
Copyright © 2002 W. A. Tucker 20
Summary of Array Passing
• Passing an integer array called num
Prototype Call Definition
int [ ] (num) int a [ ]
• Passing a value of an integer array called num
Prototype Call Definition
int (num[i]) int a
Copyright © 2002 W. A. Tucker 21
Parallel Arrays
• Recall that an array is a collection of elements related by the same data type.
• How can you establish an array relationship of sets of elements where each set contains more than one data type?
• The answer is to utilize the concept of “parallel arrays.”
Copyright © 2002 W. A. Tucker 22
Parallel Arrays
• Parallel Arrays are different arrays that have the same number of entries.
• Since they are different arrays, they may contain collections of different data types.
• Since they have the same number of elements, there is a correspondence relationship between elements with the same subscript
Copyright © 2002 W. A. Tucker 23
Parallel Arrays
• EX: a set of two data elements that are related, Student ID Student Grade
123456 95.4
int studID[SIZE]; double studGrade[SIZE];
123456 95.4Subscript N
Copyright © 2002 Jade Lindquist 24
Iterating through Parallel Arrays
Code to print the contents of two parallel arrays: int studID[SIZE];double studGrade[SIZE];int cnt = 0;getInput(ifile, studID, studGrade, cnt ); // cnt is set to the
number of elements read into the arrayfor (int i = 0; i < cnt; i++){
cout << “Student ID: “ << studID[i] << “ Grade: “ << studGrade[i] << endl;
}
Copyright © 2002 Jade Lindquist 25
Filling arrays from a file
Code to fill the two parallel arrays from a file: int studID[SIZE];
double studGrade[SIZE];int cnt = 0; // cnt of records in the filewhile (cnt < SIZE && !ifile.eof()){ifile >> studID[cnt] >> studGrade[cnt];cnt++;}
Copyright © 2002 Jade Lindquist 26
The count of records in the arrays should be passed to any function
that operates on the arrays.
Filling arrays from a file, cont.
Copyright © 2002 Jade Lindquist 27
Input Files
When reading from a file using the extraction operator (>>), delete any blank lines and spaces at the end of your last record.
Example:
6217 10000 2
9280 6200 1
The cursor should be immediately after the 1. Otherwise, your program may read in garbage data.
Copyright © 2002 Jade Lindquist 28
Input Files
When reading from a file using getline, end your last line of data with a new line. The cursor should be at the beginning of the line AFTER your last record.Example:The quick brown fox jumped over the lazy dog.Now is the time for all good men to come to the aid of your country.She sells sea shells by the sea shore.Inch by inch, life's a cinch. Yard by yard, life is hard.
The cursor should be under the ‘I’ in “Inch”. Otherwise, your program will not read the last record.