Presentation is loading. Please wait.

Presentation is loading. Please wait.

Section 5 - Arrays. Problem solving often requires information be viewed as a “list” List may be one-dimensional or multidimensional List is implemented.

Similar presentations


Presentation on theme: "Section 5 - Arrays. Problem solving often requires information be viewed as a “list” List may be one-dimensional or multidimensional List is implemented."— Presentation transcript:

1 Section 5 - Arrays

2 Problem solving often requires information be viewed as a “list” List may be one-dimensional or multidimensional List is implemented by an array construct.

3 Array is a group of variables - Same name and data type - Variables are related in some way - Most commonly used – multi-dimensional - One-dimensional array - Two-dimensional array

4 Arrays Arrays allow you to store a number of similar type items but with a single name. Array: variable that can store multiple values of the same type Values are stored in adjacent memory locations Declared using [] operator: int tests[5]; This creates an array named tests with 5 elements (storage locations)

5 Array Terminology In the definition int tests[5]; int is the data type of the array elements tests is the name of the array 5, in [5], is the size declarator. It shows the number of elements in the array.

6 Array Declaration element-type array-name [array-size]; Type of all the values in the array Name of the entire collection of values Integer expression indicating number of elements in the array

7 Declaring Array Variables datatype arrayName[arraySize]; Example: double myList[10]; C++ requires that the array size used to declare an array must be a constant expression. For example, the following code is illegal: int size = 4; double myList[size]; // Wrong But it would be OK, if size is a constant as follow: const int size = 4; double myList[size]; // Correct

8 Suppose const int N = 20; const int M = 40; const int MaxStringSize = 80; const int MaxListSize = 1000; Then the following are all valid array definitions int A[10]; // array of 10 ints char B[MaxStringSize]; // array of 80 chars double C[M*N]; // array of 800 floats int Values[MaxListSize]; // array of 1000 ints

9 Array - Memory Layout The definition: int tests[5]; // size is 5 elements allocates the following memory: first element second element third element fourth element fifth element

10 Accessing Array Elements Each array element has a subscript, used to access the element. Subscripts start at 0 01234 Subscripts

11 Array Subscripts Enclosed in brackets ([ ]) Indicates which element is referenced by position Array subscript value is different than array element value Subscript can be an expression of any integer type To be valid, subscript must be a value between 0 and one less than the array size

12 Accessing Array Elements Array elements can be used as regular variables: tests[0] = 79; cout << tests[0]; cin >> tests[1]; tests[4] = tests[0] + tests[1]; Arrays must be accessed via individual elements: cout << tests; // not legal

13 Accessing Array Contents Can access element with constant subscript: cout << tests[3] << endl; Can use integer expression as subscript: for (i = 0; i < 5; i++) cout << tests[i] << endl;

14 Suppose int A[10]; // array of 10 int A[0], … A[9] To access individual element must apply a subscript to list name A A subscript is a bracketed expression also known as the index First element of list has index 0 A[0] Second element of list has index 1, and so on A[1] Last element has an index one less than the size of the list A[9] Incorrect indexing is a common error A[10] // does not exist

15 Array Initialization List of initial values enclosed in braces ({ }) following assignment operator (=) Values from initialization list are assigned in order to array elements Length of initialization list cannot exceed size of the array Size of array can be automatically set to number of initializing values using empty brackets ([ ])

16 Initialization element-type array-name [array-size] = {initialization-list}; float x[8] = {16.0, 12.0, 6.0, 8.0, 2.5, 12.0, 14.0, -54.5}; 16.012.06.08.02.512.014.0-54.5

17 cout << x[0]; x[3] = 25.0; sum = x[0] + x[1]; sum += x[2]; x[3] += 1.0; x[2] = x[0] + x[1];

18 double myList[4] = {1.9, 2.9, 3.4, 3.5}; This shorthand notation is equivalent to the following statements: double myList[4]; myList[0] = 1.9; myList[1] = 2.9; myList[2] = 3.4; myList[3] = 3.5;

19 C++ allows you to omit the array size when declaring and creating an array using an initializer. For example, the following declaration is valid double myList[] = {1.9, 2.9, 3.4, 3.5}; C++ automatically figures out how many elements are in the array.

