C Programming: Program Design Including Data Structures, Second Edition - PowerPoint PPT Presentation

1 / 112
About This Presentation
Title:

C Programming: Program Design Including Data Structures, Second Edition

Description:

C++ Programming: Program Design Including Data Structures, Second Edition Chapter 9: Arrays and Strings – PowerPoint PPT presentation

Number of Views:104
Avg rating:3.0/5.0
Slides: 113
Provided by: Charl498
Category:

less

Transcript and Presenter's Notes

Title: C Programming: Program Design Including Data Structures, Second Edition


1
C Programming Program Design Including Data
Structures, Second Edition
  • Chapter 9 Arrays and Strings

2
Objectives
  • In this chapter you will
  • Learn about arrays
  • Explore how to declare and manipulate data into
    arrays
  • Understand the meaning of array index out of
    bounds
  • Become familiar with the restrictions on array
    processing
  • Discover how to pass an array as a parameter to a
    function

3
Objectives
  • Learn about C-strings
  • Examine the use of string functions to process
    C-strings
  • Discover how to input data inand output data
    froma C-string
  • Learn about parallel arrays
  • Discover how to manipulate data in a
    two-dimensional array
  • Learn about multidimensional arrays

4
C Data Types
structured
simple
array struct union class
integral enum
char short int long bool
5
Data Types
  • A data type is called simple if variables of that
    type can store only one value at a time
  • A structured data type is one in which each data
    item is a collection of other data items

6
Structured Data Type
  • A structured data type is a type that
  • stores a collection of individual components with
    one variable name
  • and allows individual components to be stored and
    retrieved

7
Declare variables to store and total 3 blood
pressures
  • int bp1, bp2, bp3
  • int total

4002
4000
4004
bp2
bp1
bp3
cin gtgt bp1 gtgt bp2 gtgt bp3
total bp1 bp2 bp3
8
What if you wanted to store and total 1000 blood
pressures?
  • int bp 1000
  • // declares an array of 1000 int
    values

9
Arrays
  • Array - a collection of a fixed number of
    components wherein all of the components have the
    same data type
  • One-dimensional array - an array in which the
    components are arranged in a list form
  • The general form of declaring a one-dimensional
    array is
  • dataType arrayNameintExp
  • where intExp is any expression that evaluates to
    a positive integer

10
One-Dimensional Array Definition
  • An array is a structured collection of components
    (called array elements), all of the same data
    type, given a single name, and stored in adjacent
    memory locations.
  • The individual components are accessed by using
    the array name together with an integral valued
    index in square brackets.
  • The index indicates the position of the component
    within the collection.

11
Another Example
  • Declare an array called temps which will hold up
    to 5 individual float values.
  • float temps5 // declaration allocates memory

number of elements in the array
Base Address
7000 7004 7008 7012
7016
temps0 temps1 temps2 temps3
temps4
indexes or subscripts
12
Accessing Array Components
  • The general form (syntax) of accessing an array
    component is
  • arrayNameindexExp
  • where indexExp, called index, is any expression
    whose value is a nonnegative integer
  • The operator is called the array subscripting
    operator
  • Index value specifies the position of the
    component in the array
  • The array index always starts at 0

13
Assigning Values to Individual Array Elements
  • float temps 5 // allocates memory for
    array
  • int m 4
  • 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?

7000 7004 7008 7012
7016
99.4 ? 98.6 101.2
50.6
temps0 temps1 temps2 temps3
temps4
14
What values are assigned?
  • float temps 5 // allocates memory for
    array
  • int m
  • for (m 0 m lt 5 m)
  • temps m 100.0 m 0.2

7000 7004 7008 7012
7016
? ? ? ?
?
temps0 temps1 temps2 temps3
temps4
15
Now what values are printed?
  • float temps 5 // allocates memory for
    array
  • int m
  • . . . . .
  • for (m 4 m gt 0 m-- )
  • cout ltlt temps m ltlt endl

7000 7004 7008 7012
7016
100.0 100.2 100.4 100.6
100.8
temps0 temps1 temps2 temps3
temps4
16
Variable Subscripts
  • float temps 5 // allocates memory for
    array
  • int m 3
  • . . . . . .
  • What is temps m 1 ?
  • What is temps m 1 ?

7000 7004 7008 7012
7016
100.0 100.2 100.4 100.6
100.8
temps0 temps1 temps2 temps3
temps4
17
A Closer Look at the Compiler
  • float temps5 // this declaration allocates
    memory
  • To the compiler, the value of the identifier
    temps alone is the base address of the array. We
    say temps is a pointer (because its value is an
    address). It points to a memory location.

18
Processing One-Dimensional Arrays
  • Some basic operations performed on a
    one-dimensional array are
  • Initialize
  • Input data
  • Output data stored in an array
  • Find the largest and/or smallest element
  • Each operation requires ability to step through
    the elements of the array
  • Easily accomplished by a loop

