Académique Documents
Professionnel Documents
Culture Documents
• An array is a collection of data that holds fixed number of values of same type.
• It is also known as a set.
• An array is a data type.
• Representation of a large number of homogeneous values.
• Structures of related data items.
• Static entity –same size throughout program.
• Group of consecutive memory locations.
• Array size must be a constant value.
How to declare an array in C?
• To refer to an element, specify
• Array name
• Position number / index/ subscript
• Format:
• data_type array_name[array_size];
• For example: if you want to store marks of 100 students, you can create an array for
it. int marks[100];
• We have declared an array with name “marks” of int type and size 100, that means, it
can hold 100 int values.
• The size and type of arrays cannot be changed after its declaration.
Elements of an array and how to access them?
• By default, first element is always at position 0.
• You can access elements of an array by indices.
• Suppose you declared an array mark as float mark[5]. The first element
is mark[0], second element is mark[1] and so on.
• Arrays have 0 as the first index not 1. In this example, mark[0].
• If the size of an array is n, to access the last element, (n-1) index is used. In this
example, mark[4].
• Suppose the starting address of mark[0] is 2120. Then, the next address, a[1],
will be 2124, address of a[2] will be 2128d and so on. It's because the size of a
float is 4 bytes.
• Hence, address of any element will be
• add of mark[i] = add of mark[0] + i * sizeof(datatype)
Types of arrays
• There are 2 types of C arrays. They are:
• One dimensional array
• Multi dimensional array
• Two dimensional array
• Three dimensional array
• four dimensional array etc…
One-dimensional array
• How to initialize an array in C programming?
• Compile time initialization
• Run time initialization
• int n[ 5 ] = { 1, 2, 3, 4 };
• If not enough initializers, rightmost elements become 0. Here, n[4] will be initialized to zero.
• int n[ 5 ] = { 0 }
• All elements 0
• It is a best practice to initialize an array to zero or null while declaring, if we don’t assign any values to
array.
• Here, x is a two-dimensional (2d) array. The array can hold 12 elements. You can
think the array as table with 3 row and each row has 4 column.
How to initialize a two-dimensional
array?
• There are many ways to initialize a two dimensional array (Compile Time):
• int c[2][3] = {{1, 3, 0}, {-1, 5, 9}};
• int c[][3] = {{1, 3, 0}, {-1, 5, 9}};
• int c[2][3] = {1, 3, 0, -1, 5, 9};
Initializing 2D array (Run time)
Applications of 2D Array
• Multiplication Table
• Matrix Operations
• Addition of matrices
• Multiplication of matrices
• Transpose of a matrix
• Symmetric matrix
• etc.
Three-dimensional array