Lecture 6-10
Lecture 6-10
Dr Lavika Goel
MNIT Jaipur
Arrays
• Arrays are data structure consisting of related data items of
the same type.
• Arrays are “static” entities in that they remain the same size
throughout program execution and can be initialised only
during the declaration time.
• Array name is a pointer to the base address of the array.
• An array is a group of contiguous memory locations
that all have the same type.
Arrays
• Any array element can be referred by giving
the array’s name followed by the position
number of the element in square brackets
([]), which is called index or subscript.
• An index must be an integer
• The first element in every array is the zeroth
element.
• An array name is like any other identifiers
• The brackets used to enclose the index of an
array are actually an operator in C.
Arrays
Arrays
Arrays
Defining Arrays
• Arrays occupy space in memory.
• The type of each element and the number of
elements each array requires are to be
specified so that the computer can reserve
the appropriate amount of memory.
• The definition int b[100] reserves 100
elements for integer array b with indices in
the ranges 0–99
• Arrays may contain other data types like char,
float, double etc.
Initializing an Array
• The elements of an array can also be initialized when
the array is defined by following the definition with an
equals sign and braces, {}, containing a comma-
separated list of array initializers
• If there are fewer initializers than elements in the
array, the remaining elements are initialized to 0
• If number of initializers assigned are more than the
size of the array, a syntax error is generated
• If the array size is omitted from a definition with an
initializer list, the size of array will be the number of
elements in the initializer list
Example 1
Example 2: Initialization using a loop
Calculating the MemoryLocation
For n+1 th element
& a[n] = a + (n x sizeof(datatype)]
Row 0 8 16 9 52
Row 1 3 15 27 6
Row 2 14 25 2 10
total = 0;
for (int row = 0; row < 3; ++row)
for (int col = 0; col < 3; ++col)
total += a[row][col];
Multidimensional Array
C programming language allows multidimensional
arrays. Here is the general form of a multidimensional
array declaration −
type name[size1][size2]...[sizeN];
int threedim[5][10][4];
Two dimensional Array
Matrix Addition
Matrix Multiplication
Matrix Addition in C
Matrix Multiplication
Matrix multiplication
Matrix Multiplication
If matrix 1 =
123
456
789
And matrix 2 =
987
654
321
Product of both matrices =
30 24 18
84 69 54
138 114 90
FUNCTIONS WITH 2D ARRAYS
• a[i] *(a+i)
• a[i][j] *(*(a+i)+j)
Example
Output
Array of pointers
Example
Array of structures
Initialising array of structures