19
Accessing Array Components
  • Consider the declaration
  • int list100 //list is an array of the size
    100
  • int i
  • This for loop steps-through each element of the
    array list starting at the first element
  • for(i 0 i lt 100 i) //Line 1
  • process listi //Line 2

20
inputting data into list
  • If processing list requires inputting data into
    list
  • the statement in Line 2 takes the from of an
    input statement, such as the cin statement
  • for(i 0 i lt 100 i) //Line 1
  • cingtgtlisti

21
Array Index Out of Bounds
  • If we have the statements
  • double num10
  • int i
  • The component numi is a valid index if i 0,
    1, 2, 3, 4, 5, 6, 7, 8, or 9
  • The index of an array is in bounds if the index
    gt0 and the index lt arraySize-1

22
Array Index Out of Bounds
  • If either the index lt 0 or the index gt
    arraySize-1
  • then we say that the index is out of bounds
  • There is no guard against indices that are out of
    bounds
  • C does not check if the index value is with in
    range
  • it is programmers responsibility to make sure
    that an array index does not go out of bounds.
    The index must be within the range 0 through the
    declared array size minus one

23
Array Initialization
  • As with simple variables
  • Arrays can be initialized while they are being
    declared
  • When initializing arrays while declaring them
  • Not necessary to specify the size of the array
  • Size of array is determined by the number of
    initial values in the braces
  • For example
  • double sales 12.25, 32.50, 16.90, 23,
    45.68

24
Partial Initialization
  • The statement
  • int list10 0
  • declares list to be an array of 10 components
    and initializes all components to zero
  • The statement
  • int list10 8, 5, 12
  • declares list to be an array of 10 components,
    initializes list0 to 8, list1 to 5, list2
    to 12 and all other components are initialized to
    0

25
Partial Initialization (continued)
  • The statement
  • int list 5,6,3
  • declares list to be an array of 3 components and
  • initializes list0 to 5, list1 to 6, and
    list2 to 3
  • The statement
  • int list25 4,7
  • declares list to be an array of 25 components
  • The first two components are initialized to 4 and
    7 respectively
  • All other components are initialized to zero

26
Initializing in a Declaration
  • int ages 5 40, 13, 20, 19, 36
  • for ( int m 0 m lt 5 m )
  • cout ltlt ages m

27
Restrictions on Array Processing
  • Assignment does not work with arrays
  • If x and y are two arrays of the same type and
    size then the following statement is illegal
  • y x // illegal
  • In order to copy one array into another array we
    must copy component-wise
  • This can be accomplished by a loop
  • for(j 0 j lt 25 j)
  • yj xj

28
No Aggregate Array Operations
  • Comparison of arrays, reading data into an array
    and printing the contents of an array must be
    done component-wise
  • cingtgtx //illegal
  • coutltlty //illegal
  • C does not allow aggregate operations on an
    array
  • i.e. any operation that manipulates the entire
    array as a single unit

29
In C, No Aggregate Array Operations
  • the only thing you can do with an entire array as
    a whole (aggregate) with any type of component
    elements is to pass it as an argument to a
    function
  • EXCEPTION aggregate I/O is permitted for
    C-strings (special kinds of char arrays) later
    in this chapter

30
Arrays as Parameters to Functions
  • Arrays are passed by reference only
  • The symbol is used when declaring an array as a
    formal parameter
  • whenever an array is passed as an argument, its
    base address is sent to the called function
  • The size of the array is usually omitted

31
Arrays as Parameters to Functions
  • If the size of one-dimensional array is specified
    when it is declared as a formal parameter
  • It is ignored by the compiler
  • The reserved word const in the declaration of the
    formal parameter can prevent the function from
    changing the actual parameter

32
Using Arrays as Arguments to Functions
  • Generally, functions that work with arrays
    require items of information as arguments
  • the beginning memory address of the array (base
    address)
  • the number of elements to process in the array
  • - might be less than the size of array
  • See next example

33
Example with Array Parameters
include ltiomanipgt include ltiostreamgt void
Obtain ( int , int )
// prototypes here void FindWarmest ( const
int , int , int ) void FindAverage (
const int , int , int ) void Print (
const int , int ) using namespace std
int main ( ) int temp31 //
array to hold up to 31 temperatures int
numDays int average int
hottest int m
33
34
Example continued
cout ltlt How many daily temperatures?
cin gtgt numDays Obtain( temp,
numDays ) // call passes value of numDays
and // address of array temp to
function cout ltlt numDays ltlt
temperatures ltlt endl Print ( temp,
numDays ) FindAverage ( temp, numDays,
average ) FindWarmest ( temp, numDays,
hottest ) cout ltlt endl ltlt Average
was ltlt average ltlt endl cout ltlt
Highest was ltlt hottest ltlt endl
return 0
34
35
Memory Allocated for Array

