- An array is defined as the collection of similar type of data items stored at contiguous memory locations.
- Arrays are the derived data type in C programming language which can store the primitive type of data such as int, char, double, float, etc.
- By using the array, we can access the elements easily.
- Example: In a sports game, you might want to store data of all players and give them score. If in baseball there are 162 players where there is a need to store all the variables, so it is very tedious so here array helps us to group a huge data under a single name you don’t need to separate variables of each item or data.
- An array is a fixed number of data items that are of same type.
- Only problem with array is that it can only fix to a specified value like if we assign it to int it only takes integral numbers.
- Example: char myArray[100];
In the above example I will only be able to store upto 100 characters if I am going to exceed out of it then I will be shown an error referred to as array out of bound which you will be seeing in the next few minutes.
- Data items in an array are referred to as elements.
- The elements in an array must be same datatype (int, double, float, long)
- You cannot mix all the data types no such thing as a single array of int and double.
- Declaring an array in a program to a normal variable that contains a single value.
- Difference is that you need a number between the square brackets. []
- Example: long numbers[10];
- The number in the brackets determines that how many elements the array contain. This is called the size of an array or array dimension.
- Data item stored in an array are accessed by the same name.
- You need to select an element by using an index or subscript value between square bracket following the array name.
- Index values are sequential integers that start from zero.
- Arrays are zero based. 0 is the first index value for the first array element.
- For an array of 10 elements, index value 9 refers to the last element.
- It is very common that we assume that an array starts from 1.
- You can use simple integers to explicitly reference the element that you want to access.
- To access the fourth value in an array you need an expression arrayName[3]
- You can also specify an index for an array element by an expression in the square brackets following the array name.
- The expression must result in an integer value that corresponds to one of the possible index values.
- It is common that we use loop to access each element easily.
- Example:
for ( i = 0; i<10; ++i)
printf(“Number is %d”, numbers[i]);
Structure of an array:
Array out of bounds:
- If we use an expression or a variable for an index value that is outside the range of array, your program may crash, or the array can contain garbage data.
- Referred to as array out of bounds.
- Example: If there are 10 variables in an assigned data so when we give a name arrayName[11] then the program will be executed but with an array out of bound errors.
- The compiler cannot check array out of bound errors.
- Also array indexes are within boundaries.
Assigning values to an array:
- A value in an array can be stored in an element by specifying the array element on the left side by an equal to sign.
- Example: grades[100] = 95;
- The value here 95 is stored in the grade array 100.
- Can also use variables to assign array values.
Example:
#include<stdio.h> int main() { int grades[10], i, n, sum = 0, average; printf("Enter the number of elements: "); scanf("%d", &n); for(i = 0; i < n; ++i){ printf("Enter the number%d ", i +1); scanf("%d", &grades[i]); sum+= grades[i]; } average = sum/n; printf("The average of grades is %d", average); return 0; }
Initialisation:
- Initializing an array is assigning initial value to the elements.
- Defining a value for an array makes it easier to detect mistakes.
- To initialise values to an array you can simply provide the values in the list.
- The values in the list are separated by commas and the entire list is enclosed in braces.
- int counters[5] = (0, 0, 0, 0, 0);
- Declares an array counter which contain five integer values and initialises each element to zero.
- int counters[5] = (0, 1, 2, 3, 4);
- Declares an array named integer which sets the values intgers[0] to 0, intgers[1] to 1, intgers[2] to 2, and so on..
- It is not necessary to completely initialise an array.
- If fewer initial values are specified, then only some equal number of elements are initialised remaining are set to zero.
- float sample_data[500] = {100.0, 300.3, 500.5};
- in this first three values are set to 100, 300, and 500 and remaining 497 are set to zero.
- C99 compiler added a feature which is called design initialiser which allows us to pick and choose which elements are initialised.
- We can enclose an element number in a pair of brackets, and specify array elements can be initialised in any order.
- float sample_data[500]= { [2] = 500.5, [1] = 300.0, [0] = 100.0};
- int arr[6] = { [5]= 212};
- Example of traditional initialisation:
#include<stdio.h> #define MONTHS 12 int main() { int days[MONTHS] = {31, 28, 30, 31, 30, 31, 30, 31, 30, 31, 30, 31}; int index; for(index = 0; index < MONTHS; ++index){ printf("Months %d has %2ddys\n", index + 1, days[index]); } return 0; }
***/// Index **///
Index: An Index is a numerical representation of an item’s position in a sequence. This sequence can refer to many things: a list, a string of characters, or any arbitrary sequence of values. In some programming languages, an array can be defined by key-value pairs, where a specific key points to a value.
Output\\:
Repeating an initial value:
- C will not provide any shortcut mechanism for initialising array elements.
Types of Arrays:
- There are three types of arrays:
- A single-dimensional (one bracket with one size)
- Two-dimensional array is as rectangular arrangement like rows and columns.
- One of the most natural applications for a two-dimensional array arises as matrix.
- Two-dimensional array is declared the same way that one-dimensional arrays are
- int matrix[4][5];
- Declares the array matrix to be a 2d array consisting of 4 rows and 5 columns, for a total of 20 elements.
- Note how each dimension is between its own pair of square brackets.
- Initializing a two-dimensional array:
- When listing elements for initialization, the values are listed by the row
- The difference is that you put the initial values for each row between braces, {} and then encloses all the rows between braces.
- int numbers[3][4] = {
- { 10, 20, 30, 40 }, //Values for 1st row
- { 15, 25, 35, 45 }, //Values for 2nd row
- { 47, 48, 49, 50 } //Values for 3rd row
- };
- Commas are required after each brace that closes off a row, except in the case of the final row.
- The use of inner braces is actually optional, but readability is very important.
- As with 1d array it is not required that the entire array be initialized.
- int matrix[4][5] = {
- { 10, 5, -3 },
- { 9, 0, 0},
- { 32, 20, 1 },
- { 0, 0, 8 }
- };
- Only initializes the first three elements of each row of the matrix to be indicated values remaining values are set to zero.
- In this case, the inner pairs of braces are required to force to correct the initialization.
- Designated initializers:
- Subscripts can also be used in the initialization list, in a like manner to single-dimensional array.
- The individual elements of an array are referenced by appending a subscript.
- In square brackets, behind the name. The subscript itself can be any legitimate C expression that yields an integer value, even a general expression.
- Usually, the array size is fixed, while strings can have a variable number of elements.
- int matrix[4][3] = { [0][0] = 1, [1][1] = 5, [2][2] = 9};
- Initializes the three indicated elements of matrix to the specified values. – syntax
- Unspecified elements are set to zero by default.
- Each set of values that initializes the elements in a row is between braces.
- The entire initialization goes between another pair of braces.
- The values for a row are separated by commas.
- Each set of row values is separated from the next set by a comma.
- Other dimensions:
- Everything mentioned so far about 2d arrays can be generalized, to 3d arrays and further
- You can declare 3d array thus way:
- int box[10][20][30];
- A 3d array can be visualized by a stack of data tables.
- Typically, you would use three nested loops to process a 3d array, four nested loops to process a 4d array and so on..
- Initializing an array of more than 2d;
- For arrays of three or more dimensions, the process of initialization is extended.
- A 3d array will have three level of nested braces, the braces with the inner level containing sets of initializing values for a row.
- int number[2][3][4] = {
- {
- { 10, 20, 30, 40 };
- { 15, 25, 35, 45 };
- { 47, 48, 49, 50};
- }
- {
- { 10, 20, 30, 40 };
- { 15, 25, 35, 45 };
- { 47, 48, 49, 50 };
- }
- }
- Processing elements in a n dimensional array:
- You need a nest loop to process all the elements in a multidimensional array.
- To the level of nesting will be the number of array dimensions.
- The level of nesting will be the number of array dimensions.
- Each loop iterates over one array dimension.
- int sum = 0;
- for(int i = 0; i < 2; ++i)
- {
- for(int j = 0; j < 3; ++j)
- {
- for(int k = 0; k < 4; ++k)
- {
- sum += number{i][j][k];
- }
Variables Length Arrays:
- So far, we gave a size number to every datatype.
- The term variable length array does not mean that you can modify the length of the array after you create it.
- A VLA keeps the same size after creation.
- A variable length array allows to specify the size of an array with a variable when creating an array.
- C99 introduced variable length arrays primarily to allow C to become a better language for numerical computing.
- VLA’s makes it easier to convert existing libraries of FORTRAN numerical values routine to C.
- FORTRAN was designed for scientists and engineers and has dominated this field. For the past 30 years FORTRAN has been used for such projects as the design of bridges and aeroplane structures, it is used for factory automation control, for storm drainage design, analysis of scientific data and so on.
- You cannot initialize a VLA in its declaration.