Class notes:

SECTION 4- ONE-DIMENSIONAL ARRAYS

(ch. 12.1 only)


Introduction

-Suppose we wanted to read in 100 scores, find their average, and THEN process them to find out which ones were above/below average:

int s1,s2,s3,s4,s5,…,s99, s100;

cout << "Enter score #1 " << endl;

cin >> s1;

cout << "Enter score #2 " << endl;

cin >> s2;

cout << "Enter score #3 " << endl;

cin >> s3;

etc.

avg = (s1+s2+s3+…+s99+s100)/100;

if (s1 >avg)

cout << "Score 1 is above average\n";

else

cout << "Score 2 is below average\n";

etc.

WHEW! That's a lot of code and a lot of variables!

-what we need is some way to keep track of all scores as a group, yet also have access to them individually An array!

-Arrays are like general purpose string constructs: instead of a sequence of characters, an array is a sequence of ANY data type: integer, real, string(!), enumerated type, etc

-We access them via index, just like individual string characters.

-Attributes are same as strings: length, index from 0 to N, etc.

-BIG difference: arrays are fixed length and we must specify how many elements when we declare them

Declaring arrays:

Type

ArrayName[length]

-where type is any previously defined type (include enumerated type), which refers to the contents of the array (what kind of data it holds)

-ArrayName is any valid C++ identifier

-length is the number of elements in the array - if length is N, elements are numbered 0 to N-1

-e.g.,

int

Array1[10];

double

Array2[100];

char

Array3[17]; //NOT a string - fixed length!

Strings

Array4[50]; //holds 50 variable length strings!

Array1[4] = 42;

Array1[4]++;

Array2[99] = 3.14159;

Array3[1] = "hello"; //what's in the rest? '\0' and zeroes

Array4[50] = "This is a string";

-It is good programming practice to use named constants when defining the length of the array:

const int

Size = 100;

double

SomeArray[Size];

for (j=0; J<Size;j++)


-This makes maintenance easier, if size of array changes in future - only need to change the constant declaration

Initializing arrays

-Arrays can be initialized when declared:

const

size=10;

double

Array[size]={10,9,8,7,6,5,4,3,2,1};

-If you provide only part of values, the rest of the array is zeroed out (an uninitialized array is full of garbage)

Inputting values into an array (other than initializing)

-Array values must be input one element at a time, usually using a loop

-CANNOT assign one array to another - to copy, use a for loop

-When getting array values from user/file, be careful not to go beyond array bounds!

int n,i=0;

cout << "Enter a number, CTRL-Z to stop \n";

cin >> n;

while (i<ArraySize && !cin.eof()) //or !instream.eof()

{

Array1[i++] = n;

cout << "Enter a number, CTRL-Z to stop \n";

cin >> n;

}

-This protects from reading in too many values

-When done, 'I' holds actual number of values read in (the "working length" of the array

-won't always use full array, therefore, when processing arrays, usually must also always keep track of how many elements you are actually using (i.e, when passing array to function)

Outputting the values of an array

-Can't print entire array w/ << operator, must print element by element, using a loop:

for(I=0; I < size; I++)

cout << Array[I] << endl;

Arrays and functions

-First, an array is AUTOMATICALLY passed by reference, WITHOUT using the & !!

-In functions where we don't want to accidentally change the value, we can pass them as constant reference parameter, like we did with strings

-To make functions more generic, we can pass arrays in such a way that the function will work on an array of ANY size. We do this by using empty brackets, and passing a size variable for the function to use:

void SomeFunction(int SomeArray[], int Size)

{

something;

}

-example input function (reading #'s from a file):

void FillArray(int IntArray[], int& Length, fstream& Instr)

{

int n;

Length=0;

Instr >> n;

while(Length<Size && !Instr.eof()) //Size is global constant

{

IntArray[Length++] = n;

Instr >> n;

}

}

-Note that this function returns a filled array AND the "working length" of the array (in variable "Length")

-example output function (printing the array to a file):

void PrintArray(const int IntArray, int Length, fstream Outstr)

{

for (int j=0; j < Length; j++)

Outstr << IntArray[j] << endl;

}

-Note use of for loop, since we know the length

-In general, use while loop for array input (unless # of values is guaranteed), and use for loop for output, since length is known at that point

-In general, must pass two pieces of info to a function which process an array: the array itself, and the "working length" variable (unless array will always have set length, e.g., number of days in a week)

-write a function which copies one array into another

-write a function which returns the average of the values of a real array

-write a function which prints the even numbered elements of an array

-write a function which prints the even values in an array of integers

-write a function which prints an array in reverse order

-write a function which copies an array into another, in reverse order (w/o using an extra array)

for (I=0; I < length; I++)

A1[I] = A2[length-1-I];

Enumerated types and arrays

-It is often the case that we use enumerated types as the indices of an array, for readability purposes

-recall the Day type declaration:

enum Day {DayUnderflow = -1, //too-low error

Sunday, Monday, Tuesday, //0-2

Wednesday, Thursday, Friday, //3-5

Saturday, //6

NumDays, //7

DayOverflow=7}; //too-high error (also 7)

-with this, we can declare the following array:

double

HoursWorked[NumDays];

-Note that this array holds real numbers, not day types (that's different - see below)

-This allows us to use the days as subscripts, to enhance readability:

HoursWorked[Sunday] = 0.0;

if (HoursWorked[Saturday] > 0)

dosomething;

etc.

-We'd like to be able to do this to process the array:

Day d;

total=0;

for (d=Sunday; d <= Saturday; d++)

total+=HoursWorked[d];

to total the hours in the array, but remember! VC++ does not allow the ++ operator on enumerated types!!

-So, define an overloaded ++ operator, or define a Next() function (which we have for days)

-This usually is anticipated in the design of the enumerated type library, by including an overloaded ++ operator, or a Next() function, when the type is created in the library.

-Note the difference between the previous array declaration and this one:

Day

DayArray[7];

-This is a 7-element array, which contains values of day type

e.g.,

DayArray[1] = Sunday;

DayArray[2] = Next(Sunday);