4. Arrays

About this Tutorial –

Objectives –

This course is aimed at students who need to get up to speed in C++. The course introduces object-oriented concepts and shows how they are implemented in C++. The course does not require awareness or familiarity with object-oriented programming techniques, but programming experience would be useful but not necessarily required.

Audience

Students who are new to object orientation (or programming) and need to learn C++.

Prerequisites

No previous experience in C++ programming is required. But any experience you do have in programming will help. Also no experience in Visual Studio is required. But again any experience you do have with programming development environments will be a valuable.

Contents

The C++ course covers these topics and more:

  • Introduction to C++: Key features of C++; Defining variables; Formulating expressions and statements; Built-in data types; Console input/output
  • Operators and types: Assignment; Compound Assignment; Increment and decrement operators; Const declarations; Type conversions
  • Going Further with Data Types: Enumerations; Arrays; Using the standard vector class; Using the standard string class; Structures

Download Solutions

Java tutorial


Overview

Estimated Time – 0.5 Hours

Not what you are looking? Try the next tutorial – Pointers and References

  1. An array is an sequential collection of elements of a specified type
    • Elements are accessed by index position, from [0] to [n-1]
    • Once created, an array is fixed size
  2. You can create an array of built-in types or objects
    • We’ll deal with arrays of built-in types here
    • We’ll see how to work with arrays of objects later in the course

Lab 1: Declaring and using arrays

Lab 1: Declaring and using arrays
  1. Creating an Array
    • You can create an array variable as follows:
      • Where type is a primitive type or a class type
      • Where size is a compile-time constant
        type arrayName[size];
    • Array1D

    • Examples:
      • Note that these statements actually reserve the storage for the arrays (on the stack)
        int examMarks[10];
        double rainfallFigures[12];
        string premierLeagueTeams[20];
  2. Using an Array Initializer
    • You can create and populate an array all in one go, using array initializer syntax
      • You can omit the size inside the []
      • The compiler counts the number of terms enclosed in the {}
        type arrayName[] = { value0, value1, ... };
    • Examples:
      const int DAYS_IN_MONTH[] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
      const string SEASONS[] = { "Spring", "Summer", "Autumn", "Winter" };
      string topTeams[] = { "Man City", "Man Utd", "Arsenal" };
  3. Accessing Elements in an Array
    • To access elements in an array:
      • No bounds checking in C++!
      • If you overflow, you access whatever data is in that space!
        arrayName[index]
    • You can read and write array elements
      • As long as the array isn’t const, of course
        string topTeams[] = { "Man City", "Man Utd", "Arsenal" };
        cout << "The top team is " << topTeams[0] << endl; topTeams[1] = "Swansea City"; cout << "The next best team is " << topTeams[1] << endl;
  4. Traversing an Array
    • You can traverse an array using a for loop
      • This is the traditional approach
      • Use an integer array index that ranges from 0 to (n-1)
        const string DAYS_OF_WEEK[] = {"Sunday", "Monday", "Tuesday", "Wednesday",
                         "Thursday", "Friday", "Saturday"};
        for (int i = 0; i < 7; i++) {  cout << "Day " << i << " is " << DAYS_OF_WEEK[i] << endl; }
    • Note 1:
      • Arrays don't have a "length" property in C++
    • Note 2:
      • There is no such construct as a "foreach" loop in C++
      • Although there's an algorithm that emulates it - see later
  5. Copying Arrays
    • You can't assign arrays to each other
      int array1[10];
      int array2[10];
      array1 = array2;
    • Instead, you must assign each array element individually
      int array1[10];
      int array2[10];
      for (int i = 0; i < 10; i++) {  array1[i] = array2[i]; }
    • Note: There is no "array" class in C++
Lab
  1. Declaring a 2D array
    • In Visual Studio, create a new C++ project named ArraysApp2 in the student folder. Write code to declare and use a 2D array, to hold the lap times for athletes in a 1600m race. Suggestions and requirements:
      • First, write a header file named AthleteDeclarations.h. In the header file, add two #define directives as follows:
        • Define a symbol named NUM_ATHLETES, and set this value to 8
          #define NUM_ATHLETES 8
        • Define a symbol named NUM_LAPS, and set this value to 4 (there are 4 laps in a 1600m race).
          #define NUM_LAPS 4
        • View code file.
      • Now, in your source code file, define a 2D array to hold the lap times for all the athletes. The 2D array should have NUM_ATHLETES rows and NUM_LAPS columns. Note that the lap times will be fractional values, not whole numbers
        double athleteTimes[NUM_ATHLETES][NUM_LAPS];
      • Write a for-loop to prompt the user to enter the lap times for each athlete. For example:
        // Words
        Athlete 1, lap 1 time? xxx
        Athlete 1, lap 2 time? xxx
        Athlete 1, lap 3 time? xxx
        ...
        Athlete 2, lap 1 time? xxx
        Athlete 2, lap 2 time? xxx
        etc...
        // CODE
         cout << "Enter the lap times for each athlete:" << endl;  for (int athlete = 0; athlete < numAthletes; athlete++)  {   for (int lap = 0; lap < numLaps; lap++)   {    double time;    cout << "Athlete " << athlete + 1 << ", lap " << lap + 1 << " time: ";    cin >> time;
           athleteLapTimes[athlete][lap] = time;
          }
         }
      • View code file.
      • Write another for-loop to display all the lap times for each athlete
         cout << endl << "Lap times for each athlete:";  for (int athlete = 0; athlete < numAthletes; athlete++)  {   cout << endl << "Athlete " << athlete + 1 << " lap times: ";   for (int lap = 0; lap < numLaps; lap++)   {    cout << athleteLapTimes[athlete][lap] << " ";   }  }  cout << endl;
      • View code file.

