Arduino — Arrays
Arduino Long Distance Communication
14 Lectures 1 hours
Arduino Wireless Power Transmission
13 Lectures 50 mins
Arduino Car Parking Assistant
9 Lectures 42 mins
An array is a consecutive group of memory locations that are of the same type. To refer to a particular location or element in the array, we specify the name of the array and the position number of the particular element in the array.
The illustration given below shows an integer array called C that contains 11 elements. You refer to any one of these elements by giving the array name followed by the particular element’s position number in square brackets ([]). The position number is more formally called a subscript or index (this number specifies the number of elements from the beginning of the array). The first element has subscript 0 (zero) and is sometimes called the zeros element.
Thus, the elements of array C are C[0] (pronounced “C sub zero”), C[1], C[2] and so on. The highest subscript in array C is 10, which is 1 less than the number of elements in the array (11). Array names follow the same conventions as other variable names.
A subscript must be an integer or integer expression (using any integral type). If a program uses an expression as a subscript, then the program evaluates the expression to determine the subscript. For example, if we assume that variable a is equal to 5 and that variable b is equal to 6, then the statement adds 2 to array element C[11].
A subscripted array name is an lvalue, it can be used on the left side of an assignment, just as non-array variable names can.
Let us examine array C in the given figure, more closely. The name of the entire array is C. Its 11 elements are referred to as C[0] to C[10]. The value of C[0] is -45, the value of C[1] is 6, the value of C[2] is 0, the value of C[7] is 62, and the value of C[10] is 78.
To print the sum of the values contained in the first three elements of array C, we would write −
To divide the value of C[6] by 2 and assign the result to the variable x, we would write −
Declaring Arrays
Arrays occupy space in memory. To specify the type of the elements and the number of elements required by an array, use a declaration of the form −
The compiler reserves the appropriate amount of memory. (Recall that a declaration, which reserves memory is more properly known as a definition). The arraySize must be an integer constant greater than zero. For example, to tell the compiler to reserve 11 elements for integer array C, use the declaration −
Arrays can be declared to contain values of any non-reference data type. For example, an array of type string can be used to store character strings.
Examples Using Arrays
This section gives many examples that demonstrate how to declare, initialize and manipulate arrays.
Example 1: Declaring an Array and using a Loop to Initialize the Array’s Elements
The program declares a 10-element integer array n. Lines a–b use a For statement to initialize the array elements to zeros. Like other automatic variables, automatic arrays are not implicitly initialized to zero. The first output statement (line c) displays the column headings for the columns printed in the subsequent for statement (lines d–e), which prints the array in tabular format.
Result − It will produce the following result −
Example 2: Initializing an Array in a Declaration with an Initializer List
The elements of an array can also be initialized in the array declaration by following the array name with an equal-to sign and a brace-delimited comma-separated list of initializers. The program uses an initializer list to initialize an integer array with 10 values (line a) and prints the array in tabular format (lines b–c).
Result − It will produce the following result −
Example 3: Summing the Elements of an Array
Often, the elements of an array represent a series of values to be used in a calculation. For example, if the elements of an array represent exam grades, a professor may wish to total the elements of the array and use that sum to calculate the class average for the exam. The program sums the values contained in the 10-element integer array a.
Result − It will produce the following result −
Arrays are important to Arduino and should need a lot more attention. The following important concepts related to array should be clear to a Arduino −
S.NO. | Concept & Description |
---|---|
1 | Passing Arrays to Functions To pass an array argument to a function, specify the name of the array without any brackets. arrayDescriptionAn array is a collection of variables that are accessed with an index number. Arrays in the C++ programming language Arduino sketches are written in can be complicated, but using simple arrays is relatively straightforward. Creating (Declaring) an ArrayAll of the methods below are valid ways to create (declare) an array. You can declare an array without initializing it as in myInts. Accessing an ArrayArrays are zero indexed, that is, referring to the array initialization above, the first element of the array is at index 0, hence mySensVals[0] == 2, mySensVals[1] == 4, and so forth. It also means that in an array with ten elements, index nine is the last element. Hence: For this reason you should be careful in accessing arrays. Accessing past the end of an array (using an index number greater than your declared array size — 1) is reading from memory that is in use for other purposes. Reading from these locations is probably not going to do much except yield invalid data. Writing to random memory locations is definitely a bad idea and can often lead to unhappy results such as crashes or program malfunction. This can also be a difficult bug to track down. Unlike BASIC or JAVA, the C++ compiler does no checking to see if array access is within legal bounds of the array size that you have declared. arrayDescriptionAn array is a collection of variables that are accessed with an index number. Arrays in the C programming language, on which Arduino is based, can be complicated, but using simple arrays is relatively straightforward. Creating (Declaring) an ArrayAll of the methods below are valid ways to create (declare) an array. You can declare an array without initializing it as in myInts. Accessing an ArrayArrays are zero indexed, that is, referring to the array initialization above, the first element of the array is at index 0, hence mySensVals[0] == 2, mySensVals[1] == 4, and so forth. It also means that in an array with ten elements, index nine is the last element. Hence: For this reason you should be careful in accessing arrays. Accessing past the end of an array (using an index number greater than your declared array size — 1) is reading from memory that is in use for other purposes. Reading from these locations is probably not going to do much except yield invalid data. Writing to random memory locations is definitely a bad idea and can often lead to unhappy results such as crashes or program malfunction. This can also be a difficult bug to track down. Unlike BASIC or JAVA, the C compiler does no checking to see if array access is within legal bounds of the array size that you have declared. arrayDescriptionAn array is a collection of variables that are accessed with an index number. Arrays in the C++ programming language Arduino sketches are written in can be complicated, but using simple arrays is relatively straightforward. Creating (Declaring) an ArrayAll of the methods below are valid ways to create (declare) an array. You can declare an array without initializing it as in myInts. Accessing an ArrayArrays are zero indexed, that is, referring to the array initialization above, the first element of the array is at index 0, hence mySensVals[0] == 2, mySensVals[1] == 4, and so forth. It also means that in an array with ten elements, index nine is the last element. Hence: For this reason you should be careful in accessing arrays. Accessing past the end of an array (using an index number greater than your declared array size — 1) is reading from memory that is in use for other purposes. Reading from these locations is probably not going to do much except yield invalid data. Writing to random memory locations is definitely a bad idea and can often lead to unhappy results such as crashes or program malfunction. This can also be a difficult bug to track down. Unlike BASIC or JAVA, the C++ compiler does no checking to see if array access is within legal bounds of the array size that you have declared. МассивыОбъявление массиваМассив (array) – это совокупность переменных одного типа, к которым можно обратиться с помощью общего имени и индекса, т.е. номера элемента в массиве. По сути это набор переменных, которые называются одним именем и имеют личные номера. Для объявления массива достаточно указать квадратные скобки после имени переменной с любым типом данных. Указать компилятору размер массива можно двумя способами: явным числом в квадратных скобках, либо при объявлении записать в каждую ячейку значение, тогда компилятор сам посчитает их количество. Рассмотрим пример объявления массива разными способами:
Обращение к элементамОбращение к элементу массива осуществляется точно так же, в квадратных скобках. Важно помнить, что отсчёт в программировании начинается с нуля, и первый элемент массива имеет номер 0 (ноль): Размер массиваДля определения размера массива можно воспользоваться функцией sizeof() , которая вернёт размер массива в количестве байтов. Зачем? Допустим в программе массив задаётся без указания размера, но элементы задаются явно (в фигурных скобках) и в процессе разработки программы размер массива может меняться. Чтобы не пересчитывать размер вручную и не менять его везде в программе, можно использовать эту функцию. Примечание: если размер массива неизвестен на момент компиляции программы – sizeof() не сможет его посчитать и выдаст размер указателя (2 байта на AVR). Ещё один момент: sizeof(имя_массива) даёт вес массива, а не количество элементов в нём! Если массив состоит из элементов типа byte – его вес совпадёт с размером. В остальных случаях нужно разделить вес массива на вес одного элемента, например так: sizeof(arr) / sizeof(arr[0]) – делим на вес элемента, чтобы не привязываться к типам данных. Результат вычисляется на этапе компиляции и в процессе работы программы время на вычисление не тратится. Многомерные массивыВыше мы рассмотрели одномерные массивы, в которых элементы определяются просто порядковым номером (индексом). Можно задавать и многомерные массивы, в которых адрес элемента будет определяться несколькими индексами. Например двумерный массив, он же матрица, он же таблица, каждый элемент имеет номер строки и столбца. Задаётся такой массив следующим образом: тип имя[строки][столбцы] Очень важно помнить, что при объявлении массива с вручную вписанными данными нужно обязательно указать размер количества ячеек в измерении на 1 меньше размерности массива (для двумерного – обязательно указать размер одного из измерений, для трёхмерного – два, и т.д.). В рассмотренном выше двумерном массиве myMatrix элемент с адресом 0, 2 (строка 0 столбец 2) имеет значение 12. Обращение к этому элементу например с целью перезаписи будет выглядеть так: С элементами массивов можно производить такие же действия, как с обычными переменными, т.е. всю математику, которую мы рассматривали в предыдущем уроке. Также не стоит забывать, что массивом может быть почти любой тип данных: численные переменные, структуры, классы, строки… Область видимости точно так же применяется к массивам, ведь массив – это по сути обычная переменная. Видео |