int temp31 // array to hold up to 31
temperatures
36
void Obtain ( / out / int temp ,
/ in / int number ) // Has user
enter number temperature values at keyboard //
Precondition // number is assigned
number gt 0 // Postcondition // temp 0 . .
number -1 are assigned int m
for ( m 0 m lt number m ) cout
ltlt Enter a temperature cin gtgt
temp m
36
37
void Print ( / in / const int temp ,
/ in / int number ) // Prints
number temperature values to screen //
Precondition // number is assigned
number gt 0 // temp 0 . . number -1 are
assigned // Postcondition // temp 0 . .
number -1 have been printed 5 to a line
int m cout ltlt You entered
for ( m 0 m lt number m )
if ( m 5 0 ) cout ltlt
endl cout ltlt setw(7) ltlt temp m

37
38
Use of const
  • because the identifier of an array holds the base
    address of the array, an is never needed for an
    array in the parameter list
  • arrays are always passed by reference
  • to prevent elements of an array used as an
    argument from being unintentionally changed by
    the function, you place const in the function
    heading and prototype

39
Use of const in prototypes
  • void Obtain ( int , int )
  • void FindWarmest ( const int , int , int
    )
  • void FindAverage ( const int , int , int
    )
  • void Print ( const int , int )

do not use const with outgoing array
because function is supposed to change array
values
use const with incoming array values to prevent
unintentional changes by function
40
void FindAverage ( / in / const int temp
, / in /
int number ,
/ out / int avg ) // Determines average
of temp0 . . number-1 // Precondition //
number is assigned number gt 0 //
temp 0 . . number -1 are assigned //
Postcondition // avg arithmetic
average of temp0 . . number-1 int m
int total 0 for ( m 0 m lt
number m ) total
total temp m avg int
(float (total) / float (number) .5)
40
41
void FindWarmest ( / in / const int temp
, / in
/ int number ,
/ out / int largest ) // Determines
largest of temp0 . . number-1 //
Precondition // number is assigned
number gt 0 // temp 0 . . number -1 are
assigned // Postcondition // largest
largest value in temp0 . . number-1 int
m largest temp0 //
initialize largest to first element
// then compare with other elements for (
m 0 m lt number m )
if ( temp m gt largest )
largest tempm
41
42
Base Address of an Array
  • The base address of an array is the address, or
    memory location of the first array component
  • If list is a one-dimensional array
  • base address of list is the address of the
    component list0
  • When we pass an array as a parameter
  • base address of the actual array is passed to the
    formal parameter
  • Functions cannot return a value of the type array

43
  • //Arrays as parameters to functions
  • include ltiostreamgt
  • using namespace std
  • const int arraySize 10
  • void initializeArray(int x,int sizeX)
  • void fillArray(int x,int sizeX)
  • void printArray(const int x,int sizeX)
  • int sumArray(const int x,int sizeX)
  • int indexLargestElement(const int x,int sizeX)
  • void copyArray(const int x, int y, int
    length)
  • int main() // Driver
  • int listAarraySize 0 //Line 1
  • int listBarraySize //Line 2
  • cout ltlt "Line 1 listA elements " //Line 3

44
  • fillArray(listA, arraySize) //Line 11
  • cout ltlt endl //Line 12
  • cout ltlt "Line 13 After filling listA elements
    are"
  • ltlt endl //Line 13
  • printArray(listA, arraySize) //Line 14
  • cout ltlt endl ltlt endl //Line 15
  • cout ltlt "Line 16 Sum of the elements of listA
    is "
  • ltlt sumArray(listA, arraySize) ltlt endl ltlt
    endl //Line 16
  • cout ltlt "Line 17 Position of the largest
    element in listA is "
  • ltlt indexLargestElement(listA, arraySize)
  • ltlt endl //Line 17
  • cout ltlt "Line 18 Largest element in listA is "
  • ltlt listAindexLargestElement(listA,
    arraySize)
  • ltlt endl ltlt endl //Line 18
  • copyArray(listA, listB, arraySize) //Line 19
  • cout ltlt "Line 20 After copying the elements of
    "

45
  • //Function to initialize an array to 0
  • void initializeArray(int list, int listSize)
  • int counter
  • for (counter 0 counter lt listSize
    counter)
  • listcounter 0
  • //Function to read data and store in an array
  • void fillArray(int list, int listSize)
  • int counter
  • for (counter 0 counter lt listSize
    counter)
  • cin gtgt listcounter
  • //Function to print the array
  • void printArray(const int list, int listSize)
  • int counter
  • for (counter 0 counter lt listSize
    counter)

//Function to find and return the index of the
//largest element of an array int
indexLargestElement(const int list, int
listSize) int counter int maxIndex
0 //Assume first element is the largest for
(counter 1 counter lt listSize counter)
if (listmaxIndex lt listcounter)
maxIndex counter return
maxIndex //Function to copy one array into
another array //The array listB must be at least
as large as the array listA. void copyArray(const
int listA, int listB, int listASize)
int counter for (counter 0 counter lt
listASize counter) listBcounter
listAcounter
46
Array with enum Index Type
  • DECLARATION
  • enum Department WOMENS, MENS, CHILDRENS,
    LINENS, HOUSEWARES, ELECTRONICS
  • float salesAmt 6
  • Department which
  • USE
  • for ( which WOMENS which lt ELECTRONICS
    which Department ( which 1 ) )
  • cout ltlt salesAmt which ltlt endl

