CSci 152: Programming II Fall 2004 - PowerPoint PPT Presentation

1 / 51
About This Presentation
Title:

CSci 152: Programming II Fall 2004

Description:

The size of the array is determined by the number of initial values in the braces. ... 1. The string 'Air' is smaller than the string 'Boat' ... – PowerPoint PPT presentation

Number of Views:24
Avg rating:3.0/5.0
Slides: 52
Provided by: DerekH71
Category:
Tags: boat | csci | fall | programming | used | values

less

Transcript and Presenter's Notes

Title: CSci 152: Programming II Fall 2004


1
CSci 152 Programming IIFall 2004
  • One-Dimensional Arrays

2
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
  • 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

3
  • 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.

4
  • //Program to read five numbers, find their sum,
    and
  • //print the numbers in reverse order.
  •  
  • include ltiostreamgt
  • using namespace std
  •  
  • int main()
  • int item0, item1, item2, item3, item4
  • int sum
  •  
  • coutltlt"Enter five integers "
  • cingtgtitem0gtgtitem1gtgtitem2gtgtitem3gtgtitem4
  • coutltltendl
  •  
  • sum item0 item1 item2 item3 item4
  •  
  • coutltlt"The sum of the numbers "ltltsumltltendl
  • coutltlt"The numbers in reverse order are "

5
  • We note the following in the above program.
  • 1. Five variables must be declared because the
    numbers are to be printed in reverse order.
  • 2. All variables are of the type intthat is, of
    the same data type.
  • 3. The way in which these variables are declared
    indicates that the variables to store these
    numbers have the same name except the last
    character, which is a number.
  • Statement 1 tells you that you have to declare
    five variables.
  • Statement 3 tells you that it would be convenient
    if you could somehow put the last character,
    which is a number, into a counter variable and
    use one for loop to count from 0 to 4 for reading
    and another for loop to count from 4 to 0 for
    printing.
  • All variables are of the same type. So you should
    be able to specify how many variables must be
    declaredand their data typewith a simpler
    statement than the one we used earlier.

6
Arrays
  • An array is a collection of a fixed number of
    components wherein all of the components are of
    the same data type.
  • A one-dimensional array is 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.

7
  • Example 9-1
  • The statement
  • int num5
  • declares an array num of 5 components. Each
    component is of the type int. The components are
    num0, num1, num2, num3, and num4.

8
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.
  • Index value specifies the position of the
    component in the array.
  • In C, is an operator, called the array
    subscripting operator.
  • In C array index starts at 0.

9
  • int list10

10
  • list5 34

11
  • If i is an int variable, the assignment statement
  • list3 63
  • is equivalent to the assignment statements
  • i 3
  • listi 63
  • If i is 4, then the assignment statement
  • list2i-3 58
  • stores 58 in list5, because 2i-3 evaluates to
    5.

12
  • list3 10
  • list6 35
  • list5 list3 list6

13
  • Example 9-2
  • You can also declare arrays as follows
  •              
  • const int arraySize 10
  •  
  • int listarraySize
  • When you declare an array, its size must be
    known.
  •                 
  • int arraySize //Line 1
  •  
  • coutltlt"Enter the size of the array " //Line 2
  • cingtgtarraySize //Line 3
  • coutltltendl //Line 4
  •  
  • int listarraySize //Line 5 not allowed

14
Processing One-Dimensional Arrays
  • Some of the 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 of these operations requires the ability to
    step through the elements of the array.
  • Stepping-through the elements of an array is
    easily accomplished by a loop.

15
  • Consider the declaration.
  • int list100 //list is an array of the size 100
  • int i
  • The following for loop steps-through each element
    of the array list starting at the first element
    of list.
  • for(i 0 i lt 100 i) //Line 1
  • process listi //Line 2
  • 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

16
  • Example 9-3
  • double sale10
  • int index
  • double largestSale, sum, average
  • (a) Initializing an array
  • for(index 0 index lt 10 index)
  • saleindex 0.0
  • (b) Reading data in an array
  • for(index 0 index lt 10 index)
  • cingtgtsaleindex
  • (c) Printing an array
  • for(index 0 index lt 10 index)
  • coutltltsaleindexltlt" "