Lab 2: Passing arrays into functions

Lab 2: Passing arrays into functions
  1. Overview
    • When you pass an array into a function:
      • The function receives the address of the first element in the array
      • In other words, the function has access to the original array!
      • This is different from how all other types work in C++!!!
    • When passing arrays into functions, it's commonplace to pass two parameters
      • The array itself
      • The count of elements in the array
  2. Example
    • Here's an example of a function that displays an array of integer values to the console
      • Note that you do not specify the array size inside the []
      • This is because the function only receives the address of the first element, not a copy of the entire array
        void displayArray(int array[], int count)
        {
         for (int i = 0; i < count; i++)   cout << array[i] << endl }
      • You can pass any array of integers into the example function
        int examMarks[10];
        int lotteryNumbers[6];
        ...
        displayArray(examMarks, 10);
        displayArray(lotteryNumbers, 6);
  3. Updating Arrays
    • Functions are allowed to modify the elements in an array
      • Because functions receive the start address of the actual array
    • Example:
      void tripleValues(int array[], int count)
      {
       for (int i = 0; i < count; i++)   array[i] *= 3; } int myNumbers[] = { 10, 20, 30, 40, 50 }; displayArray(myNumbers, 5); // Displays 10, 20, 30, 40, 50. tripleValues(myNumbers, 5); // Updates actual array elements. displayArray(myNumbers, 5); // Displays 30, 60, 90, 120, 150.
  4. Protecting Arrays
    • If you want to indicate (and ensure) a function doesn't modify an array...
      • Declare the array as const (in the prototype and the definition)
      • Client code can rest assured that the function will not change the array values
      • Very good practice!
    • Example:
      void safeDisplayArray(const int array[], int count)
      {
       for (int i = 0; i < count; i++)   cout << array[i] << endl }
Lab
  1. Passing a 2D array into a function
    • Write functions to populate and display your 2D array of athlete lap times. Here are the function prototypes for you to add to your header file:
      • GetAthleteLapTimes
        void GetAthleteLapTimes(double athleteLapTimes[][NUM_LAPS],
                int numAthletes);
      • DisplayAthleteLapTimes
        void DisplayAthleteLapTimes(const double athleteLapTimes[][NUM_LAPS],
                int numAthletes);
      • View code file.
    • Implement these functions in your source file. This is easy, you can simply copy-and-paste much of the code from main(), and then just call your new functions from main()
      // From main()
      GetAthleteLapTimes(athleteTimes, NUM_ATHLETES, NUM_LAPS);
      DisplayAthleteLapTimes(athleteTimes, NUM_ATHLETES, NUM_LAPS);
      // E.g. in source file
      void GetAthleteLapTimes(double athleteLapTimes[][NUM_LAPS], int numAthletes, int numLaps)
      {
       cout << "Enter the lap times for each athlete:" << endl;  ... }
    • View code file.

Lab 3: Multi-dimensional arrays

Lab 3: Multi-dimensional arrays
  1. Overview
    • All the arrays we've seen so far have been 1-dimensional except in the labs
      • Declared and indexed using a single set of []
    • C++ also allows you to define multi-dimensional arrays
      • E.g. for grids, cubes, etc.
      • Use multiple sets of []
  2. Creating a Multi-Dimensional Array
    • To create a multi-dimensional array (e.g. 2 dimensions):
      type arrayName[numRows][numCols];
    • You can use initializer syntax, with multiple sets of braces
      type arrayName[][numCols] = {
               { ..., ..., ... },
               { ..., ..., ... },
             };
    • Array2D

    • To traverse a multi-dimensional array, use nested loops
      for (int r = 0; r < numRows; r++) {  for (int c = 0; c < numCols; c++)  {   // Access element arrayName[r][c]  } }
  3. Passing into Functions
    • You can pass multi-dimensional arrays into a function
      • Specify the correct number of []
      • You must specify all but the first dimension
        void displayPeoplesLotteryNumbers(int lotteryNumbers[][6], int numPeople)
        {
         for (int r = 0; r < numPeople; r++)  {   cout << "Here are the lottery numbers for person " << r << endl;   for (int c = 0; c < 6; c++)   {    cout << lotteryNumbers[r][c] << endl   }  } } // Client Side int myFriendsLotteryNumbers[10][6]; // 10 rows, 6 columns per row. displayPeoplesLotteryNumbers(myFriendsLotteryNumbers, 10);
Lab
  1. Further array processing
    • Calculate the total finishing time for each athlete as follows:
      • Write a new function named DisplayFinishingTimes()
        void DisplayFinishingTimes(const double athleteLapTimes[][NUM_LAPS], int numAthletes, int numLaps)
        {
         ...
        }
      • In this function, write a loop to step through all the athlete lap times. Then write a nested loop to add up the 4 lap times for that athlete. Display the total time for each athlete
         cout << endl << "Total finishing times for each athlete: " << endl;  for (int athlete = 0; athlete < numAthletes; athlete++)  {   double athleteTotalTime = 0;   for (int lap = 0; lap < numLaps; lap++)   {    athleteTotalTime += athleteLapTimes[athlete][lap] ;   }   cout << "Total time for athlete " << athlete + 1 << ": " << athleteTotalTime << endl;  }
      • Call your new function from main(), to test it
        DisplayFinishingTimes(athleteTimes, NUM_ATHLETES, NUM_LAPS);
    • View code file.

 

Well done. You have completed the tutorial in the C++ course. The next tutorial is

5. Pointers and References


Back to beginning
Copyright © 2016 TalkIT®





If you liked this post, please comment with your suggestions to help others.
If you would like to see more content like this in the future, please fill-in our quick survey.
Scroll to Top