46
47
float salesAmt6
The index has semantic content salesAmt
WOMENS ( i. e. salesAmt 0 )
salesAmt MENS ( i. e. salesAmt
1 ) salesAmt CHILDRENS (
i. e. salesAmt 2 ) salesAmt LINENS
( i. e. salesAmt 3 ) salesAmt
HOUSEWARES ( i. e. salesAmt 4 )
salesAmt ELECTRONICS ( i. e. salesAmt
5 )

48
C Strings (Character Arrays)
  • Character array - an array whose components are
    of type char
  • String - a sequence of gt 0 characters enclosed
    in double quote marks
  • C stings are null terminated (\0)
  • The last character in a string is the null
    character
  • char ch \0 // stores the null chr

49
ASCII and EBCDIC
  • ASCII (pronounced ask-key) and EBCDIC are the
    two character sets commonly used to represent
    characters internally as integers
  • ASCII is used on most personal computers, and
    EBCDIC is used mainly on IBM mainframes
  • using ASCII the character A is internally
    stored as integer 65.
  • Using EBCDIC the A is stored as 193.
  • In both sets, the successive alphabet letters are
    stored as successive integers.
  • This enables character comparisons with A less
    than B, etc.

50
ASCII (Printable) Character Set 0 1
2 3 4 5 6 7 8
9
50
51
C Strings (Character Arrays)
  • There is a difference between 'A' and A
  • A is the character A
  • A is the string A
  • "A" represents two characters, 'A' and '\0
  • Because strings are null terminated
  • Similarly, "Hello" contains six characters, 'H',
    'e', 'l', 'l', 'o', and '\0'

52
C Strings (Character Arrays)
  • Consider the statement
  • char name16
  • Because C strings are null terminated and name
    has sixteen components
  • The largest string that can be stored in name is
    15
  • If you store a string of length, say 10 in name
  • The first 11 components of name are used and the
    last 5 are left unused

53
C Strings (Character Arrays)
  • The statement
  • char name16 "John"
  • declares a string variable name of length 16 and
    stores "John" in it
  • The statement
  • char name "John"
  • declares a string variable name of length 5 and
    stores "John" in it

54
String Comparison p.444 and 1474-5
  • C-strings are compared character by character
    using the collating sequence of the system
  • If we are using the ASCII character set
  • The string "Air" is smaller than the string
    "Boat"
  • The string "Air" is smaller than the string "An"
  • The string "Bill" is smaller than the string
    "Billy b/c of the null chr in "Bill"
  • The string "Hello" is smaller than "hello"

55
C String functions p.444 and 1474-5
  • C String functions p. 1474-5
  • strcmp(str1, str2)
  • strcat(deststr1, srcstr2)
  • strcpy(deststr1, srcstr2)
  • strlen(str)

56
Reading and Writing Strings
  • String Input
  • Aggregate operations are allowed
  • cingtgtname
  • stores the next input string in name
  • e.g. char name31
  • cingtgtname // input C-string must lt30 chrs
  • Strings that contain blanks cannot be read using
    the extraction operator gtgt

57
Reading and Writing Strings
  • To read strings with blanks, use the get function
    with an input stream variable, such as cin
  • cin.get(str, m1)
  • Stores the next m characters into str but the
    newline character is not stored in str,
  • Ex read 2 lines of input
  • Today is hot.
  • My class CS901 is the best one.
  • we need to discard the new line char at the
    end of the 1st line to store the 2nd line in
    line2
  • char line125, line225, char newline
  • cin.get (line1, 25) // store C-string up to 24
    in length
  • cin.get (newline) // discard the new line char
  • cin.get (line2, 25)
  • note see how to use getline ( infile, name )
    p.254 where string name
  • If the input string has fewer than m characters,
    the reading stops at the newline character

58
Reading and Writing Strings
  • String Output
  • coutltltname
  • outputs the content of name on the screen
  • The insertion operator ltlt continues to write the
    contents of name until it finds the null
    character
  • If name does not contain the null character, then
    we will see strange output ltlt continues to
    output data from memory adjacent to name until
    '\0' is found

59
Input/Output Files
  • The header file ltstringgt p.1475 contains the
    function c_str
  • Converts a value of the type string to a
    null-terminated character array
  • The syntax to use the function c_str is
  • strVar.c_str()
  • where strVar is a variable of the type string

60
Input/Output Files
  • C strings are not null terminated
  • Variables of type string can be used to read and
    store the names of input/output files
  • string fileName
  • The argument to the function open must be a null
    terminated string (a C-string)
  • cout ltlt Enter file name
  • cin gtgt fileName
  • infile.open (fileName.c_str())
  • The value of the variable must first be converted
    to a C-string (null-terminated string)
  • note another solution p.448