17
  • (d) Finding the sum and average of an array
  • sum 0
  • for(index 0 index lt 10 index )
  • sum sum saleindex
  • average sum / 10
  • (e) Largest element in the array
  • maxIndex 0
  • for(index 1 index lt 10 index )
  • if(salemaxIndex lt saleindex)
  • maxIndex index
  • largestSale salemaxIndex

18
  • maxIndex 0 index 1
  • id mId salemId saleid salemIdltsaleid
  • 1 0 12.50 8.35 12.50 lt 8.35 is false
  • 2 0 12.50 19.60 12.50 lt 19.60 is true
    mId 2
  • 3 2 19.60 25.00 19.60 lt 25.00 is
    true mId 3
  • 4 3 25.00 14.00 25.00 lt 14.00 is false
  • 5 3 25.00 39.43 25.00 lt 39.43 is true
    mId 5
  • 6 5 39.43 35.90 39.43 lt 35.90 is false
  • 7 5 39.43 98.23 39.43 lt 98.23 is true mId
    7
  • 8 7 98.23 66.25 98.23 lt 66.65 is
    false
  • 9 7 98.23 35.64 98.23 lt 35.64 is false
  • In the above table id stands for index and mId
    stands for maxIndex

19
  • Example 9-4
  • //Program to read five numbers, find their sum,
    and
  • //print the numbers in reverse order.
  • include ltiostreamgt
  • using namespace std
  • int main()
  • int item5 //declare an array item of five
    components
  • int sum
  • int counter
  • coutltlt"Enter five numbers."ltltendl
  • sum 0

20
  • for(counter 0 counter lt 5 counter)
  • cingtgtitemcounter
  • sum sum itemcounter
  • coutltlt"The sum of the numbers is "ltltsumltltendl
  • coutltlt"The numbers in reverse order are "
  • //print numbers in reverse order
  • for(counter 4 counter gt 0 counter--)
  • coutltltitemcounterltlt" "
  • coutltltendl
  • return 0

21
  • Sample Run The user input is in red.
  • Enter five numbers.
  • 12 76 34 52 89
  • The sum of the numbers is 263
  • The numbers in reverse order are 89 52 34 76
    12

22
Array Index Out of Bounds
  • double num10
  • int i
  • The component numi is valid, that is, i is a
    valid index, if i 0, 1, 2, 3, 4, 5, 6, 7, 8,
    or 9.
  • The index, say index, of an array is in bounds if
    index gt0 and index lt arraySize-1.
  • If either index lt 0 or index gt arraySize-1,
    then we say that the index is out of bounds.
  • In C, there is no guard against indices that
    are out of bounds. That is, C does not check if
    the index value is with in range, that is,
    between 0 and arraySize-1.

23
  • A loop such as the following can set the index
    out of bounds.
  • for(i 0 i lt 10 i)
  • listi0
  • Here we assume that list is an array of 10
    components.

24
Array Initialization During Declaration
  • Like any other simple variable, arrays can also
    be initialized while they are being declared.
  • double sales5 12.25, 32.50, 16.90, 23,
    45.68
  • sales0 12.25, sales1 32.50, sales2
    16.90, sales3 23.00, and sales445.68.
  • When initializing arrays while declaring them, it
    is not necessary to specify the size of the
    array.
  • The size of the array is determined by the number
    of initial values in the braces.
  • double sales 12.25, 32.50, 16.90, 23,
    45.68

25
Partial Initialization of Arrays During
Declaration
  • 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.

26
  • 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 and all other components are
    initialized to zero.

27
Some Restrictions on Array Processing
  • Suppose x and y are two arrays of the same type
    and size, say 25. 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 like the following.
  • for(j 0 j lt 25 j)
  • yj xj
  • Similarly comparison of arrays, reading data into
    an array and printing the contents of an array
    must be done component-wise.
  • cingtgtx //illegal
  • coutltlty //illegal

