Lecture Programming in C++ - Chapter 9: One-dimensional numeric arrays. On completion of this chapter students will know how to: Create and manipulate arrays, trace and debug loops that manipulate arrays, reserve memory during program execution, use arrays to solve problems.
Trang 1Numeric Arrays
Trang 2Data structure
Grouping of liketype data
Indicated with brackets containing positive integer constant or expression following
identifier
– Subscript or index
Loops commonly used for manipulation
Lesson 9.1
Trang 3Declaration indicates name and reserves space for all elements
Values assigned to array elements using assignment statements
Array names classified as identifiers
Programmer sets size of array explicitly
Lesson 9.1
Trang 4const int N = 26;
double b[N]; int a[25];int b[5+2];
Trang 5Lesson 9.1
Valid
Invalid
Trang 9– Start at zero
– Continue while loop control variable < N
N is the size of the array
Lesson 9.2
Trang 11
Example
Declare and fill an array which will hold 5 double numbers
double num[5];
for (int a = 0; a < 5; a++)
cin >> num[a];
Initialize by reading from the keyboard
Initialize by assigning
values in loop
num[a] = 0;
Lesson 9.2
Trang 12Lesson 9.3
Trang 13for (j = 0; !infile1.eof ( ); j++) {
Trang 15File Input with Known Number of Elements
First line of file contains number
of array elements
infile1 >> num_elem;
for (j = 0; j < num_elem; j++) {
infile1 >> a[j];
}
Trang 16Particular predefined value contained in file that indicates end of data group
Loop and read data value by value until
sentinel is read
for (j = 0; a[j] != 1; j++) {
infile1 >> a[j];
}
Where –1 is the
sentinel value.
Trang 17
Loop to Print Data From Array
(scores is array of 20 test scores)
for (int j = 0; j < 20; ++j) {
cout << scores[ j ] << endl; }
Lesson 9.3
Trang 18Pass address of array to function instead of element values
Trang 19Lesson 9.4
Trang 20b is identifier used to represent
array within function num_elem used to represent number
of array elements in function
Trang 23
Find Smallest Value in Array
small = scores [0];
for (int j = 1; j < 20; ++j) {
if (scores[ j ] < small) small = scores [ j ];
}
Lesson 9.5
Trang 24Declared using class name, object name, and brackets enclosing integer constant Vehicle truck[3];
– Three objects (truck[0], truck[1], truck[2] of class Vehicle
Call member function
– object, dot operator, and function name
truck[0].set_data (50, 2, 3);
Lesson 9.6
Trang 25Good when multiple pieces of information are linked
Use assignment statement to copy one
object array element to another
truck[1] = truck[0];
Lesson 9.6
Trang 26Learned how to: