• No results found

Arrays in C++ Lecture 5

N/A
N/A
Protected

Academic year: 2020

Share "Arrays in C++ Lecture 5"

Copied!
55
0
0

Loading.... (view fulltext now)

Full text

(1)

Arrays in C++

Lecture 5

(2)

Problem

■ Given 5 numbers, read them in and

calculate their average

■ THEN print out the ones that were

(3)

Data Structure Needed

■ Need some way to hold onto all the

individual data items after processing them

■ making individual identifiers x1, x2,

x3,... is not practical or flexible

■ the answer is to use an ARRAY

■ a data structure - bigger than an

(4)

an Array

■ you need a way to have many variables

all with the same name but distinguishable!

■ in math they do it by subscripts or

indexes

■ x

1, x2, x3 and so on

■ in programming languages, use syntax

(5)

C++ Arrays

■ An array is a consecutive group of

memory locations.

■ Each group is called an element of the

array.

■ The contents of each element are of the

same type.

■ Could be an array of int, double, char, …

■ We can refer to individual elements by

giving the position number (index) of the element in the array.

(6)

Array Usage

■ Powerful storage mechanism ■ Can issue command like:

■ "Do this to ith indexed variable"

where i is computed by program

■ "Display all elements of array score"

■ "Fill elements of array score from user input" ■ "Find highest value in array score"

(7)

Memory and Arrays int foo[6]; foo[0] foo[1] foo[5] 4 bytes

(8)

C++ Arrays start at 0 !!!!!!!

■ The first element is the 0th element!

■ If you declare an array of n elements,

the last one is number n-1.

■ If you try to access element number n it

(9)

Semantics

■ numbered from 0 to n-1 where n is the

number of elements

■ all elements of an array have the same

type

(10)

Array Subscripts

■ The element numbers are called

subscripts.

foo[i]

Array name

subscript

A subscript can be any integer expression: These are all valid subscripts:

(11)

Initialization

■ You can initialize an array when you

declare it (just like with variables):

int foo[5] = { 1,8,3,6,12};

double d[2] = { 0.707, 0.707};

(12)

Properties of an array

■ Homogeneous ■ Contiguous

■ Have random access to any element ■ Ordered (numbered from 0 to n-1)

■ Number of elements does not change -

(13)

Arrays of char are special

■ C++ provides a special way to deal with

arrays of characters:

char string1[] =

"RPI without PI is like meat without eat";

■ char arrays can be initialized with string

(14)

14

Declaration of an Array

■ The index is also called the subscript

■ In C++, the first array element always has

subscript 0, the second array element has subscript 1, etc.

■ The base address of an array is its beginning

(15)

Using a named constant

■ it is very common to use a named

constant to set the size of an array

■ const int SIZE = 15; ■ int arr[SIZE];

■ useful because it can be used to control

loops throughout program

■ easy to change if size of array needs to

(16)

Solution to problem

int ct = 0, n[5], total = 0; float average;

while (ct < 5) {

cout << "enter a number "; cin >> n[ct]; total = total + n[ct];

ct = ct + 1; }

(17)

Solution to problem - cont'd

average = total / 5; ct = 0; while (ct < 5) { if (n[ct] > average) cout << n[ct]; ct = ct + 1; }

(18)

the for loop

■ since you need a loop with a counter often

with an array, use a specialized one

■ syntax

■ for (initialization; condition; increment) body ■ as usual, body can be one statement or a

block of statements

■ initialization usually sets a counter to zero ■ condition tests counter for upper limit

(19)

Semantics of a for loop

■ initialization happens ONCE, at start of

loop execution

■ the condition is tested next ■ if the condition is true,

■ body is executed

■ increment is executed

■ then condition is tested again

■ if the condition is false,

(20)

Scope of counter in a for loop

■ if declare counter outside of the loop, it

has usual scope (body of the function)

■ can declare counter in header of loop

for (int i = 0; i < 5; i++)

■ then the scope is JUST the body of the

(21)

for and while loops are

equivalent

for (i = 0; i < 5; i++) { body } VERSUS i = 0; while (i < 5) { body i++; }

(22)

Initialization of arrays

■ int a[] = {1, 2, 9, 10}; // has 4

elements