20 C++ allows you to initialize a part of the array. For example, the following statement assigns values 1.9, 2.9 to the first two elements of the array. The other two elements will be set to zero. Note that if an array is declared, but not initialized, all its elements will contain “unkowns”, like all other local variables. double myList[4] = {1.9, 2.9};

21 Access to Array Elements Random Access –Access elements is any order Sequential Access –Process elements in sequential order starting with the first

22 Example of Sequential Access int cube[10]; for (int i = 0; i < 10; i++) cube[i] = i * i * i;

23 Displaying an Array // List A of n elements has already been set for (int i = 0; i < n; ++i) { cout << A[i] << " "; } cout << endl;

24 Finding the smallest index of the largest element double max = myList[0]; int indexOfMax = 0; for (int i = 1; i < ARRAY_SIZE; i++) { if (myList[i] > max) { max = myList[i]; indexOfMax = i; }

25 #include using namespace std; int main() { const int NUMBER_OF_ELEMENTS = 10; double numbers[NUMBER_OF_ELEMENTS]; double sum = 0; for (int i = 0; i < NUMBER_OF_ELEMENTS; i++) { cout << "Enter a new number: "; cin >> numbers[i]; sum += numbers[i]; } double average = sum / NUMBER_OF_ELEMENTS; int count = 0; // The number of elements above average for (int i = 0; i < NUMBER_OF_ELEMENTS; i++) if (numbers[i] > average) count++; cout << "Average is " << average << endl; cout << "Number of elements above the average " << count << endl; return 0; } Example

26 Multidimensional Arrays Allows for complex arrangement of data Can have many dimensions Syntax element-type arrayName [size 1 ] [size 2 ]…[size n ]; Example double table[NROWS] [NCOLS];

27 Declaring Two- Dimensional Arrays Most common multidimensional array Represents a table Example char ticTacToe[3][3]; Access ticTacToe[1][2] Row Column

28 Function sumMatrix float sumMatrix (float table[NROWS][NCOLS]) { float sum = 0.0; // Add each array element value to sum. for (int r = 0; r < NROWS; r++) for (int c = 0; c < NCOLS; c++) sum += table[r][c]; return sum; }

29

30 Example - A classroom seating plan

31 Example const int NUM_ROWS = 11; const int SEATS_IN_ROW = 9; string seatPlan [NUM_ROWS][SEATS_IN_ROW];... seatPlan[0][8] = “Gerry”;

32 Initialization Each inner pair of braces contains initial values for one row of the array matrix const int NUM_ROWS = 2; const int NUM_COLS = 3; float matrix[NUM_ROWS][NUM_COLS] ={{5.0, 4.5, 3.0}, {-16.0, -5.9, 0.0}};

33 Two-dimensional Array Illustration

34

35 Nested Loops for 2-D Arrays Row order –use row subscript as outer loop control variable Column order –use column subscript as outer loop control variable

36 Initializing Arrays with Random Values The following loop initializes the array with random values between 0 and 99: for (int row = 0; row < rowSize; row++) { for (int column = 0; column < columnSize; column++) { matrix[row][column] = rand() % 100; }

37 Printing Arrays To print a two-dimensional array, you have to print each element in the array using a loop like the following: for (int row = 0; row < rowSize; row++) { for (int column = 0; column < columnSize; column++) { cout << matrix[row][column] << " "; } cout << endl; }

38 Summing Elements by Column For each column, use a variable named total to store its sum. Add each element in the column to total using a loop like this: for (int column = 0; column < columnSize; column++) { int total = 0; for (int row = 0; row < rowSize; row++) total += matrix[row][column]; cout << "Sum for column " << column << " is " << total << endl; }

39 No Bounds Checking in C++ C++ does not check if an array subscript is in the range of values for subscripts of the array Can access memory using subscripts that is before or after the memory for an array Can corrupt other memory locations, crash program, or lock up computer Need to be careful!


Download ppt "Section 5 - Arrays. Problem solving often requires information be viewed as a “list” List may be one-dimensional or multidimensional List is implemented."

Similar presentations


Ads by Google