Download presentation
Presentation is loading. Please wait.
Published byRoss Maximilian Jefferson Modified over 8 years ago
1
ARRAYS (C) KHAERONI, M.SI
2
OVERVIEW Introduction to Arrays Arrays in Functions Programming with Arrays Multidimensional Arrays
3
INTRODUCTION TO ARRAYS
4
INTRODUCTION Array: variable that can store multiple values of the same type An array is used to process a collection of data of the same type Examples: A list of names A list of temperatures Why do we need arrays? Imagine keeping track of 5 test scores, or 100, or 1000 in memory How would you name all the variables? How would you process each of the variables?
5
DECLARING AN ARRAY An array, named score, containing five variables of type int can be declared as int score[5]; This is like declaring 5 variables of type int: score[0], score[1], …, score[4] The value in brackets is called a subscript or an index
6
ARRAY - MEMORY LAYOUT The definition/declaration of an array: int score[5]; allocates the following memory: first element second element third element fourth element fifth element
7
ARRAY - TERMINOLOGY The definition/declaration of an array: int score[5]; int is the data type of the array elements score is the name of the array 5, in [5], is the size declarator. It shows the number of elements in the array.
8
SIZE DECLARATORS Named constants are commonly used as size declarators. const int SIZE = 5; int tests[SIZE]; This eases program maintenance when the size of the array needs to be changed.
9
INDEXED VARIABLE ASSIGNMENT To assign a value to an indexed variable, use the assignment operator: int n = 2; score[n + 1] = 99; In this example, variable score[3] is assigned 99
10
ACCESSING ARRAY ELEMENTS Each element in an array is assigned a unique subscript. Subscripts start at 0 01234 subscripts:
11
ACCESSING ARRAY ELEMENTS The last element’s subscript is n-1 where n is the number of elements in the array. 01234 subscripts:
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]; Can use integer expression as subscript: int i = 5; cout << tests[i] << endl; Arrays must be accessed via individual elements: cout << tests; // not legal
13
LOOPS AND ARRAYS for-loops are commonly used to step through arrays. Example: for (i = 0; i < 5; i++) { cout << score[i] << " off by “; cout << (max – score[i]) << endl; } could display the difference between each score and the maximum score stored in an array First index is 0 Last index is (size – 1)
14
#include using namespace std; int main () { int i, score[5], max; cout << "Enter 5 scores :\n"; cin >> score[0]; max = score[0]; for (i = 1; i < 5; i++) { cin >> score[i]; if (score[i] > max) max = score[i]; } cout << "The highest score is " << max << endl << "The scores and their\n" << "differences from the highest are:\n"; for (i = 0; i < 5; i++) cout << score[i] << " off by " << (max - score[i]) << endl; return 0; } Predict, what is the output? EXAMPLE
15
CONSTANTS AND ARRAYS Using a constant allows your code to be easily altered for use on a smaller or larger set of data. Example: const int NUMBER_OF_STUDENTS = 50; int score[NUMBER_OF_STUDENTS]; … for ( i = 0; i < NUMBER_OF_STUDENTS; i++) cout << score[i] << " off by " << (max – score[i]) << endl;
16
VARIABLES AND DECLARATIONS Most compilers do not allow the use of a variable to declare the size of an array. Example: cout > number; int score[number]; This code is illegal on many compilers
17
DEFAULT INITIALIZATION Global array all elements initialized to 0 by default Local array all elements uninitialized by default
18
ARRAY INDEX OUT OF RANGE A common error is using a nonexistent index Index values for int a[6] are the values 0 through 5 An index value not allowed by the array declaration is out of range Using an out of range index value does not produce an error message!
19
OUT OF RANGE PROBLEMS If an array is declared as: int a[6]; and an integer is declared as: int i = 7; Executing the statement a[i] = 238; causes… The computer to calculate the address of the illegal a[7] (This address could be where some other variable is stored) The value 238 is stored at the address calculated for a[7] No warning is given!
20
EXAMPLE The following code defines a three-element array, and then writes five values to it!
21
WHAT THE CODE DOES
22
NO BOUNDS CHECKING IN C++ Be careful not to use invalid subscripts. Doing so can corrupt other memory locations, crash program, or lock up computer, and cause elusive bugs.
23
OFF-BY-ONE ERRORS An off-by-one error happens when you use array subscripts that are off by one. This can happen when you start subscripts at 1 rather than 0: // This code has an off-by-one error. const int SIZE = 100; int numbers[SIZE]; for (int count = 1; count <= SIZE; count++) numbers[count] = 0;
24
INITIALIZING ARRAYS To initialize an array when it is declared The values for the indexed variables are enclosed in braces and separated by commas Example: int children[3] = {2, 12, 1}; Is equivalent to: int children[3]; children[0] = 2; children[1] = 12; children[2] = 1;
25
DEFAULT VALUES If too few values are listed in an initialization statement The listed values are used to initialize the first of the indexed variables The remaining indexed variables are initialized to a zero of the base type Example: int a[10] = {5, 5}; initializes a[0] and a[1] to 5 and a[2] through a[9] to 0
26
UN-INITIALIZED ARRAYS If no values are listed in the array declaration, some compilers will initialize each variable to a zero of the base type DO NOT DEPEND ON THIS!
27
SECTION REVIEW Can you 1. Describe the difference between a[4] and int a[5] ? 2. Show the output of char symbol[3] = {'a', 'b', 'c'}; for (int i = 0; i < 3; i++) cout << symbol[i];
28
PROCESSING ARRAY CONTENTS
29
Array elements can be treated as ordinary variables of the same type as the array When using ++, -- operators, don’t confuse the element with the subscript: score[i]++; // add 1 to score[i] score[i++]; // increment i, no // effect on score
30
ARRAY ASSIGNMENT To copy one array to another, Don’t try to assign one array to the other: newScore = score; // Won't work Instead, assign element-by-element: for (i = 0; i < ARRAY_SIZE; i++) newScore[i] = score[i];
31
PRINTING THE CONTENTS OF AN ARRAY You can display the contents of a character array by sending its name to cout : char myName[] = “OnnyThea"; cout << myName << endl; But, this ONLY works with character arrays!
32
PRINTING THE CONTENTS OF AN ARRAY For other types of arrays, you must print element- by-element: for (i = 0; i < ARRAY_SIZE; i++) cout << score[i] << endl;
33
SUMMING AND AVERAGING ARRAY ELEMENTS Use a simple loop to add together array elements: int tnum; double average, sum = 0; for(tnum = 0; tnum < SIZE; tnum++) sum += score[tnum]; Once summed, can compute average: average = sum / SIZE;
34
FINDING THE HIGHEST VALUE IN AN ARRAY int count; int highest; highest = numbers[0]; for (count = 1; count < SIZE; count++) { if (numbers[count] > highest) highest = numbers[count]; } When this code is finished, the highest variable will contains the highest value in the numbers array.
35
USING PARALLEL ARRAYS Parallel arrays: two or more arrays that contain related data A subscript is used to relate arrays: elements at same subscript are related Arrays may be of different types
36
PARALLEL ARRAY EXAMPLE const int SIZE = 5; // Array size int id[SIZE]; // student ID double average[SIZE]; // course average char grade[SIZE]; // course grade... for(int i = 0; i < SIZE; i++) { cout << "Student ID: " << id[i] << " average: " << average[i] << " grade: " << grade[i] << endl; }
37
ARRAYS IN FUNCTIONS
38
Indexed variables can be arguments to functions Example: If a program contains these declarations: int i, n, a[10]; void my_function(int n); Variables a[0] through a[9] are of type int, making these calls legal: my_function( a[0] ); my_function( a[3] ); my_function( a[i]);
39
RETURNING AN ARRAY Recall that functions can return a value of type int, double, char, …, or a class type Functions cannot return arrays We learn later how to return a pointer to an array
40
SECTION REVIEW Can you 1. Write a program that will read up to 10 letters into an array and write the letters back to the screen in the reverse order? abcd should be output as dcba Use a period as a sentinel value to mark the end of input
41
MULTIDIMENSIONAL ARRAYS
42
MULTI-DIMENSIONAL ARRAYS C++ allows arrays with multiple index values char page [30][100]; declares an array of characters named page page has two index values: The first ranges from 0 to 29 The second ranges from 0 to 99 Each index in enclosed in its own brackets Page can be visualized as an array of 30 rows and 100 columns
43
INDEX VALUES OF PAGE The indexed variables for array page are page[0][0], page[0][1], …, page[0][99] page[1][0], page[1][1], …, page[1][99] … page[29][0], page[29][1], …, page[29][99] page is actually an array of size 30 page's base type is an array of 100 characters
44
TWO-DIMENSIONAL ARRAYS Can define one array for multiple sets of data Like a table in a spreadsheet Use two size declarators in definition: const int ROWS = 4, COLS = 3; int exams[ROWS][COLS]; First declarator is number of rows; second is number of columns
45
TWO-DIMENSIONAL ARRAY REPRESENTATION const int ROWS = 4, COLS = 3; int exams[ROWS][COLS]; Use two subscripts to access element: exams[2][2] = 86; exams[0][0]exams[0][1]exams[0][2] exams[1][0]exams[1][1]exams[1][2] exams[2][0]exams[2][1]exams[2][2] exams[3][0]exams[3][1]exams[3][2] columns rowsrows
48
7-48
49
2D ARRAY INITIALIZATION Two-dimensional arrays are initialized row-by-row: const int ROWS = 2, COLS = 2; int exams[ROWS][COLS] = { {84, 78}, {92, 97} }; Can omit inner { }, some initial values in a row – array elements without initial values will be set to 0 or NULL 8478 9297
50
TWO-DIMENSIONAL ARRAY AS PARAMETER, ARGUMENT Use array name as argument in function call: getExams(exams, 2); Use empty [] for row, size declarator for column in prototype, header: const int COLS = 2; // Prototype void getExams(int [][COLS], int); // Header void getExams(int exams[][COLS], int rows)
51
EXAMPLE – THE SHOWARRAY FUNCTION FROM PROGRAM 7-19
52
HOW SHOWARRAY IS CALLED
53
SUMMING ALL THE ELEMENTS IN A TWO-DIMENSIONAL ARRAY Given the following definitions: const int NUM_ROWS = 5; // Number of rows const int NUM_COLS = 5; // Number of columns int total = 0; // Accumulator int numbers[NUM_ROWS][NUM_COLS] = {{2, 7, 9, 6, 4}, {6, 1, 8, 9, 4}, {4, 3, 7, 2, 9}, {9, 9, 0, 3, 1}, {6, 2, 7, 4, 1}};
54
SUMMING ALL THE ELEMENTS IN A TWO- DIMENSIONAL ARRAY // Sum the array elements. for (int row = 0; row < NUM_ROWS; row++) { for (int col = 0; col < NUM_COLS; col++) total += numbers[row][col]; } // Display the sum. cout << "The total is " << total << endl;
55
SUMMING THE ROWS OF A TWO-DIMENSIONAL ARRAY Given the following definitions: const int NUM_STUDENTS = 3; const int NUM_SCORES = 5; double total; // Accumulator double average; // To hold average scores double scores[NUM_STUDENTS][NUM_SCORES] = {{88, 97, 79, 86, 94}, {86, 91, 78, 79, 84}, {82, 73, 77, 82, 89}};
56
SUMMING THE ROWS OF A TWO-DIMENSIONAL ARRAY // Get each student's average score. for (int row = 0; row < NUM_STUDENTS; row++) { // Set the accumulator. total = 0; // Sum a row. for (int col = 0; col < NUM_SCORES; col++) total += scores[row][col]; // Get the average average = total / NUM_SCORES; // Display the average. cout << "Score average for student " << (row + 1) << " is " << average <<endl; }
57
SUMMING THE COLUMNS OF A TWO-DIMENSIONAL ARRAY Given the following definitions: const int NUM_STUDENTS = 3; const int NUM_SCORES = 5; double total; // Accumulator double average; // To hold average scores double scores[NUM_STUDENTS][NUM_SCORES] = {{88, 97, 79, 86, 94}, {86, 91, 78, 79, 84}, {82, 73, 77, 82, 89}};
58
SUMMING THE COLUMNS OF A TWO- DIMENSIONAL ARRAY // Get the class average for each score. for (int col = 0; col < NUM_SCORES; col++) { // Reset the accumulator. total = 0; // Sum a column for (int row = 0; row < NUM_STUDENTS; row++) total += scores[row][col]; // Get the average average = total / NUM_STUDENTS; // Display the class average. cout << "Class average for test " << (col + 1) << " is " << average << endl; }
59
7.9 ARRAYS WITH THREE OR MORE DIMENSIONS
60
Can define arrays with any number of dimensions: short rectSolid[2][3][5]; double timeGrid[3][4][3][4]; When used as parameter, specify all but 1 st dimension in prototype, heading: void getRectSolid(short [][3][5]);
61
7.11 INTRODUCTION TO THE STL VECTOR
62
A data type defined in the Standard Template Library (covered more in Chapter 16) Can hold values of any type: vector scores; Automatically adds space as more is needed – no need to determine size at definition Can use [] to access elements
63
DECLARING VECTORS You must #include Declare a vector to hold int element: vector scores; Declare a vector with initial size 30: vector scores(30); Declare a vector and initialize all elements to 0: vector scores(30, 0); Declare a vector initialized to size and contents of another vector: vector finals(scores);
64
ADDING ELEMENTS TO A VECTOR Use push_back member function to add element to a full array or to an array that had no defined size: scores.push_back(75); Use size member function to determine size of a vector: howbig = scores.size();
65
REMOVING VECTOR ELEMENTS Use pop_back member function to remove last element from vector: scores.pop_back(); To remove all contents of vector, use clear member function: scores.clear(); To determine if vector is empty, use empty member function: while (!scores.empty())...
66
OTHER USEFUL MEMBER FUNCTIONS Member Function DescriptionExample at(elt) Returns the value of the element at position elt in the vector cout << vec1.at(i); capacity() Returns the maximum number of elements a vector can store without allocating more memory maxelts = vec1.capacity(); reverse() Reverse the order of the elements in a vector vec1.reverse(); resize (elts,val) Add elements to a vector, optionally initializes them vec1.resize(5,0); swap(vec2) Exchange the contents of two vectors vec1.swap(vec2);
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.