arrays one-dimensional initialize & display arrays as arguments part i
TRANSCRIPT
Structured Data Type - Array
An array is a collection of data storage locations, each of which holds the same type of data. Each storage location is called an element of the array.
An homogeneous aggregate of elements
Each element is referred to as an indexed or subscripted variable.
Array Declaration
SyntaxdataType arrayName [[ ConstIntExpression ]]
The number of elements in an array is stated within square brackets, [ ][ ].
Examplesdouble angle [4]; const int POLY = 8;int testScore [12]; double angle [POLY]; char password [8];
Array Storage
Each array has sufficient memory reserved to hold the number of data items of the given type.
Initializing an array sets up the address of the first element. Addresses of all other elements are offsets from the starting address.
Array elements occupy contiguous memory locations.
Array Element Access
Syntax
arrayName [ indexExpression ]
Program access to each of the array elements is by referring to an offset from the array name. Array elements are counted beginning with zero.
A[0] => add zero to the address of A (1st element)
A[3] => add (3 * width of element) to the address of A (4th element)
Array Element Access
double angle[4]; // declaration
Exampleangle [0] = 6.21;angle [1] = 15.89;angle [2] = 7.5;angle [3] = -45.7;
angle sub zero = 6.21angle sub one = 15.89angle sub two = 7.5angle sub three = -45.7
* * *
6.21
15.89
7.5
-45.7
angle3
--Mathematical notation
Using Array Elements
a write the contents of an array element:cout << angle[2]; // the third element
a assign values to an array element:cin >> angle[3]; // the fourth element angle[2] = pow(axis,4); // the third element
a use it as a parameter:y = sqrt(angle[0]); // the first element
a use it in an expression:x = 2.5 * angle[1] + 64; // the second
element
* * * *
Declare an Array
float myArray[100];
Want to reset myArray to zerosmyArray = 0.0; // works in some languages
In C++, the array name is a pointer to an address in memory
myArray is an address in memory
An attempt to assign a float to a pointer to a float
Array Component Access
for(indexindex=0; index index < arraySize; indexindex++)myArray[indexindex] = 0.0;
100
* *
Zero out an entire array. (Initialize every element to 0.0.)
For loops were “made for” arrays
You always know how many times the loop will execute – once for each element
Off Set
memoryaddresses
starting address
off set by one unit
off set by two units
off set by three units
[ 0 ]
[ 1 ]
[ 2 ]
[ 3]
@#$
@#$
angle int angle[4];
Out-of-Bounds Array Index
memoryaddresses
angle[4] = 135;
cout << angle[5];
[ 0 ]
[ 1 ]
[ 2 ]
[ 3]
@#$
@#$
angle
grade
score
Overwrites value in memory without warning!
Declare an Array
Syntaxtype arrayName[index];
Exampledouble dailyHigh[31] ;
int quizGrade[29] ;
char YSUID[9] ;
*
Initialize an Array Element
SyntaxarrayName[index] = value;
ExampledailyHigh[18] = 16.7;
quizGrade[2] = 15;
YSUID[3] = ‘7’;
*
Initialize an Array at Declaration Time
double angle[4] = {16.21, 15.89, 7.5, -45.7};
double convert[5] = {.64, .89, .76, .83, .65};
int scores[12] = {210, 198, 203, 188, 200, 224, 220, 217, 211, 194, 197, 189};
double iona[8] = {0.0}; // fill with zeros*
Initialize an Array - Variations
int scores[ ] = {210, 198, 203, 188, 200, 224, 220, 217, 211, 194, 197, 189};
char name1[4] = {‘Z’, ‘o’, ‘l’, ‘a’};
char name2[4] = “Zola”; // no braces or ,char phrase [ ] = “Hello World”;
* *
Space for 12 integers
Compiler will allocate 12 bytesWill not compile: “init string too long”
5
Character Arrays - \0
char name1[4] = {‘Z’, ‘o’, ‘l’, ‘a’};
char name2[5] = “Zola”; // no braces or ,needs 5 slots to have space for the end
of string character, \0
char phrase [ ] = “Hello World”;
* *
Compiler will allocate 12 bytes
Sequencing Through an ArrayUse the for statement to sequence through an array.Assume an array with 7 grades in it…Total the contents of an array:
sum = 0;for (index=0; index < 7; index++)
sum += grades[index];
char name1[4] = {‘Z’, ‘o’, ‘l’, ‘a’};Print out an array
for (i = 0, i < 4 , i++) cout << name1[i]; // prints Zola
Loading an Array – with cin
double grade[10];
int index;
for(index=0; index < 10; index++){
cout<<“Enter a grade “;
cin >> grade[index];
}
75 85 65 95 77 88 68 93 59 90
grade0
9
Finding the Max/Min Value
• Set the max or min to element zero.
• Use a for loop to cycle through the array.
• Compare each element to the max/min.
• If necessary, assign a new value to max/min.
How would you do this?
*
Finding the Maximum Value
double find_max(int temp[30]){
int max = temp[0]; //only max seen thus far
for(int index=1; index < 30; index++)if (temp[index] > max)
max = temp[index];return (max);
}
*
If the current temp[ ] is bigger than the max seen thus far. Remember this one!
Finding the Minimum Value
double find_min(int temp[30]){
int min = temp[0]; // minimum thus far
for(int index = 1; index < 30; index++)if (temp[index] << min)
min = temp[index];return ( min );
}
*
Aggregate Assignment - NOT!
There are no aggregate assignments with arrays. That is, you may not assign one array to another.
int x[5] = {11, 22, 33, 44, 55};
int y[5];
y = x; y[ ] = x[ ];
for (i=0;i<5;i++)
y[i] = x[i];
Arrays as Arguments
double find_max(int temp[ ]temp[ ]){
max = temp[0];
for(index = 1; index < 30; index++)if (temp[index] > max)
max = temp[index];return max;
}
double find_max(int temp[ ]temp[ ])
*
Leave blank or use constant
Passing an Array or Elements
find_max(temptemp); // whole array, no [ ]
inventory(priceprice, quantityquantity, amountamount); // 3 arrays
words(cupletcuplet);
find_max(temp[3]temp[3]);
inventory(priceprice, quantity[4]quantity[4], amount[12]amount[12]);
words(cuplet[0]cuplet[0]);
*
Elements of an array
Comparing Arrays as Arguments to Simple Data Types
formal parameterformal parameter formal parameterformal parameterdeclaration fordeclaration for declaration fordeclaration for
parameterparameter Pass-by-ValuePass-by-Value Pass-by-ReferencePass-by-Reference
simple var. int cost int& pricearray impossible int myArray[ ]
array const int source[ ]Keeps function from changing values in the array
Passing an Array Element
Follows the rules for the type of an element in the array
int cntA[1111];cntA[33] is an int and is treated as any
other int when used as an actual argument.
cntA refers to the entire array. It is the address of the array or a pointer to the array.
1-D Array Review
An array is a structured data type
1st element is “arrayName subzero”
Array Declarationint myArray [9];
Array Initializationint myArray [9 ] = { 9, 9, 9, 8, 7, 6, 5, 4,
3};
Array Element ReferencemyArray [3]; // value = 8 *
99
const int MAXELS = 9;
Use everywhere instead of the literal