Notes on Array
Notes on Array
Here:
• int = data type
• numbers = name of the array
• 5 = number of elements it can store (index from 0 to 4)
Initialize an array at the time of declaration: Values to an array can be assigned during
its declaration. This process is known as initialization at the time of declaration.
Syntax for this is:
Here, the array numbers is created with a size of 5. Each value is assigned in order
to each index viz. numbers[0] = 10, numbers[1] = 20, …, numbers[4] = 50
Size determined by the compiler: If the size is omitted while initializing an array, the
compiler will automatically calculate the size based on the number of values provided.
Example: int numbers[] = {10, 20, 30, 40, 50}; // Automatically size = 5
Since there are 5 values in the initializer list, the compiler sets the size of numbers to 5.
This saves manual effort and avoids mismatch between declared size and number of
initial values.
Types of Arrays: On the basis of dimensions, there are 3 type of array in C:-
For 1D array
• suppose A be a 1D array of size N. Each element takes size bytes. Base is the
base address. You want to access A[i]
Address(A[i]) = Base + (i × size)
Ex.:- If Base = 2001, size = 2, and i = 3, then:
Address(A[3]) = 2001 + (3 × 2) = 2007
Row-Major Order
• In Row-Major Order, the rows of the array are stored one after the other in
memory.
• Example:
A[3][4] =
[ [1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12] ]
• Memory Layout:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
• Address Calculation (Row-Major):
Address(A[i][j]) = Base + ((i * N) + j) * size
Where: Base = Base address of the array
i = Row index
j = Column index
N = Total number of columns
size = Size of each element in bytes
Column-Major Order
Comparison Diagram
Sparse Matrices and Their Representation
Definition:
- Opposite to sparse, a matrix where most elements are non-zero is called Dense
Matrix.
Example:
Matrix (4x5): Triplet Representation:
00 0 5 0 Row Col Value
00 8 0 0 0 3 5
00 0 0 0 1 2 8
06 0 0 9 3 1 6
3 4 9
Example:
Original Matrix: CSR Representation: Build rowPtr Array
rowPtr[i] to Corresponds Range in Non-Zero
0 0 3 0 4 0 values[] = [3, 4, 5, 2, 6, 1] rowPtr[i+1] to Row values[] Elements
0 0 0 0 0 0 colIndex[] = [2, 4, 0, 3, 5, 1] values[0]
5 0 0 2 0 0 rowPtr[] = [0, 2, 2, 4, 5, 6] 3 at col 2,
0→2 Row 0 to
4 at col 4
0 0 0 0 0 6 values[1]
0 1 0 0 0 0 2→2 Row 1
(empty
—
row)
values[2] 5 at col 0,
2→4 Row 2
to [3] 2 at col 3
4→5 Row 3 values[4] 6 at col 5