02 - Arrays
02 - Arrays
- CONSTANT ACCESS
- BIG O COMPLEXITY
- DRY RUNNING OF 2D ARRAY
- PRACTICE QUESTIONS
Engr. Dr. Sidra Sultana
WHAT IS ARRAY?
● To write
array_addr+elem_size*(i-first_index)
=1000+8*(6-0)
=1048
CALCULATING THE ADDRESS OF ANY ELEMENT IN THE 1-D ARRAY:
EXAMPLE 1:
Given the base address of an array
A[1300 ………… 1900] as 1020
and the size of each element is 2 bytes in the memory,
find the address of A[1700].
SOLUTION
Given:
Base address B = 1020
Lower Limit/Lower Bound of subscript LB = 1300
Storage size of one element store in any array W = 2 Byte
Subset of element whose address to be found I = 1700
Formula used:
Address of A[I] = B + W * (I – LB)
Solution: Address of A[1700] = 1020 + 2 * (1700 – 1300)
= 1020 + 2 * (400)
= 1020 + 800
Address of A[1700] = 1820
MULTI-DIMENSIONAL ARRAYS (ARRAY OF AN ARRAY)
ROW MAJOR VS COLUMN MAJOR
Row Major: array_addr + elem_size*((i-first_index)*N + (j-first_index))
Column Major: array_addr + elem_size*((i-first_index) + (j-first_index)*M)
CALCULATE THE ADDRESS OF ANY ELEMENT IN THE 2-D ARRAY:
EXAMPLE 2:
Formula used:
Address of[I][J][K] =B + W (M * N(i-x) + N *(j-y) + (k-z))
Solution:
Address of arr[5][-1][8] = 400 + 2 * {[9 * 6 * (5 – 1)] + 6 * [(-1 + 4)]} + [8 – 5]
= 400 + 2 * (9*6*4)+(6*3)+3
= 400 + 2 * (237)
= 874
COLUMN MAJOR ORDER
Address of A[i][j][k]= B + W(M * N(i – x) + M *(k – z) + (j – y))
Here:
B = Base Address (start address)
W = Weight (storage size of one element stored in the array)
M = Row (total number of rows)
N = Column (total number of columns)
P = Width (total number of cells depth-wise)
x = Lower Bound of Row
y = Lower Bound of Column
z = Lower Bound of Width
EXAMPLE 4:
1. (2,1,1)
2. (1,2,1)
3. (1,1,2)
4. None of above
TIMES FOR COMMON OPERATIONS
BIG O COMPLEXITY
int main() {
int a[2][2] = {{1,2},{3,4}};
int i,j;
for (i = 0; i<2 ; i++){
for (j = 0 ; j<2 ; j++)
{
std::cout <<a[i][j] << " ";
}
std::cout<< std::endl;
}
return 0;
}
ARRAY PROGRAMS
● Addition
● Subtraction
● Multiplication