Title: Arrays
1Arrays
- Hanly - Chapter 7
- Friedman-Koffman - Chapter 9
23/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
39.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
2
4Array 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
4
5Array Declaration
6
6Sample Declarations
- Suppose
- const int N 20
- const int M 40
- const int MaxStringSize 80
- const int MaxListSize 1000
7
7Sample Declarations
- Then the following are all correct array
declarations. - int A10
- char BMaxStringSize
- float CMN
- int ValuesMaxListSize
- Rational DN-15
8
8Array Initialization
- An array can be initialized at the time it is
declared - char grades5 '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 0 - double x10 1.5, 2.5, 3.5, 4.5, 5.5
9Subscripting
- Suppose
- int A10 // 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 0
- A0
9
10Subscripting
- Second element of A has index 1, and so on
- A1
- Last element has an index one less than the size
of the array - A9
- Incorrect indexing is a common error
- be careful not to index past the end of the array
10
11Array Elements
- Suppose
- int A10 // array of 10 uninitialized ints
- To access an individual element we must apply a
subscript to array name A
11
12Array Element Manipulation
- Given the following
- int i 7, j 2, k 4
- A0 1
- Ai 5
- Aj Ai 3
- Aj1 Ai A0
- AAj 12
12
13Array Element Manipulation
- cin gtgt Ak // where the next input value is 3
13
14Array Processing
- None of the operators are defined for an array
- ltlt gtgt arithmetic comparison
- To do the same thing to every element in an
array, use a loop
15Inputting Into An Array
- int AMaxListSize
- int n 0
- int CurrentInput
- while((n lt MaxListSize) (cin gtgt
CurrentInput)) -
- An CurrentInput
- n
14
16Displaying An Array
- // List A of n elements has
- // already been set
- for (int i 0 i lt n i)
-
- cout ltlt Ai ltlt " "
-
- cout ltlt endl
15
17Partially 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
183/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
19Cheating
- 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
20Access to Array Elements
- Sequential Access
- Process elements in sequential order starting
with the first - Random Access
- you can access elements in random order
17
219.3 Array Elements
- Use lt, , gt, , - 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 call
- swap (s3, s5)
23
22swap.cpp
- // FILE Exchange.cpp
- // Exchanges two type float values
- void exchange (float a1, float a2)
-
- float temp
- temp a1
- a1 a2
- a2 temp
-
24
23Arrays 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
25
249.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
30
259.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
37
26Linear 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
43
27Sorting 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
46
28Section 1 3/18/02
29character 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
30literal 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
31C-style strings
- array of char with a null character as the last
element - null character has ASCII code 0
- '\0'
operators and not defined for C-style strings
32Declaring and initializing
- Declaring uninitialized
- char cstr15
- Declaration with initialization
- char 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
33string.h
34length vs number of elements
- char word "word"
- word has 5 elements
- BUT strlen( word) 4
35assigning values
- NOT ALLOWED
- char a "stuff", b
- b a
- How do you do this?
- strcpy( b, a)
- Now b also contains "stuff"
36comparing C-style strings
- not defined for strings
- use strcmp
- strcmp( a, b)
- returns 0 if the strings are the same
- returns a number gt0 if a comes after b
lexicographically - returns a number lt 0 if a comes before b
37reading strings
- char a10
- cin gtgt a
- whitespace delimited
- to read multiple words, use getln
- cin.getline( a, 10)
- the number is the number of elements in the array
38concatenating C-style strings
- char str1"cat", str2"top"
- strcat(str2, str1)
- after this code has executed, str2 will contain
"topcat"
39C string class
- library is string (no .h)
- declaration and initialization
42
40string Class
- include ltstringgt
- 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
41Remember
- 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
16
429.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
65
43Common 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
66