28
  • if(x lt y) //illegal
  • .
  • .
  • .
  • C does not allows aggregate operations on
    array.
  • An aggregate operation on an array is any
    operation that manipulates the entire array as a
    single unit.

29
Arrays as Parameters to Functions
  • By Reference Only In C, arrays are passed by
    reference only.
  • Since arrays are passed by reference only, we do
    not use the symbol when declaring an array as a
    formal parameter.
  • When declaring a one-dimensional array as a
    formal parameter the size of the array is usually
    omitted.
  • If we specify the size of the one-dimensional
    array when it is declared as a formal parameter,
    it is ignored by the compiler.

30
  • void initialize(int list5)
  • int count
  • for(count 0 count lt 5 count)
  • listcount 0
  • The for loop inside the function executes 5
    times, the above function will correctly
    initialize any int array of size 5 to zero.
  • If we add another formal parameter, say size in
    the function heading, use the value of size to
    control the for loop iterations, and pass the
    name of the actual array together with its size
    during call, then we can use the same function
    for any size array.
  • void initialize(int list, int size)
  • int count
  • for(count 0 count lt size count)
  • listcount 0

31
  • Even though an array is always passed by
    reference, we can still prevent the function from
    changing the actual parameter.
  • This is accomplished by using the reserved word
    const in the declaration of the formal parameter.
  • void example(int x, const int y,
  • int sizeX, int sizeY)
  • .
  • .
  • .

32
  • Example 9-5
  • //Function to initialize an array to 0
  • void initializeArray(int x,int sizeX)
  • int counter
  • for(counter 0 counter lt sizeX counter)
  • xcounter 0
  • //Function to read data and store in an array
  • void fillArray(int x,int sizeX)
  • int counter
  • for(counter 0 counter lt sizeX counter)
  • cingtgtxcounter

33
  • //Function to print the array
  • void printArray(int x,int sizeX)
  • int counter
  • for(counter 0 counter lt sizeX counter)
  • coutltltxcounterltlt" "

34
  • //Function to find and return the sum of an array
  • int sumArray(int x,int sizeX)
  • int counter
  • int sum 0
  • for(counter 0 counter lt sizeX counter)
  • sum sum xcounter
  • return sum

35
  • // Function to find and return the index of the
  • // largest element of an array
  • int indexLargestElement(const int x,int sizeX)
  • int counter
  • int maxIndex 0 //Assume first element is the
    largest
  • for(counter 1 counter lt sizeX counter)
  • if(xmaxIndex lt xcounter)
  • maxIndex counter
  • return maxIndex

36
  • C Strings (Character Arrays)
  • Character array An array whose components are of
    the type char is called a character array.
  • ch '\0'
  • String A string is a sequence of zero or more
    characters enclosed in double quote marks.
  • C stings are null terminated. That is, the last
    character in a string is the null character.
  • "John L. Johnson"
  • "Hello there."

37
  • There is a difference between 'A' and "A". The
    first one is character A and the second is string
    A.
  • Since strings are null terminated, "A" represents
    two characters, 'A' and '\0'.
  • "Hello" represents six characters, 'H', 'e', 'l',
    'l', 'o', and '\0'.
  • To store 'A' we need only one memory cell of the
    type char, while to store "A", we need two memory
    cells of the type char, one for 'A' and the other
    for '\0'.
  • To store the string "HELLO" in computer we need
    six memory cells of the type char.
  • Consider the statement.
  • char name16
  • Since 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.

38
  • char name16 'J', 'o', 'h', 'n', '\0'
  • During char array variable declaration, C
    allows the string notation to be used in the
    initialization statement.
  • char name16 "John" //Line A
  • The statement
  • char name "John" //Line B
  • declares a string variable name of length large
    enough, that is, 5 (here) and stores "John" in
    it.
  • There is a difference between the last two
    statements. Both statements stores "John" in
    name.
  • The size of name in the statement in Line A is 16
    while its size in the statement in Line B is 5.