■ int a[5] = {2, 5, 4, 1, -2, 5}; // error! ■ int a[5] = {2, 3}; // rest are zero

■ int a[5] = {0}; // all are zero

■ don't use this "zero initialization" with

strings! objects don't take well to being set to a zero

(23)

Watch out index out of range!

■ subscripts range from 0 to n-1

■ the compiler will NOT tell you if an

index goes out of that range - it cannot detect

■ can make very bad bugs

■ from just garbage values in your data to ■ crashing your computer to

(24)

24

Assigning Values to

Individual Array Elements

float temps[5]; int m = 4; // Allocates memory

temps[2] = 98.6; temps[3] = 101.2; temps[0] = 99.4;

temps[m] = temps[3] / 2.0; temps[1] = temps[3] - 1.2;

// What value is assigned?

temps[0] temps[1] temps[2] temps[3] temps[4]

7000 7004 7008 7012 7016

99.4 ? 98.6 101.2 50.6

(25)

25

What values are assigned?

float temps[5]; // Allocates memory

int m;

for (m = 0; m < 5; m++) {

temps[m] = 100.0 + m * 0.2 ; }

temps[0] temps[1] temps[2] temps[3] temps[4]

7000 7004 7008 7012 7016

(26)

26

Now what values are printed?

float temps[5]; // Allocates memory

int m; . . . . .

for (m = 4; m >= 0; m--) {

cout << temps[m] << endl; }

temps[0] temps[1] temps[2] temps[3] temps[4]

7000 7004 7008 7012 7016

(27)

Array Program Example:

(28)

Array Program Example:

(29)

Indexes

■ subscripts can be constants or variables

or expressions

■ if i is 5, a[i-1] refers to a[4] and a[i*2]

refers to a[10]

you can use i as a subscript at one

point in the program and j as a

subscript for the same array later - only the value of the variable matters

(30)

30

Variable Subscripts

float temps[5]; // Allocates memory

int m = 3;

. . . .

What is temps[m + 1] ? What is temps[m] + 1 ?

temps[0] temps[1] temps[2] temps[3] temps[4]

7000 7004 7008 7012 7016

(31)

Selection sort - 1-d array

Algorithm for the sort

1. find the maximum in the list

2. put it in the highest numbered

element by swapping it with the data that was at that location

3. repeat 1 and 2 for shorter unsorted list - not including highest numbered

location

(32)

Find the maximum in the list

// n is number of elements

max = a[0]; // value of largest element // seen so far

for (i = 1; i < n; i++) // note start at 1, not 0

if (max < a[i]) max = a[i];

// now max is value of largest element in list

(33)

Find the location of the max

max = 0; // max is now location of the max

for (i = 1; i < n; i++) if (a[max] < a[i])

(34)

Swap with highest numbered

element at right end of list is numbered n-1

temp = a[max]; a[max] = a[n-1]; a[n-1] = temp;

(35)

Find next largest element and

swap

max = 0;

for (i = 1; i < n-1; i++) // note n-1, not n if (a[max] < a[i]) max = i; temp = a[max]; a[max] = a[n-2]; a[n-2] = temp;

(36)

Arrays of Arrays

■ You can create an array of arrays:

int a[2][2];

for (int i=0;i<2;i++)

for (int j=0;j<2;j++) a[i][j] = i+j;

(37)

2-D Array: int A[3][4]

Col 0 Col 1 Col 2 Col 3

Row 0 A[0][0] A[0][1] A[0][2] A[0][3]

Row 1 A[1][0] A[1][1] A[1][2] A[1][3]

(38)

2-dimensional arrays

■ data sometimes has more structure to it

than just "a list"

■ has rows and columns

■ uses two subscripts to locate an item ■ syntax

■ int a[5][4]; // row then column

■ twenty elements, numbered from [0][0] to [4][3]

(39)

39

Two-Dimensional Array

A two-dimensional array is a collection of

components, all of the same type, structured in two dimensions, (referred to as rows and columns)

Individual components are accessed by a pair

of indexes representing the component’s position in each dimension

(40)

40 [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10][11] 66 64 72 78 85 90 99 105 98 90 88 80 row 2, col 7 might be Arizona’s high for August

EXAMPLE -- Array for monthly high temperatures for all 50 states