61
Parallel Arrays
  • DEFINITION
  • Parallel arrays are 2 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
  • float hourlyWage SIZE
    parallel arrays

62
const int SIZE 50 int idNumber SIZE
// parallel arrays holdfloat
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

63
Two-Dimensional Arrays
  • Two-dimensional Array a collection of a fixed
    number of components arranged in two dimensions
  • All components are of the same type
  • Individual components are accessed by a pair of
    indexes representing the components position in
    each dimension.

64
Two-Dimensional Arrays
  • The syntax for declaring a two-dimensional array
    is
  • dataType arrayNameintexp1intexp2
  • where intexp1 and intexp2 are expressions
    yielding positive integer values
  • intexp1 and intexp2 specify the number of rows
    and the number of columns, respectively, in the
    array
  • Two-dimensional arrays are sometimes called
    matrixes or tables

65
Accessing Array Components
  • The syntax to access a component of a
    two-dimensional array is
  • arrayNameindexexp1indexexp2
  • where indexexp1 and indexexp2 are expressions
    yielding nonnegative integer values
  • indexexp1 - the row position and
  • indexexp2 - the column position

66
Initialization
  • Like one-dimensional arrays
  • Two-dimensional arrays can be initialized when
    they are declared
  • To initialize a two-dimensional array when it is
    declared
  • int board 3 2 1, 2,
  • 3, 6,
  • 9, 2
  • Elements of each row are enclosed within braces
    and separated by commas
  • All rows are enclosed within braces
  • For number arrays,
  • if all components of a row are not specified, the
    unspecified components are initialized to zero

67
Processing Two-Dimensional Arrays
  • A two-dimensional array can be processed in three
    different ways
  • Process the entire array
  • Process a particular row of the array, called row
    processing
  • Process a particular column of the array, called
    column processing

68
Processing Two-Dimensional Arrays
  • Each row and each column of a two-dimensional
    array is a one-dimensional array
  • When processing a particular row or column of a
    two-dimensional array
  • We use algorithms similar to processing
    one-dimensional arrays

69
Initialization
  • This for loop initializes row four to zero
  • row 4
  • for(col 0 col lt columns col)
  • matrixrowcol 0
  • To initialize the entire matrix, we can also put
    the first index (row position) in a loop
  • These nested for loops initialize each component
    of matrix to 0
  • for(row 0 row lt rows row)
  • for(col 0 col lt columns col)
  • matrixrowcol 0

70
Print
  • The following nested for loops print the
    components of matrix, one row per line
  • for(row 0 row lt rows row)
  • for(col 0 col lt columns col)
  • coutltltsetw(5)ltltmatrixrowcolltlt" "
  • coutltltendl

71
Input
  • This for loop inputs data in row number 4 of
    matrix
  • row 4
  • for(col 0 col lt columns col)
  • cingtgtmatrixrowcol
  • By putting the row number in a loop we can input
    data in each component of the matrix
  • for(row 0 row lt rows row)
  • for(col 0 col lt columns col)
  • cingtgtmatrixrowcol

72
  • EXAMPLE -- To keep monthly high temperatures for
    all 50 states in one array.
  • const int NUM_STATES 50
  • const int NUM_MONTHS 12
  • int stateHighs NUM_STATES NUM_MONTHS
  • 0
  • 1
  • 2
  • .
  • . stateHighs 2 7
  • .
  • 48
  • 49

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 Arizonas high for August
73
Finding the average high temperature for Arizona
  • int total 0
  • int month // WITHOUT ENUM TYPES
  • int average
  • for ( month 0 month lt NUM_MONTHS month )
  • total total stateHighs 2 month
  • average int ( total / 12.0 0.5 )
  • average
  • 85

74
  • enum MonthType JAN, FEB, MAR, APR, MAY,
    JUN,
  • JUL, AUG, SEP, OCT, NOV, DEC
  • const int NUM_MONTHS 12
  • const int NUM_STATES 50
  • int stateHighs NUM_STATES NUM_MONTHS
  • 0
  • 1
  • 2
  • .
  • . stateHighs 2 AUG
  • .
  • 48
  • 49

JAN . . . AUG
. . DEC
66 64 72 78 85 90 99 105 98 90 88 80
row 2, col AUG could be Arizonas high for August
75
Finding the Average High Temperature for Arizona
  • int total 0
  • MonthType month // WITH ENUM TYPES
    DEFINED
  • int average
  • for ( month JAN month lt DEC month
    MonthType( month 1) )
  • total total stateHighs 2 month
  • average int ( total / 12.0 0.5 )
  • average
  • 85

