Coit29222 structured programming lecture week 07
Sponsored Links
This presentation is the property of its rightful owner.
1 / 38

COIT29222-Structured Programming Lecture Week 07 PowerPoint PPT Presentation


  • 108 Views
  • Uploaded on
  • Presentation posted in: General

COIT29222-Structured Programming Lecture Week 07 . Reading: Study Guide Book 2, Module 11 Textbook (4 th Ed.), Chapter 4 Textbook (6 th Ed.), Chapter 7 This week, we will cover the following topics: Introduction to Arrays Declaring Arrays Accessing Arrays

Download Presentation

COIT29222-Structured Programming Lecture Week 07

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript


COIT29222-Structured Programming Lecture Week 07

  • Reading: Study Guide Book 2, Module 11

    Textbook (4th Ed.), Chapter 4

    Textbook (6th Ed.), Chapter 7

  • This week, we will cover the following topics:

    • Introduction to Arrays

    • Declaring Arrays

    • Accessing Arrays

    • Passing Arrays to Functions

      NOTE: Arrays should not be used in Assignment 1


Arrays

  • In this class we introduce Arrays which are very useful for storing, searching and sorting data.

  • An array is a collection of memory locations which have same name and same type

  • The idea is quite simple – to begin, let’s go back to the beginning


Variables

write “Number of marks in exam ==> “

read NbrMarks

write “Student’s mark ==> “

read StudentMark

set Percentage to 100 * StudentMark / NbrMarks

write “ Student’s percentage: “

write Percentage

This design uses 3 variables:

NbrMarks, StudentMark, Percentage