const int NUM_STATES = 50; const int NUM_MONTHS = 12;

int stateHighs[NUM_STATES][NUM_MONTHS]; [0] [1] [2] . . stateHighs[2][7] . [48] [49]

(41)

Rows Of A 2D Array

a[0][0] a[0][1] a[0][2] a[0][3] row 0

a[1][0] a[1][1] a[1][2] a[1][3] row 1

a[2][0] a[2][1] a[2][2] a[2][3] row 2

(42)

Columns Of A 2D Array

a[0][0] a[0][1] a[0][2] a[0][3] a[1][0] a[1][1] a[1][2] a[1][3] a[2][0] a[2][1] a[2][2] a[2][3]

(43)

Processing a 2-d array by rows

finding the total for the first row for (i = 0; i < 5; i++)

total = total + a[0][i];

finding the total for the second row for (i = 0; i < 5; i++)

(44)

Processing a 2-d array by rows

total for ALL elements by adding first row, then second row, etc.

for (i = 0; i < 5; i++)

for (j = 0; j < 4; j++) total = total + a[i][j];

(45)

Processing a 2-d array by

columns

total for ALL elements by adding first column, second column, etc.

for (j = 0; j < 4; j++) for (i = 0; i < 5; i++)

(46)

46

Finding the average high temperature for Arizona

// assumes Arizona’s data is in row 2 int total = 0;

int month; int average;

for (month = 0; month < NUM_MONTHS; month ++)

total = total + stateHighs[2][month]; average = int (total / 12.0 + 0.5);

average

(47)

Passing an array as an

argument

■ by default arrays are passed by

reference, do not need an &

■ int fun1 (int arr[]);

■ prototype and header

■ nothing between the [] !

■ call the function as

(48)

Arrays versus Files

■ Arrays are usually smaller than files ■ Arrays are faster than files

■ Arrays are temporary, in RAM - files are

permanent on secondary storage

■ Arrays can do random or sequential,

(49)

Passing a 2-d array as a

argument

■ a little bit different from 1-d arrays ■ int fun1 (int arr [][SIZE]);

■ only first subscript is left blank

■ second (and more if higher dimensions) subscripts have to have values

■ called as x = fun1 (myarr);

■ where myarr is declared as int myarr[5][SIZE];

(50)

50

Declaring Multidimensional Arrays

Example of three-dimensional array

const NUM_DEPTS = 5;

// mens, womens, childrens, electronics, furniture

const NUM_MONTHS = 12;

const NUM_STORES = 3; // White Marsh, Owings Mills, Towson

int monthlySales[NUM_DEPTS][NUM_MONTHS][NUM_STORES];

(51)

51

const NUM_DEPTS = 5;

// mens, womens, childrens, electronics, furniture

const NUM_MONTHS = 12;

const NUM_STORES = 3; // White Marsh, Owings Mills, Towson

int monthlySales[NUM_DEPTS][NUM_MONTHS][NUM_STORES];

monthlySales[3][7][0]

sales for electronics in August at White Marsh

12 MONTHS columns 5 DEPTS rows

3 STORES sheets

(52)

Parallel arrays

■ Sometimes you have data of different

types that are associated with each other

■ like name (string) and GPA (float) or

name (string) and letter grade (char)

■ cannot store them in the same array ■ so use two different arrays "side by

(53)

Parallel arrays, cont'd

■ for (i = 0; i < 5; i ++)

cin >> name[i] >> gpa[i];

■ logically the name in position i

corresponds to the gpa in position i

■ nothing in the syntax forces this to be

true, you just have to program it to be so

(54)

54

Parallel Arrays

Parallel arrays are two or more arrays that have the

same index range and whose elements contain related information, possibly of different data types

EXAMPLE

const int SIZE 50;

int idNumber[SIZE];

(55)

55

const int SIZE 50;

int idNumber[SIZE]; // Parallel arrays hold float hourlyWage[SIZE]; // Related information

idNumber[0] 4562 hourlyWage[0] 9.68 idNumber[1] 1235 hourlyWage[1] 45.75 idNumber[2] 6278 hourlyWage[2] 12.71 . . . . . . . . . . . . idNumber[48] 8754 hourlyWage[48] 67.96 idNumber[49] 2460 hourlyWage[49] 8.97

References

Related documents