Arrays - PowerPoint PPT Presentation

1 / 43
About This Presentation
Title:

Arrays

Description:

In first case above, the null character is appended for you. string.h ... Arrays are always passed by reference. Can use const if array elements are not to be modified ... – PowerPoint PPT presentation

Number of Views:21
Avg rating:3.0/5.0
Slides: 44
Provided by: teres1
Category:

less

Transcript and Presenter's Notes

Title: Arrays


1
Arrays
  • Hanly - Chapter 7
  • Friedman-Koffman - Chapter 9

2
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

3
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

2
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

4
5
Array Declaration
6
6
Sample Declarations
  • Suppose
  • const int N 20
  • const int M 40
  • const int MaxStringSize 80
  • const int MaxListSize 1000

7
7
Sample Declarations
  • Then the following are all correct array
    declarations.
  • int A10
  • char BMaxStringSize
  • float CMN
  • int ValuesMaxListSize
  • Rational DN-15

8
8
Array 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

9
Subscripting
  • 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
10
Subscripting
  • 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
11
Array Elements
  • Suppose
  • int A10 // array of 10 uninitialized ints
  • To access an individual element we must apply a
    subscript to array name A

11
12
Array 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
13
Array Element Manipulation
  • cin gtgt Ak // where the next input value is 3

13
14
Array 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

15
Inputting Into An Array
  • int AMaxListSize
  • int n 0
  • int CurrentInput
  • while((n lt MaxListSize) (cin gtgt
    CurrentInput))
  • An CurrentInput
  • n

14
16
Displaying 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
17
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

18
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

19
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

20
Access to Array Elements
  • Sequential Access
  • Process elements in sequential order starting
    with the first
  • Random Access
  • you can access elements in random order

17
21
9.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
22
swap.cpp
  • // FILE Exchange.cpp
  • // Exchanges two type float values
  • void exchange (float a1, float a2)
  • float temp
  • temp a1
  • a1 a2
  • a2 temp

24
23
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

25
24
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

30
25
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

37
26
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

43
27
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

46
28
Section 1 3/18/02
29
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

30
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

31
C-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
32
Declaring 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

33
string.h
34
length vs number of elements
  • char word "word"
  • word has 5 elements
  • BUT strlen( word) 4

35
assigning values
  • NOT ALLOWED
  • char a "stuff", b
  • b a
  • How do you do this?
  • strcpy( b, a)
  • Now b also contains "stuff"

36
comparing 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

37
reading 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

38
concatenating C-style strings
  • char str1"cat", str2"top"
  • strcat(str2, str1)
  • after this code has executed, str2 will contain
    "topcat"

39
C string class
  • library is string (no .h)
  • declaration and initialization

42
40
string 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

41
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

16
42
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

65
43
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

66
Write a Comment
User Comments (0)
About PowerShow.com