Tải bản đầy đủ (.pdf) (26 trang)

Lecture Programming in C++ - Chapter 9: One-dimensional numeric arrays

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (417.29 KB, 26 trang )

Chapter 9 – One­Dimensional 
Numeric Arrays


Array
Data structure
Grouping of like­type data
Indicated with brackets containing positive 
integer constant or expression following 
identifier
– Subscript or index

Loops commonly used for manipulation
Lesson 9.1


 One­Dimensional Arrays
Declaration 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


Array Length
Determined by expression or value enclosed 
in brackets in declaration
General form for declaration


    type  name[value];
Value in brackets can be constant variable, 
expression, or literal
const  int N = 26;
double b[N];
Lesson 9.1

int a[25];
int b[5+2];


Array Length
Must be integer constant greater than 0
Only integer type variables (with modifiers)
– int, char
– signed, unsigned, short, long

Always within brackets following identifier
Valid
Examples:     int c[32];
                      int  c[­25], b[43.5]; Invalid
Lesson 9.1


Array Subscripts
First index or subscript is 0
int a[2];






Data type of elements is int
Name of array is a
Number of elements is 2
Valid subscripts are 0 and 1

Address as  a[0] and a[1]
Lesson 9.1


Printing Array Elements
Use cout
Treat like single variable
Print one element at a time
Example:
  cout << "a[0] = " << a[0]  << endl;

Lesson 9.1


Initialization
In declarations enclosed in curly braces
int a[5] = {11,22};
Declares array a and initializes first two 
elements and all remaining set to zero
int b[ ] = {1,2,8,9,5};
Declares array b and initializes all elements
and sets the length of the array to 5
Lesson 9.2



Working With Arrays
Remember subscripts must calculate to an 
integral value
Normally use loop to control array processing
Common loop is for loop
– Start at zero
– Continue while loop control variable  < N
N is the size of the array

 
Lesson 9.2

 


Using An Array
Declare     int   test[3];
– sets aside  3  storage locations

use index to reference the variables
  test[0] = 86;
  test[1] = 92;
86 92
90
  test[2] = 90;
 
Lesson 9.2


 


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];
num[a] = 0;
Initialize by assigning
Initialize by reading
from the keyboard
values in loop
 
Lesson 9.2

 


Input/Output
Typically use files
Reading from file, number of elements ?
– Guard against reading past end of file
– Use function eof( ) which returns 1 when end

Reading from file, number of elements 
known

Lesson 9.3



Loop to Read Data Into an Array
Number of elements unknown!

for (j = 0; !infile1.eof ( ); j++)
      {
       infile1 >> a[j];
      }
Example of for loop
Lesson 9.3


Loop to Read Data Into an Array
Number of elements unknown!
length = 0;
infile >> data;
while ((length < max_array_size) && ! infile.eof ( ))
{
   a[length] = data;
Example of while loop
   ++length;
   infile >> data;
}
 
Lesson 9.3

 



File Input with Known 
Number of Elements 
infile1 >> num_elem;
for (j = 0; j < num_elem; j++)
        {
         infile1 >> a[j];
        }
First line of file contains number 
of array elements.


File Input – Sentinel Value
Particular 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++)
Where –1 is the
      {
sentinel value.
       infile1 >> a[j];
       }


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

 


Arrays and Functions
Pass address of array to function instead of 
element values
Function declaration
– Data type and empty brackets     int[ ]

Function call
– Array name with no brackets       x

Function header
– Data type, name, and empty brackets    int x[ ]
Lesson 9.4


Passing Array Information
Three pieces of information 
– Size of single array element
Indicated by data type

– Address of array
Indicated by array name in function call


– Location to store array address
Indicated by identifier followed by brackets in 
function header

Lesson 9.4


General Form
Function return type
Type of values stored in array
Number of array elements

Declaration rtype function (type [ ], int);
Call
function (array, num);
Header

rtype function (type b[ ], int num_elem)
Function name
Type of second argument
Array name in calling function
b is identifier used to represent
num_elem used to represent number
array within function
of array elements in function

Lesson 9.4


Classes with Array Data Members

Automatically made accessible to public 
class member functions
Use enumeration to size data member 
arrays
– Comma­separated list of identifiers
– Identifier automatically assigned constant 
integer value
– Value assigned depends on order in 
enumeration list

Lesson 9.5


Enumeration
Keyword enum
Makes code more readable
Example:    
enum {sun = 1, mon, tues, wed, thur, fri, sat};
– Assigns integer constant 1 to sun, 2 to mon, etc.

Example of usage:  int day;
                                day = wed;
Lesson 9.5

Same as day = 4;


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

 


Arrays of Objects
Declared 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


Arrays of Objects
Good 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


×