Download - Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.

Transcript
Page 1: Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.

Arrays

• Hanly - Chapter 7

• Friedman-Koffman - Chapter 9

Page 2: Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.

3/13/02

• Program 4 questions?– revised test1 and my version of the program– program should always process at least one

customer

• Program 6 (and HW2) may be done by two people working together

Page 3: Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.

2

9.1 The Array Data Type• Array collection of elements with a common name

– Entire array is referenced through the name

• Array elements are of the same type — the base type– Base type can be any fundamental, library-

defined, or programmer -defined type• For now: arrays are static - they have a fixed

number of elements

Page 4: Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.

4

Array Elements• Individual elements of the array are referenced by

sub_scripting the group name– Subscripts are denoted as expressions within

brackets: [ ]– The index type is integer and the index range

must be 0 ... n-1• where n is the number of elements in the array

Page 5: Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.

6

Array Declaration

Type ofvalues in

list

BaseType Id [ SizeExp ] ;

Nameof list

Bracketedconstantexpressionindicatingnumber ofelements in

list

Page 6: Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.

7

Sample Declarations

• Supposeconst int N = 20;

const int M = 40;

const int MaxStringSize = 80;

const int MaxListSize = 1000;

Page 7: Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.

8

Sample Declarations

• Then the following are all correct array declarations.int A[10];

char B[MaxStringSize];

float C[M*N];

int Values[MaxListSize];

Rational D[N-15];

Page 8: Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.

Array Initialization

• An array can be initialized at the time it is declaredchar grades[5] = {'A', 'B', 'C', 'D', 'F'};

int primes[] = {1, 2, 3, 5, 7, 11, 13, 17, 19, 23}

• if values provided do not fill the array, remainder of elements will be 0double x[10] = {1.5, 2.5, 3.5, 4.5, 5.5}

Page 9: Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.

9

Subscripting• Suppose

int A[10]; // array of 10 ints

• To access an individual element we must apply a subscript to array name A– A subscript is a bracketed expression

• The expression in the brackets is known as the index

– First element of A has index 0A[0]

Page 10: Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.

10

Subscripting– Second element of A has index 1, and so on

A[1]– Last element has an index one less than the size

of the array

A[9]

• Incorrect indexing is a common error– be careful not to index past the end of the array

Page 11: Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.

11

Array Elements

• Supposeint A[10]; // array of 10 uninitialized ints

• To access an individual element we must apply a subscript to array name A

-- -- ----AA[4] A[5] A[6]A[3]A[0] A[2] A[8] A[9]A[7]A[1]

-- -- ---- -- --

Page 12: Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.

12

Array Element Manipulation• Given the following:

int i = 7, j = 2, k = 4;A[0] = 1;A[i] = 5;A[j] = A[i] + 3;A[j+1] = A[i] + A[0];A[A[j]] = 12;

Page 13: Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.

13

Array Element Manipulation

cin >> A[k]; // where the next input value is 3

-- 8 61AA[4] A[5] A[6]A[3]A[0] A[2] A[8] A[9]A[7]A[1]

-- -- 53 --12

Page 14: Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.

Array Processing

• None of the operators are defined for an array– << >> arithmetic comparison

• To do the same thing to every element in an array, use a loop

Page 15: Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.

14

Inputting Into An Array int A[MaxListSize];

int n = 0;

int CurrentInput;

while((n < MaxListSize) && (cin >> CurrentInput))

{

A[n] = CurrentInput;

++n;

}

Page 16: Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.

15

Displaying An Array

// List A of n elements has

// already been set

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

{cout << A[i] << " ";

}

cout << endl;

Page 17: Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.

Partially filled arrays

• You don't have to use all the elements of an array– don't always know how many elements you will

need– declare array big enough to handle all cases

• it is your job to keep track of how many elements are valid

Page 18: Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.

3/15/01

• HW 2: Planning for program 6– you may do this in pairs– look at P6 handout for ideas– this is a planning exercise - you are not writing

code

• P5 - start thinking about how to organize the main playing loop of a Yahtzee game

Page 19: Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.

Cheating

• making copies of other students programs is NOT appropriate behavior

• I will be comparing all Program 4 submissions to check for copying

• Acknowledge anyone that you get help from in your readme

Page 20: Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.

17

Access to Array Elements

• Sequential Access– Process elements in sequential order starting

with the first

• Random Access– you can access elements in random order

Page 21: Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.

23

9.3 Array Elements

• Use <, ==, >, +, - to test and modify array elements

• At times it might benefit you to pass an entire array to a function

