What is an Array?
● An array is a collection of similar type data items stored in continuous memory
locations.
● Each element has a unique index (starting from 0).
● All elements are accessed by the same array name.
This creates 5 integer locations (marks[0] to marks[4]).
Declaration of Array:
data_type → int, float, char, etc.
size → total number of elements.
Initialization of Arrays:
1. Compile Time Initialization:
data_type array_name[size] = {value1, value2, ...};
Example:
(i) All values given
(ii) Partial initialization
(iii) Without size
2. Run Time Initialization:
Memory Representation of array: Arrays are stored in contiguous
memory locations.
Suppose the base address of marks[0] is 1000 and size of `int = 4 bytes.
Then memory allocation will be like this:
General Formula for Address:
Base address = BA (starting address of marks[0])
Size of datatype = w (in bytes)
Index = i
So if BA = 1000 and w = 4:
● Address of marks[0] = 1000 + (0×4) = 1000
● Address of marks[1] = 1000 + (1×4) = 1004
● Address of marks[2] = 1000 + (2×4) = 1008
● Address of marks[3] = 1000 + (3×4) = 1012
● Address of marks[4] = 1000 + (4×4) = 1016
Operations on Arrays:
1. Traversal:Visiting each element of the array once.
Output:
10 20 30 40 50
2. Insertion:Adding a new element at a given position,
Since arrays have fixed size, shifting is needed.
Example: Insert 25 at position 2
Output:
10 20 25 30 40 50
3. Deletion:
Removing an element from a given position (then
shifting).
Example: Delete element at position 3
4. Searching:Finding the position of an element in the
[Link] method is linear search.
Linear Search:Linearly visiting one by one each element of
array using loop.
Example:
Some important Question:
1. Find an element in array:
[Link] maximum element(done in the class)
[Link] Minimum element.
[Link] 2nd largest element
2D Array:
A two-dimensional (2D) array is like a table (matrix) with rows and
columns.
Each element is accessed using two indices:
First index → row number
Second index → column number
Declaration of 2d array
Example:
Initialization:
(a) Complete Initialization:
(b) Partial Initialization:
Program to demonstrate initialization using scan() and
Traversal of 2d array.
Accessing Elements:using indices we can directly access the element
.
Memory Representation of 2D Arrays:
Two way to store to store 2d array:
[Link]-Major Order (Used in C):All elements of the first row are stored first,
followed by all elements of the second row, and so on.
Example:
Memory (Row-Major):
[Link]-Major Order (Used in Fortran/Matlab):All elements of the first column
are stored first, then second column, and so on.
Program: Add Two Matrices.