Arrays

36
Arrays One-Dimensional initialize & display Arrays as Arguments Part I

description

Arrays. One-Dimensional initialize & display Arrays as Arguments Part I. char, int, float, double. array, struct, union, class. Data Types. simple or atomic structured. * *. Structured Data Type - Array. - PowerPoint PPT Presentation

Transcript of Arrays

Page 1: Arrays

Arrays

One-Dimensionalinitialize & display

Arrays as Arguments

Part I

Page 2: Arrays

Data Types

a simple or atomic

a structured

* *

char, int, float, double

array, struct, union, class

Page 3: Arrays
Page 4: Arrays

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.

Page 5: Arrays
Page 6: Arrays
Page 7: Arrays
Page 8: Arrays
Page 9: Arrays

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];

Page 10: Arrays

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.

Page 11: Arrays

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)

Page 12: Arrays

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

Page 13: Arrays

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

* * * *

Page 14: Arrays

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

Page 15: Arrays

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

Page 16: Arrays

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];

Page 17: Arrays

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!

Page 18: Arrays

Declare an Array

Syntaxtype arrayName[index];

Exampledouble dailyHigh[31] ;

int quizGrade[29] ;

char YSUID[9] ;

*

Page 19: Arrays

Initialize an Array Element

SyntaxarrayName[index] = value;

ExampledailyHigh[18] = 16.7;

quizGrade[2] = 15;

YSUID[3] = ‘7’;

*

Page 20: Arrays

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*

Page 21: Arrays

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

Page 22: Arrays

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

Page 23: Arrays

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

Page 24: Arrays

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

Page 25: Arrays

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?

*

Page 26: Arrays

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!

Page 27: Arrays

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 );

}

*

Page 28: Arrays

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];

Page 29: Arrays

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

Page 30: Arrays

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

Page 31: Arrays

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

Page 32: Arrays

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.

Page 33: Arrays

                                                                                          

      

                                              

Slide 39 of 55

Page 34: Arrays

                                                                                          

      

                                              

Slide 40 of 55

Page 35: Arrays

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

Page 36: Arrays

1-D Array Review

Arrays are always passed by reference, unless const added to the formal parameter.

Array in a Function Prototypevoid myFunction(int [9]);

Array in a Function CallmyFunction(myArray);

Array in a Function Headervoid myFunction(int anyArrayName[9])

optional