Variables

  • Each variable can hold a single value

  • Each variable is associated with a single memory location

  • After running this program (previous slide) with the following inputs (50 and 30)

  • The memory locations used by this program hold the following values

    • NbrMarks: 50

    • StudentMark: 30

    • Percentage: 60

  • Each variable is associated with one memory location and can hold one value

    Number of marks in exam ==> 50


  • Arrays

    • An array can hold more than one value

    • An array called Marks might hold the collection of marks from an exam

    • We refer to values in an array using square brackets and a position number of the value of interest:

      Marks[1]

      Marks[17]

      Marks[123]


    Arrays

    • In some languages, the first value in an array is at position 1

    • However, in C++, the first value in an array is at position 0

    • In our examples, we will adopt this 0-based convention

      Marks[0]  first value held in Marks

      Marks[1]  second value held in Marks

      Marks[2]  third value held in Marks


    Arrays

    • To display the first three values in Marks, we can write (in pseudocode):

      writeMarks[0]

      writeMarks[1]

      writeMarks[2]

    • We’ll look at arrays in C++ in detail later – to output array values we write:

      cout << Marks[0];

      cout << Marks[1];

      cout << Marks[2];


    Arrays

    • We assign values to an array using the same notation:

      readMarks[0] (read value and assign as first in Marks)

      setMarks[5] =0(assign sixth value in Marks to 0)

    • No surprises here in C++:

      cin >> Marks[0];

      Marks[5] = 0;


    Arrays

    • The power of arrays comes from the ability to refer to values stored in an array using a variable

      ( display first mark )

      setMarkNbr=0

      write Marks[MarkNbr]

      ( display second mark )

      setMarkNbr=1

      write Marks[MarkNbr]


    Activity

    • If Marks holds the values shown on the right, what output will the following design produce?

      setNbrMarks=3

      setMarkNbr=0

      whileMarkNbr < NbrMarks

      write”Mark number “, MarkNbr, ” = “

      write Marks[MarkNbr]

      writeNewLine

      setMarkNbr=MarkNbr +1

      ( end of loop over marks )

    Marks

    [0]

    [1]

    [2]

    17

    29

    8


    Activity Feedback

    • If Marks holds the values shown on the right, this design will produce the following output?

      Mark number 0 = 17

      Mark number 1 = 29

      Mark number 2 = 8

    Marks

    [0]

    [1]

    [2]

    17

    29

    8


    Declaring Arrays in C++

    • We must specify the type, array name and array size as follows:

      Type ArrayName [ArraySize];

      Type is data type in C++ eg., int, float, char, etc.

      ArraySize is either a value or a defined variable

    • Below we declare an array to hold 10 integer numbers:

      int Results[10];

    • Our ten integer numbers are held in positions 0 to 9:

      Results[0]

      Results[1]

      :

      Results[9]


    Declaring Arrays in C++

    • A constant is sometimes used to hold the number of values in an array

      const int NBR_RESULTS = 10;

      int Results[NBR_RESULTS];

    • A constant is useful when looping, and also makes it easy to change the array size:

      for (ResultNbr = 0;

      ResultNbr < NBR_RESULTS;

      ResultNbr++)

      cout << “Result[“ << ResultNbr

      << “]: “ Results[ResultNbr]


    Declaring Arrays in C++

    • Take care with loop conditions – one common form is:

      for (ResultNbr = 0;

      ResultNbr < NBR_RESULTS;

      ResultNbr++)

      :

    • An alternative form is:

      for (ResultNbr = 0;

      ResultNbr <= NBR_RESULTS - 1;

      ResultNbr++)

      :


    Initialising Arrays in C++

    • To initialise values in an array, enclose the initial values in braces:

      const NBR_RESULTS = 3;

      int Results[NBR_RESULTS] = {0,1,2};

    • You can initialise all values in an array of integers to zero using:

      int Results[NBR_RESULTS] = {0};

    • If you do not provide enough initial values, others are set to zero!

      int Results[NBR_RESULTS] = {1,2};


    Initialising Arrays in C++

    • If the array size is omitted when it is declared, the compiler canautomatically determine the size from initial values

      int Primes[] = {1, 3, 5, 7, 11};

      is equivalent to

      int Primes[5] = {1, 3, 5, 7, 11};

    • We will get a syntax error, if the number of initialisers is greater than the number of elements.

      int numbers[4] = { 5, 2, 6, 4, 7};

      The above declarationis invalid because there are only 4 array elements and 5 initialisers.


    Referencing Arrays

    • We normally use an integer literal, or an integer variable, to refer to a value of interest in an array

      Results[0]

      Results[ResultNbr]

    • Also, an integer expression can be used

      Results[CurrentPos - 1]

    • A common error when using arrays is to refer to an element that does not exist

    • That is: to use an index value that is outside the acceptable range


    A Common Error Using Arrays Activity

    • Can you see how this code refers to an array element that does not exist?

      #include <iostream.h>

      void main()

      {

      const NBR_RESULTS = 3;

      int Results[NBR_RESULTS] = {0};

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

      cout << Results[i];

      }


    Activity Feedback

    • In the last trip through the loop below, the code refers to Results[3], which does not exist

      #include <iostream.h>

      void main()

      {

      const NBR_RESULTS = 3;

      int Results[NBR_RESULTS] = {0};

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

      cout << Results[i];

      }


    A Common Error Using Arrays

    • C++ does notgive an error when using an index value that is out-of-range

    • It is the programmer’s responsibility to ensure that array references are always within the acceptable range

    • If, in an expression, you refer to an array element that does not exist:

      -Results are unpredictable – the program may give erroneous output, or go into an infinite loop


    A Common Error Using Arrays

    • If you assign a value to an array elementthat does not exists:

      -With luck, you’ll get a memory violation error – so you know there’s a problem

      -Without luck, results are unpredictable:

      • Erroneous output produced

      • Infinite loops lock-up the program

      • Memory used by the operating system is overwritten causing a system crash


    Passing Arrays to Functions

    • Arrays are always passed to functions by reference–but, no ampersand (&) appears before the parameter name

    • Consider a program using an array called Results as shown on the next slide


    Passing Arrays to Functions

    main

    Results

    NbrResults

    Results

    Results

    NbrResults

    GetResults

    DisplayResults

    Results

    NbrResults

    SortResults


    void GetResults(int Results[], int &NbrResults);

    void SortResults(int Results[], int NbrResults);

    void DisplayResults(int Results[], int NbrResults);

    const int MAX_NBR_RESULTS = 10;

    void main (void)

    {

    int Results[MAX_NBR_RESULTS] = {0},

    NbrResults = 0;

    GetResults(Results, NbrResults);

    SortResults(Results, NbrResults);

    DisplayResults(Results, NbrResults);

    }

    notes: here, the maximum number of results is defined

    as a global constant – it is used to define the size of

    the Results array and will also be used to avoid an

    out-of-range error in the GetResults function


    void GetResults(int Results[], int &NbrResults);

    void SortResults(int Results[], int NbrResults);

    void DisplayResults(int Results[], int NbrResults);

    const int MAX_NBR_RESULTS = 10;

    void main (void)

    {

    int Results[MAX_NBR_RESULTS] = {0},

    NbrResults = 0;

    GetResults(Results, NbrResults);

    SortResults(Results, NbrResults);

    DisplayResults(Results, NbrResults);

    }

    notes: the NbrResults parameter is an output of the

    GetResults function, so an ampersand appears before

    its name in the GetResults header and declaration


    void GetResults(int Results[], int &NbrResults);

    void SortResults(int Results[], int NbrResults);

    void DisplayResults(int Results[], int NbrResults);

    const int MAX_NBR_RESULTS = 10;

    void main (void)

    {

    int Results[MAX_NBR_RESULTS] = {0},

    NbrResults = 0;

    GetResults(Results, NbrResults);

    SortResults(Results, NbrResults);

    DisplayResults(Results, NbrResults);

    }

    notes: the Results array is also an output of the

    GetResults function, but an ampersand does not appear

    before its name in GetResults header and declaration


    void GetResults(int Results[], int &NbrResults);

    void SortResults(int Results[], int NbrResults);

    void DisplayResults(int Results[], int NbrResults);

    const int MAX_NBR_RESULTS = 10;

    void main (void)

    {

    int Results[MAX_NBR_RESULTS] = {0},

    NbrResults = 0;

    GetResults(Results, NbrResults);

    SortResults(Results, NbrResults);

    DisplayResults(Results, NbrResults);

    }

    notes: square brackets appear in header and declaration

    to show that a parameter is an array


    void GetResults(int Results[], int &NbrResults);

    void SortResults(int Results[], int NbrResults);

    void DisplayResults(int Results[], int NbrResults);

    const int MAX_NBR_RESULTS = 10;

    void main (void)

    {

    int Results[MAX_NBR_RESULTS] = {0},

    NbrResults = 0;

    GetResults(Results, NbrResults);

    SortResults(Results, NbrResults);

    DisplayResults(Results, NbrResults);

    }

    notes: square brackets do not appear in the function call


    void GetResults(int Results[], int &NbrResults);

    void SortResults(int Results[], int NbrResults);

    void DisplayResults(int Results[], int NbrResults);

    const int MAX_NBR_RESULTS = 10;

    void main (void)

    {

    int Results[MAX_NBR_RESULTS] = {0},

    NbrResults = 0;

    GetResults(Results, NbrResults);

    SortResults(Results, NbrResults);

    DisplayResults(Results, NbrResults);

    }

    notes: one does not need to specify the size of an array

    that appears as a parameter in a function header or

    declaration – it is normal practice to not specify the size

    of a parameter that is an array


    void GetResults(int Results[], int &NbrResults);

    void SortResults(int Results[], int NbrResults);

    void DisplayResults(int Results[], int NbrResults);

    const int MAX_NBR_RESULTS = 10;

    void main (void)

    {

    int Results[MAX_NBR_RESULTS] = {0},

    NbrResults = 0;

    GetResults(Results, NbrResults);

    SortResults(Results, NbrResults);

    DisplayResults(Results, NbrResults);

    }

    notes: however, called functions need to know how many

    values have been stored in the array


    Passing Arrays to Functions

    • The DisplayResults function may look like this

    void DisplayResults(int Results[], int NbrResults)

    {

    cout << "Results: " << endl;

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

    {

    cout << " Result[" << i

    << "]: " << Results[i] << endl;

    }

    }


    Passing Arrays to Functions

    • It is possible to protect the elements of an array passed as an input to a function:

      • Putconstin front of the parameter declaration

      • Any attempt by the function to assign a value to the array will result in anerror when compiled

    void DisplayResults(const int Results[],

    int NbrResults)


    Passing Arrays Elements to Functions

    • We can pass a single array element to a function

      • Whole arrays are always reference parameters

      • Individual elements of an array can be passed as a value or reference parameter

    • Activity: what output do you think the following code will produce?


    #include <iostream.h>

    void PassByValue(int ArrayElement);

    void PassByReference(int &ArrayElement);

    void main(void)

    {

    int Marks[3] = {10,20,30};

    PassByValue(Marks[0]);

    PassByReference(Marks[1]);

    for (int Mark = 0; Mark <= 2; Mark++)

    cout << “Marks[“ << Mark << “]: “ << Marks[Mark] << endl;

    }

    void PassByValue(int ArrayElement)

    {

    ArrayElement++;

    }

    void PassByReference(int &ArrayElement)

    {

    ArrayElement++;

    }

    Activity


    Activity Feedback

    • Output produced by this program is:

    Marks[0]: 10

    Marks[1]: 21

    Marks[2]: 30


    Activity

    • Write a function named Smallest, that accepts an array of double precision real numbers, and returns the smallest value stored in the array

      double Smallest(const double Array[],int NbrValues)

      {

      }


    Some Jargon Used With Arrays

    • element: a value held in an array

    • index : an integer value that refers to an element in an array; we say C++ arrays are zero-indexed – the first position is zero

    • subscript : can be used instead of index – as in “subscript out of range”; can also be used to describe the expression that appears between the brackets to refer to an element in an array

    • dimension : the number of elements in an array - the size of the array


    Summary

    • Simple variables hold a single value

    • Arrays hold a collection of related values

    • First value in a C++ array is at position 0

    • Arrays can be defined for any of the basic data types – int, float, double, char, etc.

    • Arrays can be passed to functions


  • Login