76
  • enum StateType AL, AK, AZ, AR, CA, CO, CT,
    DE, FL, GA, HI, ID, IL, IN, IA, KS, KY, LA, ME,
    MD, MA, MI, MN, MS, MO, MT, NE, NV, NH, NJ, NM,
    NY, NC, ND, OH, OK, OR, PA, RI, SC, SD, TN, TX,
    UT, VT, VA, WA, WV, WI, WY
  • enum MonthType JAN, FEB, MAR, APR, MAY,
    JUN, JUL, AUG, SEP, OCT,
    NOV, DEC
  • const int NUM_MONTHS 12
  • const int NUM_STATES 50
  • int stateHighs NUM_STATES NUM_MONTHS
  • AL
  • AK
  • AZ
  • .
  • . stateHighs AZ
    AUG
  • .
  • WI
  • WY

JAN . . . AUG
. . DEC
66 64 72 78 85 90 99 105 98 90 88 80
row AZ, col AUG holds Arizonas high for August
77
Two-dimensional arrays are stored in row
orderThe first row is stored first, followed by
the second row, followed by the third row and so
on
Base Address 8000
stateHighs 0 0 stateHighs 0 1
stateHighs 0 2 stateHighs 0 3
stateHighs 0 4 stateHighs 0 5
stateHighs 0 6 stateHighs 0 7
stateHighs 0 8 stateHighs 0 9
stateHighs 0 10 stateHighs 0 11
stateHighs 1 0 stateHighs 1 1
stateHighs 1 2 stateHighs 1 3
. . .
To locate an element such as stateHighs 2
7 the compiler needs to know that there are 12
columns in this two-dimensional array. At what
address will stateHighs 2 7 be
found? Assume 2 bytes for type int.
78
Passing Two-Dimensional Arrays as Parameters to
Functions
  • Two-dimensional arrays can be passed as
    parameters to a function
  • By default, arrays are passed by reference
  • The base address, that is, the address of the
    first component of the actual parameter is passed
    to the formal parameter

79
Two-Dimensional Arrays
  • When declaring the size of all dimensions except
    the first must be included in the function
    heading and prototype
  • the sizes of those dimensions in the functions
    parameter list must be exactly the same as
    declared for the callers array

80
Write a function using the two-dimensional
stateHighs array to fill a one-dimensional
stateAverages array
  • const int NUM_STATES 50
  • const int NUM_MONTHS 12
  • int stateHighs NUM_STATES NUM_MONTHS
  • int stateAverages NUM_STATES
  • 0
  • 62 1
  • 85 2
  • .
  • .
  • .
  • 48
  • 49

0 1 2 3 4 5 6 7 8 9
10 11
Alaska Arizona
43 42 50 55 60 78 80 85 81 72 63 40 66 64 72 78
85 90 99 105 98 90 88 80
80
81
void FindAverages( / in / const int
stateHighs NUM_MONTHS , / out
/ int stateAverages )
  • // PRE stateHighs 0..NUM_STATES
    0..NUM_MONTHS assigned
  • // POST stateAverages 0..NUM_STATES contains
    rounded average
  • // high temperature for each state
  • int state
  • int month
  • int total
  • for ( state 0 state lt NUM_STATES
    state )
  • total 0
  • for ( month 0 month lt NUM_MONTHS
    month )
  • total stateHighs state month
  • stateAverages state int ( total / 12.0
    0.5 )

81
82
Using typedef with Arrays
  • helps eliminate the chances of size mismatches
    between
  • function arguments and parameters. FOR
    EXAMPLE,
  • typedef int StateHighsType NUM_STATES
    NUM_MONTHS
  • typedef int StateAveragesType NUM_STATES
  • void FindAverages( / in / const
    StateHighsType stateHighs ,
    / out / StateAveragesType
    stateAverages )
  • .
  • .
  • .

82
83
Multidimensional Arrays
  • Multidimensional Array collection of a fixed
    number of elements (called components) arranged
    in n dimensions (n gt 1),
  • Also called an n-dimensional array
  • General syntax of declaring an n-dimensional
    array is
  • dataType arrayNameintExp1intExp2...intExpn
  • where intExp1, intExp2, are constant
    expressions yielding positive integer values

84
Multidimensional Arrays (continued)
  • The syntax for accessing a component of an
    n-dimensional array is
  • arrayNameindexExp1indexExp2...indexExpn
  • where indexExp1,indexExp2,..., and indexExpn are
    expressions yielding nonnegative integer values.
  • indexExpi gives the position of the array
    component in the ith dimension

85
Declaring Multidimensional Arrays
  • EXAMPLE OF THREE-DIMENSIONAL ARRAY
  • const NUM_DEPTS 5 // men, women,
    childrens, electronics, furniture
  • const NUM_MONTHS 12
  • const NUM_STORES 3 // White Marsh,
    Owings Mills, Towson
  • int monthlySales NUM_DEPTS NUM_MONTHS
    NUM_STORES
  • rows columns sheets
  • OR USING TYPEDEF
  • typedef int MonthlySalesType NUM_DEPTS
    NUM_MONTHS NUM_STORES
  • MonthlySalesType monthlySales

85
86
  • 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

