cs 1400 march 5, 2007

34
CS 1400 March 5, 2007 Chapter 6 ARRAYS

Upload: xia

Post on 14-Jan-2016

23 views

Category:

Documents


0 download

DESCRIPTION

CS 1400 March 5, 2007. Chapter 6 ARRAYS. Array variables. Simple variables can hold single values int x;// x can hold one integer float y; // y can hold one float Array variables can hold multiple values int z[5];// z can hold 5 integers float w[3];// w can hold 3 floats. x. y. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: CS 1400 March 5, 2007

CS 1400March 5, 2007

Chapter 6 ARRAYS

Page 2: CS 1400 March 5, 2007

Array variables• Simple variables can hold single values

int x; // x can hold one integer

float y; // y can hold one float

• Array variables can hold multiple valuesint z[5]; // z can hold 5 integers

float w[3]; // w can hold 3 floats

x y z w

Page 3: CS 1400 March 5, 2007

Array Access…

• Individual cells of an array variable are accessed using an index:z[2] = 55; z[3] = 921; z[4] = z[2]+1;

• Cells of an array are numbered beginning with zero!

z

0 1 2 3 4

55 921 56

Page 4: CS 1400 March 5, 2007

Array Indexes…• Array indexes can also be ordinal

variables (integers)

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

z[n] = n*10;

z

0 1 2 3 4

20 30 400 10

Page 5: CS 1400 March 5, 2007

Array initialization…• Like simple variables, array variables can be

intialized when declared: int z[5] = {11, 22, 33, 44, 55};

(If insufficient initializing constants are given, the rest default to zero.)

float w[3] = {1.0};

z

0 1 2 3 4

33 44 5511 22

1.0 0.0 0.0

w

0 1 3

Page 6: CS 1400 March 5, 2007

Array Examples• Declaration examples;

int costs[10];

float rates[100];

int ages [n]; Can’t declare size with a variable!• Initialization examples;

int costs [5] = {99, 88, 77, 66, 55};

float rates [100] = {1.0};• References examples;

costs[n] = 21;

cout << rates[5];

ages[n]++; how is this different from ages[n++]?

Page 7: CS 1400 March 5, 2007

Array indexes…

• Indexes may be constants (integers) or ordinal variables• Indexes may also be simple integer expressions;

cout << costs[n+2];• There is no array bounds checking.• Array cell indexes always start at 0 (zero) • In an executable statement, only array cells may be

referenced

costs = rates * 2;

exception: char arrays holding words or strings

exception: passing an array reference to a function

Page 8: CS 1400 March 5, 2007

No bounds checking?int cost[5];

for (int n=0; n<7; n++)

cin >> cost[n]; // a long walk on a short pier!!

0 1 2 3 4 5 6 …

cost

These cells belong to cost Who do these belong to??

other variables?

program instructions?

Page 9: CS 1400 March 5, 2007

char arrays…• Note that char arrays are a special case!

– can be input or output as “strings”char word[30];cin >> word;

– can also used as arraysif (word[0] == ‘a’)

word[0] = ‘A’;cout << word[0] << word[5];

– can be inialized with strings or with characterschar name[30] = “Bobby”;char name2[30] = {‘B’, ‘o’, ‘b’, ‘b’, ‘y’, ‘\0’};

Page 10: CS 1400 March 5, 2007

Example: test grading

• Write a program to grade a test. A test has five (5) numeric answers.– assume: the test key is in key.txt– assume: the test is in answers.txt

Example inputs:

key.txt: 21 14 7 9 18

answers.txt: Fred 21 15 7 9 17

Example output: student: Fred score 3

Page 11: CS 1400 March 5, 2007

Pseudocode…

1. Read in the correct answers array from “key.txt”

2. Read in student’s answers from “answers.txt”

3. Compare against correct answers and determine score

4. Output student score

Page 12: CS 1400 March 5, 2007

1. Read in correct answers

int key[5];

ifstream fin_key;

fin_key.open (“e:\\key.txt”);

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

fin_key >> key[n];

Page 13: CS 1400 March 5, 2007

2. Read in student’s answers

int answers[5];

char name[30];

ifstream fin_ans;

fin_ans.open (“e:\\answers.txt”);

cin >> name;

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

fin_ans >> answers[n];

Page 14: CS 1400 March 5, 2007

3. Compare…

int score = 0;

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

if (answers[n] == key[n])

score++;

4. Output score

cout << “score is “ << score;

Page 15: CS 1400 March 5, 2007

int main(){ int key[5], answers[5], score = 0;

char name[30];ifstream fin_key, fin_ans;fin_key.open (“e:\\key.txt”);for (int n=0; n<5; n++)

fin_key >> key[n];fin_ans.open (“e:\\answers.txt”);fin >> name;for (int n=0; n<5; n++)

fin_ans >> answers[n];for (int n=0; n<5; n++)

if (answers[n] == key[n])score++;

cout << “score for “ << name << “ is “ << score << endl;}

Page 16: CS 1400 March 5, 2007

Linear Search• Search array list with size elements: find

the position of variable value.bool found = false;int position = -1;for (int n=0; n<size && !found; n++){ if (list[n] == value) { position = n; found = true; }}

Page 17: CS 1400 March 5, 2007

Example using a linear search