39
  • Most of the rules that apply to other arrays also
    apply to character arrays.
  • Consider the statement
  • char studentName26
  • studentName "Lisa L. Johnson" //Illegal

40
  • To use these functions the program must include
    the header file cstring via the include
    statement.
  • include ltcstringgt

41
  • String Comparison
  • In C, C-strings are compared character by
    character using the collating sequence of the
    system.
  • Let us assume that we are using the ASCII
    character set.
  • 1. The string "Air" is smaller than the string
    "Boat".
  • 2. The string "Air" is smaller than the string
    "An".
  • 3. The string "Bill" is smaller than the string
    "Billy".
  • 4. The string "Hello" is smaller than "hello".

42
  • Example 9-7
  • char studentName21
  • char myname16
  • char yourname16
  • Statement Effect
  • a. strcpy(myname,"John Robinson") mynameJohn
    Robinson
  • b. strlen("John Robinson") Returns 13, the
    length
  • of the string
  • c. int len
  • len strlen ("Sunny Day") Stores 9 into len
  • d. strcpy(yourname,"Lisa Miller") yourname
    Lisa Miller
  • strcpy(studentName,yourname) studentName
    Lisa Miller
  • e. strcmp("Bill", "Lisa") Returns a value lt
    0
  • f. strcpy(yourname, "Kathy Brown") yourname
    Kathy Brown
  • strcpy(myname, "Mark G. Clark") myname
    Mark G. Clark
  • strcmp(myname,yourname) Return a value gt 0

43
  • Reading and Writing Strings
  • char name31
  • String Input
  • Since aggregate operations are allowed for string
    input, the statement
  • cingtgtname
  • will store the next input string into name.
  • Strings that contain blanks cannot be read using
    the extraction operator gtgt.

44
  • To read strings with blanks, the general form
    (syntax) of get function together with an input
    stream variable, such as cin is
  • cin.get(str,m1)
  • This statement stores the next m characters or
    until the newline character '\n' is found into
    str. The newline character is not stored in str.
  • If the input string has fewer than m characters,
    then the reading stops at the newline character.

45
  • Consider the following statements
  • char str31
  • cin.get(str,31)
  • If the input is
  • William T. Johnson
  • then "William T. Johnson" will be stored in str
    and
  • If the input is
  • Hello there. My name is Mickey Mouse.
  • then the string
  • "Hello there. My name is Mickey"

46
  • char str126
  • char str226
  • char discard
  • Input is, say
  • Summer is warm.
  • Winter will be cold.
  • The following statements store line 1 in str1 and
    line 2 in str2.
  • cin.get(str1,26)
  • cin.get(discard)
  • cin.get(str2,26)

47
  • String Output
  • The statement
  • coutltltname
  • will output 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 since ltlt continues to
    output data from memories adjacent to name until
    '\0' is found.

48
  • Specifying Input/Output Files at the Execution
    Time
  • ifstream infile
  • ofstream outfile
  • char fileName51
  • coutltlt"Enter the input file name "
  • cingtgtfileName
  • infile.open(fileName) //open the input file
  • .
  • .
  • .
  • coutltlt"Enter the output file name "
  • cingtgtfileName
  • outfile.open(fileName) /open the output file

49
  • The string type and Input/Output Files
  • Values (that is, strings) of the type string are
    not null terminated.
  • Variables of type string can also be used to read
    and store the names of input/output files.
  • The argument to the function open must be a null
    terminated string, that is a C string.
  • if we use a variable of the type string to read
    the name of an input/output file and then use
    this variable to open a file, the value of the
    variable must (first) be converted to a C-string
    (that is, a null-terminated string).

50
  • The header file string contains the function
    c_str, which converts a value of the type string
    to a null-terminated character array (that is,
    C-string).
  • The syntax to use the function c_str is
  • strVar.c_str()
  • where strVar is a variable of the type string.

51
  • ifstream infile
  • string fileName
  • coutltlt"Enter the input file name "
  • cingtgtfileName
  • infile.open(fileName.c_str()) //open the input
    file
Write a Comment
User Comments (0)
About PowerShow.com