monthlySales370 sales for
electronics in August at White Marsh
3 STORES sheets
5 DEPTS rows
12 MONTHS columns
87
Print sales for each month by department for one
store
COMBINED SALES FOR January DEPT DEPT
NAME SALES 0 Mens 8345
1 Womens 9298 2
Childrens 7645 3 Electronics
14567 4 Furniture
21016 . . . . . . COMBIN
ED SALES FOR December DEPT DEPT
NAME SALES 0 Mens 12345
1 Womens 13200 2
Childrens 11176 3 Electronics
22567 4 Furniture 11230
88
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 . . . . for ( month 0
month lt NUM_MONTHS month ) cout
ltlt COMBINED SALES FOR
WriteOut(month) // function call to
write the name of month cout ltlt
DEPT DEPT NAME SALES ltlt endl
for (dept 0 dept lt NUM_DEPTS
dept ) totalSales 0
// sum over all stores for (store
0 store lt NUM_STORES store )
totalSales totalSales monthlySales dept
month store
WriteDeptNameAndSales(dept, totalSales )
// function call
88
89
Adding a Fourth Dimension . . .
const NUM_DEPTS 5 // mens,
womens, childrens, electronics, furniture const
NUM_MONTHS 12 const NUM_STORES
3 // White Marsh, Owings Mills,
Towson const NUM_YEARS 2 int
moreSales NUM_DEPTS NUM_MONTHS NUM_STORES
NUM_YEARS
year 0 year 1
moreSales3 7 0 1
for electronics, August, White Marsh, one year
after starting year
90
Multidimensional Arrays (continued)
  • When declaring a multi-dimensional array as a
    formal parameter in a function
  • Can omit size of first dimension but not other
    dimensions
  • As parameters, multi-dimensional arrays are
    passed by reference only
  • A function cannot return a value of the type
    array
  • There is no check if the array indices are within
    bounds

91
Programming Example
  • When a message is transmitted in secret code over
    a transmission channel
  • Usually transmitted as a sequence of bits (0s and
    1s)
  • Due to noise in the transmission channel, the
    transmitted message may become corrupted
  • The message received at destination is not the
    same as the message transmitted
  • Some of the bits may have been changed

92
Programming Example (continued)
  • Several techniques to check the validity of the
    transmitted message at the destination
  • One technique is to transmit the same message
    twice
  • At the destination, both copies of the message
    are compared bit by bit
  • If the corresponding bits are the same, the
    message received is error-free

93
Programming Example (continued)
  • We write a program to check if the message
    received at the destination is error-free
  • For simplicity, assume that
  • The secret code representing the message is a
    sequence of digits (0 to 9)
  • The maximum length of the message is 250 digits
  • The first number in the message is the length of
    the message

94
Programming Example (continued)
  • If the secret code is
  • 7 9 2 7 8 3 5 6
  • then the message is 7 digits long
  • The above message is transmitted (twice) as
  • 7 9 2 7 8 3 5 6 7 9 2 7 8 3 5 6
  • The input is a file containing the secret code
    and its copy

95
Programming Example (continued)
  • The output is the
  • secret code,
  • its copy, and
  • a message if the received code is error-free
  • The results are output in the following form
  • Code Digit Code Digit Copy
  • 9 9
  • 2 2
  • 7 7
  • 8 8
  • 3 3
  • 5 5
  • 6 6
  • Message transmitted OK

96
Problem Analysis
  • Because we have to compare the corresponding
    digits of the secret code and its copy
  • First read the secret code and store it in an
    array
  • Next, read the first digit of the copy and
    compare it with the first digit of the secret
    code, and so on

97
Problem Analysis (continued)
  • If any corresponding digits are not the same
  • Indicate this by printing a message next to the
    digits
  • Because the maximum length of the message is 250
  • Use an array of 250 components
  • The first number in the secret code, and in the
    copy of the secret code, indicates the length of
    the code

98
Algorithm Design
  1. Open the input and output files
  2. If the input file does not exist, exit the
    program
  3. Read the length of the secret code
  4. If the length of the secret code is greater than
    250, terminate the program because the maximum
    length of the code in this program is 250
  5. Read and store the secret code into an array

99
Algorithm Design (continued)
  • Read the length of the copy
  • If the length of the secret code and its copy are
    the same, compare the codes
  • otherwise, print an error message
  • To simplify function main write
  • readCode - to read the secret code and
  • compareCode - to compare the codes

100
Main Algorithm
  • Declare Variables
  • Open the files
  • Call the function readCode to read the secret
    code
  • If (length of the secret code lt 250)
  • Call compareCode() to compare the codes
  • else
  • Output an appropriate error message