• Suppose a disk file contains a database of 100 part numbers and part costs:inventory.txt: part cost

413 121.78

214 22.98

456 234.56

786 9.56

177 86.99

356 198.22

Page 18: CS 1400 March 5, 2007

POS terminal program

• Write a program to query the user for a part number and a quantity for an order. Calculate and display the total price of the order (including 20% markup and 6.5% sales tax)

Enter part number and quantity: 177 32

Order total (including tax): $ 3557.54

Page 19: CS 1400 March 5, 2007

Pseudocode…

1. read database into parallel arrays.

2. query user for part number and quantity

3. use a linear search to find associated cost

4. calculate order total

5. display

Page 20: CS 1400 March 5, 2007

1. Read database into parallel arrays

int parts[100]; float costs[100];

char word[30];

ifstream fin;

fin.open (“inventory.txt”);

fin >> word >> word; // skip over titles

for (int n=0; n<100; n++)

cin >> parts[n] >> costs[n];

Page 21: CS 1400 March 5, 2007

2. Query user for part number and quantity

int partnumber, quantity;

cout << “Enter part number and quantity: “;

cin >> partnumber >> quantity;

Page 22: CS 1400 March 5, 2007

3. Linear search…

bool found = false;

float thiscost = -1.0;

for (int n=0; n<100 && !found; n++)

{ if (partnumber == parts[n])

{ found = true;

thiscost = costs[n];

}

}

Page 23: CS 1400 March 5, 2007

4. Calculate total

float total;

total = quantity * thiscost * 1.2 * 1.065;

5. Display

cout << fixed << setprecision(2);

cout << “Order total (including tax): $ “ << total;

Page 24: CS 1400 March 5, 2007

Passing Arrays to Functions…

• Arrays (of any size) can be passed to functions by using just the array name as a function argument.

float ages[100];

float weights[200]

MyFunc(ages, 100);

MyFunc(weights, 200);

Page 25: CS 1400 March 5, 2007

Arrays as function parameters• Array parameters are declared with empty

brackets;

• A function with an array parameter may need to know the size of the array or the number of elements to be considered;

void MyFunc (float array[ ], int size);

Array parameters are always reference parameters!

Page 26: CS 1400 March 5, 2007

Examples;

• A function to find the maximum value of an array

• A function to calculate the average value of an array

• A function to count the number of negative values in an array

Page 27: CS 1400 March 5, 2007

Linear Search as a function…int LinearSearch (int list[], int size, int value){ bool found = false; int position = -1; for (int n=0; n<size && !found; n++) { if (list[n] == value) { position = n; found = true; } } return position;}

Page 28: CS 1400 March 5, 2007

Multi-dimension arrays

• Arrays can contain sub-arrays. An array of rows of cells is a 2-d table:Consider a table of chair prices;

67.83 61.99 59.70

44.56 42.68 39.98

89.99 83.56 80.15

55.67 51.34 49.99

Covering material

Style

0 1 2

0

1

2

3

Page 29: CS 1400 March 5, 2007

declaration with initialization…float chair_costs [4] [3] =

{{ 67.83, 61.99, 59.70 }, { 44.56, 42.68, 39.98 }, { 89.99, 83.56, 80.15 },

{ 55.67, 51.34, 49.99 }};

…int style, covering;cout << “enter a style and covering: “;cin >> style >> covering;cout << “cost is: “ << chair_costs[style] [covering];

Page 30: CS 1400 March 5, 2007

Passing multi-dimensional arrays

• When passing a multi-dim. array, all but the first dimension of the corresponding parameter must be stated explicitlyin main:

cout << SumChairCosts (chair_costs) << endl;

Function:float SumChairCosts (costs[ ] [3]){ float sum = 0; for (int row=0; row<4; row++) for (int col=0; col<3; col++)

sum += costs[row][col]; return sum}

Page 31: CS 1400 March 5, 2007

Higher dimensioned arrays are possible, but rarely used

• Consider a table of chairs – there are 4 styles– each style has 3 coverings– each covering has 5 colors– each color has 7 shades;

float chair_costs [4] [3] [5] [7];

int style, covering, color, shade;

cout << “enter a style, covering, color and shade: “;

cin >> style >> covering >> color >> shade;

cout << “cost is: “ << chair_costs[style][covering][color][shade];

Page 32: CS 1400 March 5, 2007

2-d char arrays

• Since strings are stored in arrays of char, a 2-d char array is an array of strings!

char names[5][10] = {“Fred”, “Jane”, “Billy”, “Annie”, “Jason”}; cout << names[n] << endl; // refers to row n or string ncout << names[n][m] << endl; // refers to char in row n, cell m

for (int thisname = 0; thisname<5; thisname++) cin >> names[thisname]; // input 5 new names

Page 33: CS 1400 March 5, 2007

Common Errors…

• Attempting to copy one array into another with a single assignment statement;

• Taking a long walk on a short pier;

int array1[10], array2[10];array1 = array2; // illegal!!

int array[10];for (int n=0; n<=10; n++) // illegal!! cin >> array[n];

Page 34: CS 1400 March 5, 2007

Interesting questions…

• Can an array have different kinds of cells?

• Can an array size be changed while a program is running?

• Can each row of a 2-d array have a different number of cells?– not yet…