• Can pass array elements to functions– actual function callswap (s[3], s[5]);

Page 22: Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.

24

swap.cpp

// FILE: Exchange.cpp// Exchanges two type float values

void exchange (float& a1, float& a2){ float temp;

temp = a1; a1 = a2; a2 = temp;}

Page 23: Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.

25

Arrays as Function Arguments• Arrays are always passed by reference

– Passing the array address– contents can be changed

• Points to remember– function definition needs only [] to indicate

that the actual argument is an array– You can use the reserved word const to

prevent the contents of an array from being changed

Page 24: Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.

30

9.4 Reading Part of an Array

• Sometimes it is difficult to know how many elements will be in an array

• Scores example– 150 students– 200 students

• Always allocate enough space at compile time

• Remember to start with index [0]

Page 25: Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.

37

9.5 Searching and Sorting Arrays

• Look at 2 common array problems– Searching– Sorting

• How do we go about finding the smallest number in an array?– Assume 1st is smallest and save its position– Look for one smaller – If you locate one smaller save its position

Page 26: Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.

43

Linear Search

• The idea of a linear search is to walk through the entire until a target value is located

• If the target is not located some type of indicator needs to be returned

Page 27: Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.

46

Sorting in Ascending OrderSelection Sort

• Idea of the selection sort is to locate the smallest value in the array

• Then switch positions of this value and that in position [0]

• We then increment the index and look again for the next smallest value and swap

• Continue until sorted

Page 28: Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.

Section 1 3/18/02

Page 29: Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.

character arrays

• arrays can have any base type

• char arrays are useful for storing text

• C used a char array for strings– use null character to designate the end of the

string

• C++ has a string class

Page 30: Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.

literal strings

• A literal string constant is a sequence of zero or more characters enclosed in double quotes

"Are you aware?\n"• Individual characters of string are stored in

consecutive memory locations• The null character ('\0') is appended to strings so

that the compiler knows where in memory strings ends

Page 31: Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.

C-style strings

• array of char with a null character as the last element– null character has ASCII code 0– '\0'

'w' 'o' 'r' 'd' '\0'

operators = and == not defined for C-style strings

Page 32: Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.

Declaring and initializing

• Declaring uninitializedchar cstr[15];

• Declaration with initializationchar letters[] = "abcde";char grades[] = {'A', 'B', 'C', 'D', 'F', '\0'}char notString[] = {'A', 'B', 'C', 'D',}

• In first case above, the null character is appended for you

Page 33: Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.

string.h

int strlen( char[]) number of characters in array; doesn't count '\0'

void strcpy( char[], char[])

copy one C-style string to another

int strcmp( char[] char[]) compare two C-style strings

void strcat( char[], char[]) append one C-style string to another

Page 34: Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.

length vs number of elements

char word = "word";

• word has 5 elements

• BUT strlen( word) = 4

Page 35: Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.

assigning values

• NOT ALLOWEDchar a[] = "stuff", b[];

b = a;

• How do you do this?strcpy( b, a);

Now b also contains "stuff"

Page 36: Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.

comparing C-style strings

• == not defined for strings– use strcmpstrcmp( a, b)

• returns 0 if the strings are the same• returns a number >0 if a comes after b

lexicographically• returns a number < 0 if a comes before b

Page 37: Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.

reading strings

char a[10];cin >> a;

• whitespace delimited

• to read multiple words, use getlncin.getline( a, 10);

the number is the number of elements in the array

Page 38: Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.

concatenating C-style strings

char str1[]="cat", str2[]="top";

strcat(str2, str1);

after this code has executed, str2 will contain "topcat"

Page 39: Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.

42

C++ string class

• library is string (no .h)

• declaration and initialization

Page 40: Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.

string Class

#include <string>

• Various operations on strings are defined– assignment with =– comparison with ==– concatenation with +, +=– length() function returns the string length– c_str() returns a C-style string as const

Page 41: Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.

16

Remember• Arrays are always passed by reference• Can use const if array elements are not to

be modified• You do not need to include the array size

within the brackets when defining an array parameter

• Initialize array with 0 or some other known value

Page 42: Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.

65

9.9 Common Programming Errors

• Watch non int subscripts (ASCII value)• Enumerated types can be used• Out of range errors

– C++ no range error checking

• Lack of subscript to gain access• Subscript reference to non-array variable• Type mixing when using with functions• Initialization of arrays

Page 43: Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.

66

Common Programming Errors

• No prefix to reference a struct member

• Incorrect prefix reference to a struct member

• Missing ; following definition of struct

• Initialization of struct members