101
  • //Program Check Code p.470
  • include ltiostreamgt
  • include ltfstreamgt
  • include ltiomanipgt
  • using namespace std
  • const int maxCodeSize 250
  • void readCode(ifstream infile, int list, int
    length, bool lenCodeOk)
  • void compareCode(ifstream infile, ofstream
    outfile, int list, int length)
  • int main()
  • //Step 1
  • int codeArraymaxCodeSize //array to store the
    secret code
  • int codeLength //variable to store the length
    of the secret code
  • bool lengthCodeOk //variable to indicate if
    the length of the
  • //secret code is less than or equal to 250
  • ifstream incode //input file stream variable
  • ofstream outcode //output file stream
    variable
  • char inputfile25 //variable to store the name
    of the input file
  • char outputfile25 //variable to store the
    name of the output file

102
  • void readCode(ifstream infile, int list, int
    length, bool lenCodeOk)
  • int count
  • lenCodeOk true
  • infile gtgt length // get the length
    of the secret code
  • if (length gt maxCodeSize)
  • lenCodeOk false
  • return
  • for (count 0 count lt length count) // get
    the secret code
  • infile gtgt listcount
  • This function first reads length of secret code
  • If length of secret code is greater than 250
  • A boolean variable lengthCodeOk, a reference
    parameter, is set to false and the function
    terminates
  • The value of lengthCodeOk is passed to the
    calling function to indicate whether the secret
    code was read successfully
  • If the length of the code is less than 250
  • The readCode function reads and stores the secret
    code into an array

//7 9 2 7 8 3 5 6 7 9 2 7 8 3 5 6
103
  • void compareCode(ifstream infile, ofstream
    outfile,
  • int list, int length)
  • int length2
  • int digit
  • bool codeOk
  • int count
  • codeOk true
  • infile gtgt length2
  • if (length ! length2)
  • cout ltlt "The original code and its copy are not
    of"
  • ltlt " the same length." ltlt endl
  • return
  • outfile ltlt "Code Digit Code Digit Copy" ltlt
    endl
  • for (count 0 count lt length count)
  • In this function we will
  • Declare variables
  • Set a bool variable codeOk true
  • Read the length of the copy of the secret code
  • If the length of the secret code and its copy are
    not the same
  • Output an appropriate error message and terminate
    the function
  • For each digit in the input file
  • Read the next digit of secret code copy
  • Output the corresponding digits from the secret
    code and its copy
  • If the corresponding digits are not the same,
    output an error message and set the flag codeOk
    false
  • If the bool variable codeOk is true
  • Output a message indicating that the secret code
    transmitted OK, else - output an error message

Code Digit Code Digit Copy 9
9 2 2 7
7 8 8 3
3 5 5
6 6 Message transmitted OK.
104
Summary
  • An array is a structured data type with a fixed
    number of components
  • Every component is of the same type
  • Components are accessed using their relative
    positions in the array
  • Elements of a one-dimensional array are arranged
    in the form of a list
  • An array index can be any expression that
    evaluates to a non-negative integer
  • The value of the index must always be less than
    the size of the array

105
Summary
  • The base address of an array is the address of
    the first array component
  • In a function call statement,
  • when passing an array as an actual parameter, you
    use only its name
  • As parameters to functions, arrays are passed by
    reference only
  • A function cannot return a value of the type
    array
  • In C, C-strings are null terminated and are
    stored in character arrays

106
Summary
  • Commonly used C-string manipulation functions
    include strcpy, strcmp, and strlen
  • Parallel arrays are used to hold related
    information
  • In a two-dimensional array, the elements are
    arranged in a table form

107
Summary
  • To access an element of a two-dimensional array,
    you need a pair of indices
  • one for the row position and one for the column
    position
  • In row processing, a two-dimensional array is
    processed one row at a time
  • In column processing, a two-dimensional array is
    processed one column at a time

108
Programming Life Cycle
  • Problem-Solving Phase
  • Analysis and Specification
  • General Solution ( Algorithm )
  • Verify
  • Implementation Phase
  • Concrete Solution ( Program )
  • Test
  • Maintenance Phase
  • Use
  • Maintain

109
A Tempting Shortcut?
DEBUG
REVISE
REVISE
DEBUG
DEBUG
REVISE
Shortcut?
CODE
GOAL
TEST
THINKING
CODE
110
Testing Often Combines Two Approaches
WHITE BOX BLACK BOX
TESTING TESTING
Code Coverage Allows us to see the
program code while designing the tests.
Ensure that each statement in the program is
executed at least once. We could say that 75 of
the branches of a program have been executed or
50 of the path have been tested (metric based
testing).
Data Coverage Data values at the
boundaries, and possibly middle values,
example of each category of inputs can be tested.
111
How to Test a Program
  • design and implement a test plan
  • a test plan is a document that specifies the test
    cases to try, which includes
  • purposes
  • conditions of the test cases
  • inputs,
  • and the expected output
  • implement the test plan by verifying that the
    program outputs the predicted results

112
PHASE RESULT
TESTING TECHNIQUE

Problem solving Algorithm Algorithm
walk-through
Implementation Coded program Code
walk-through, Trace
Compilation Object program Compiler
messages
Execution Output
Implement test plan
Write a Comment
User Comments (0)
About PowerShow.com