Array
Array
An array is a list of a finite number ‘n’ of homogeneous data element such that The elements of the array are
reference respectively by an index set consisting of n consecutive numbers.
The element of the array are respectively in successive memory locations. The number n of elements is called
the length or size of the array. The length or the numbers of elements of the array can be obtained from the
index set by the formula When LB = 0,
Length = UB – LB + 1
When LB = 1,
Length = UB
Where,
UB is the largest index called the Upper Bound
LB is the smallest index, called the Lower Bound
Let LA be a linear array in the memory of the computer. The memory of the computer is simply a
sequence of address location as shown below,
1000
1001
1002
1003
1004
LOC (LA [K]) = address of the element LA [K] of the array LA. The elements of LA are stored in successive
memory cells.
The computer does not keep track of the address of every element of LA, but needs to keep track only the
address of the first element of LA denoted by, LA[0]
Using the base address of LA, the computer calculates the address of any element of LA by the formula
LOC (LA[K]) = Base Address + w (Size of elements)(K – lower bound)
Where, w is the number of words per memory cell for the array LA.
ARRAY OPERATIONS
1. Traversing
Let A be a collection of data elements stored in the memory of the computer. Suppose if the contents of the
each elements of array A needs to be printed or to count the numbers of elements of A with a given property
can be accomplished by Traversing.
Traversing is a accessing and processing each element in the array exactly once.
Program:
#include<stdio.h>
#include<conio.h> int main()
{
int A[100],K=0,UB;
printf(“Enter the Array size less than 100: “);
printf(“Enter the elements in array: \n”);
for(K=0;K<UB;K++)
{
scanf(“%d”,&A[K]);
}
printf(“The Traverse of array is:\n”);
for(K=0;K<UB;K++)
{
printf(“%d\n”,A[K]);
}
getch();
return 0;
}
2. Inserting
Program:
#include <stdio.h>
int main()
{
int array[100], position, c, n, value; printf("Enter number of
elements in array\n"); scanf("%d", &n);
printf("Enter %d elements\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter the location where you wish to insert an element\n");
scanf("%d", &position);
printf("Enter the value to insert\n");
scanf("%d", &value);
for (c = n - 1; c >= position - 1; c--)
array[c+1] = array[c];
array[position-1] = value;
printf("Resultant array is\n");
for (c = 0; c <= n; c++)
printf("%d\n", array[c]);
return 0;
}.
Deleting
➢ Deleting refers to the operation of removing one element to the collection A.
➢ Deleting an element at the “end” of the linear array can be easily done with difficulties.
➢ If element at the middle of the array needs to be deleted, then each subsequent elements be moved one
location upward to fill up the array.
Algorithm
data_type array_name[size1][size2]....[sizeN];
data_type: Type of data to be stored in the array. Here data_type is valid C data type
array_name: Name of the array
size1, size2,... ,sizeN: Sizes of the dimensions
Examples:
Ouput:
1. Column-Major Order:
In this method the elements are stored column wise, i.e. m elements of first column are stored in first m
locations, m elements of second column are stored in next m locations and so on. E.g.
A 3 x 4 array will stored as below:
2. Row-Major Order:
In this method the elements are stored row wise, i.e. n elements of first row are stored in first n locations, n
elements of second row are stored in next n locations and so on. E.g.
A 3 x 4 array will stored as below:
Address of an element of any array say “A[ I ][ J ]” is calculated in two forms as given:
The address of a location in Column Major System is calculated using the following formula:
Address of A [ I ][ J ] Column Major Wise = BA + W * [( I – Lr ) + M * ( J – Lc )] Where,
B = Base address
I = Row subscript of element whose address is to be found
J = Column subscript of element whose address is to be found W = Storage Size of one element stored in the
array (in byte)
Lr = Lower limit of row/start row index of matrix, if not given assume 0 (zero)
Lc = Lower limit of column/start column index of matrix, if not given assume 0 (zero)
M = Number of rows of the given matrix
N = Number of columns of the given matrix.
Calculation of address of element of 1-D, 2-D, and 3-D using row-major and
column-major order
Calculating the address of any element In the 1-D array:
A 1-dimensional array (or single-dimension array) is a type of linear array. Accessing its elements involves a
single subscript that can either represent a row or column index.
Example:
1-D array
2-D array
To find the address of any element in a 2-Dimensional array there are the following two ways-
1. Row Major Order
2. Column Major Order
1. Row Major Order:
Row major ordering assigns successive elements, moving across the rows and then down the next row, to
successive memory locations. In simple language, the elements of an array are stored in a Row-Wise fashion.
To find the address of the element using row-major order uses the following formula:
Address of A[I][J] = BA + W * ((I – LR) * N + (J – LC))
I = Row Subset of an element whose address to be found,
Example: Given an array, arr[1………10][1………15] with base value 100 and the size of each element is 1
Byte in memory. Find the address of arr[8][6] with the help of row-major order.
Solution:
Given:
Base address B = 100
Storage size of one element store in any array W = 1 Bytes
Row Subset of an element whose address to be found I = 8
Column Subset of an element whose address to be found J = 6
Lower Limit of row/start row index of matrix LR = 1
Lower Limit of column/start column index of matrix = 1
Number of column given in the matrix N = Upper Bound – Lower Bound + 1
= 15 – 1 + 1
= 15
Formula:
Address of A[I][J] = B + W * ((I – LR) * N + (J – LC))
Solution:
Address of A[8][6] = 100 + 1 * ((8 – 1) * 15 + (6 – 1))
= 100 + 1 * ((7) * 15 + (5))
= 100 + 1 * (110)
Address of A[I][J] = 210
Example: Given an array arr[1………10][1………15] with a base value of 100 and the size of each element
is 1 Byte in memory find the address of arr[8][6] with the help of column-major order.
Solution:
Given:
Base address B = 100
Storage size of one element store in any array W = 1 Bytes
Row Subset of an element whose address to be found I = 8
Column Subset of an element whose address to be found J = 6
Lower Limit of row/start row index of matrix LR = 1
Lower Limit of column/start column index of matrix = 1
Number of Rows given in the matrix M = Upper Bound – Lower Bound + 1
= 10 – 1 + 1
= 10
Formula: used
Address of A[I][J] = BA + W * ((J – LC) * M + (I – LR))
Address of A[8][6] = 100 + 1 * ((6 – 1) * 10 + (8 – 1))
= 100 + 1 * ((5) * 10 + (7))
= 100 + 1 * (57)
Address of A[I][J] = 157
From the above examples, it can be observed that for the same position two different address locations are
obtained that’s because in row-major order movement is done across the rows and then down to the next row,
and in column-major order, first move down to the first column and then next column. So both the answers are
right.
So it’s all based on the position of the element whose address is to be found for some cases the same answers
is also obtained with row-major order and column-major order and for some cases, different answers are
obtained.
To find the address of any element in 3-Dimensional arrays there are the following two ways-
• Row Major Order
• Column Major Order
•
1. Row Major Order:
To find the address of the element using row-major order, use the following formula:
Address of A[i][j][k] = BA + W *(P * N * (i-x) +P *(j-y) + (k-z))
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: Given an array, arr[1:9, -4:1, 5:10] with a base value of 400 and the size of each element is 2
Bytes in memory find the address of element arr[5][-1][8] with the help of row-major order?
Solution: Given:
Block Subset of an element whose address to be found I = 5
Row Subset of an element whose address to be found J = -1
Column Subset of an element whose address to be found K = 8
Base address B = 400
Storage size of one element store in any array(in Byte) W = 2
Lower Limit of blocks in matrix x = 1
Lower Limit of row/start row index of matrix y = -4
Lower Limit of column/start column index of matrix z = 5
M(row) = Upper Bound – Lower Bound + 1 = 1 – (-4) + 1 = 6
N(Column)= Upper Bound – Lower Bound + 1 = 10 – 5 + 1 = 6
Formula used:
Address of A[i][j][k] = BA + W *(P * N * (i-x) +P *(j-y) + (k-z))
Solution:
Address of arr[5][-1][8] = 400 + 2 * {[6 * 6 * (5 – 1)] + 6 * [(-1 + 4)]} + [8 – 5]
= 400 + 2 * (6*6*4)+(6*3)+3
= 400 + 2 * (165)
= 730
Example: Given an array arr[1:8, -5:5, -10:5] with a base value of 400 and the size of each element is 4
Bytes in memory find the address of element arr[3][3][3] with the help of column-major order?
Solution:
Given:
Row Subset of an element whose address to be found I = 3
Column Subset of an element whose address to be found J = 3
Block Subset of an element whose address to be found K = 3
Base address B = 400
Storage size of one element store in any array(in Byte) W = 4
Lower Limit of blocks in matrix x = 1
Lower Limit of row/start row index of matrix y = -5
Lower Limit of column/start column index of matrix z = -10
M (row)= Upper Bound – Lower Bound + 1 = 8 -1+1 = 8
N (column)= Upper Bound – Lower Bound + 1 = 5 + 5 + 1 = 11
Formula used:
Address of A[i][j][k]= BA + W(M * N(k – z) + M *( j – y) + (i-x))
Solution:
Address of arr[3][3][3] = 400 + 4 * ((11*8*(3-1)+8*(3-(-5)+(3-(-10)))
= 400 + 4 * ((88*2 + 8*8 + 13)
= 400 + 4 * (253) = 400 + 1012 = 1412
Example: Let’s take a multi-dimensional array A[10][20][30][40] with the base address 1200. The task is to
find the address of element A[1][3][5][6].
Here, BAd = 1200 and width = 4.
L1 = 10, L2 = 20, L3 = 30, L4 = 40
Since the lower bounds are not given, so lower bounds are assumed to be zero.
E1 = 1 – 0 = 1;
E2 = 3 – 0 = 3;
E3 = 5 – 0 = 5;
E4 = 6 – 0 = 6.
Any of the techniques (Row-major or column-major) can be used for calculating the answer (unless
specified).
By applying the formula for row-major, directly write the formula as:
A[1][3][5][6] = 1200 + 4(((1 × 20 + 3)30 +5)40 + 6)
=1200 +4((23 × 30 +5)40 +6)
=1200 + 4(695 × 40 + 6)
=1200 + (4 × 27806)
=112424.
Implementation:
// C++ program for Sparse Matrix Representation
// using Array
#include<stdio.h>
int main()
{
// Assume 4x5 sparse matrix
int sparseMatrix[4][5] =
{
{0 , 0 , 3 , 0 , 4 },
{0 , 0 , 5 , 7 , 0 },
{0 , 0 , 0 , 0 , 0 },
{0 , 2 , 6 , 0 , 0 }
};
int size = 0;
for (int i = 0; i < 4; i++)
for (int j = 0; j < 5; j++)
if (sparseMatrix[i][j] != 0)
size++;
printf("\n");
}
return 0;
}
Initialization
malloc() allocates a memory block of given size (in bytes) and returns a pointer to the beginning of the
block. malloc() doesn’t initialize the allocated memory. If you try to read from the allocated memory
without first initializing it, then you will invoke undefined behavior, which usually means the values you
read will be garbage values
calloc() allocates the memory and also initializes every byte in the allocated memory to 0. If you try to read
the value of the allocated memory without initializing it, you’ll get 0 as it has already been initialized to 0
by calloc().
Parameters
Return Value
After successful allocation in malloc() and calloc(), a pointer to the block of memory is returned otherwise
NULL is returned which indicates failure.
Difference between malloc() and calloc() in C
Linked List
A linked list is a non-sequential collection of data items. It is a dynamic data structure. For every data item in a
linked list, there is an associated pointer that would give the memory location of the next data item in the linked
list.
The data items in the linked list are not in consecutive memory locations. They may be anywhere, but the
accessing of these data items is easier as each data item contains the address of the next data item.
Advantages of linked lists:
Linked lists have many advantages. Some of the very important advantages are:
1. Linked lists are dynamic data structures. i.e., they can grow or shrink during the execution of a program.
2. Linked lists have efficient memory utilization. Here, memory is not pre- allocated. Memory is allocated
whenever it is required and it is de- allocated (removed) when it is no longer needed.
3. Insertion and Deletions are easier and efficient. Linked lists provide flexibility in inserting a data item at a
specified position and deletion of the data item from the given position.
4. Many complex applications can be easily carried out with linked lists.
Disadvantages of linked lists:
1. It consumes more space because every node requires a additional pointer to store address of the next node.
2. Searching a particular element in list is difficult and also time consuming.
Types of Linked Lists:
Basically we can put linked lists into the following four items:
1. Single Linked List.
2. Double Linked List.
3. Circular Linked List.
Single linked list is one in which all nodes are linked together in some sequential manner. Hence, it is also
called as linear linked list.
A double linked list is one in which all nodes are linked together by multiple links which helps in accessing
both the successor node (next node) and predecessor node (previous node) from any arbitrary node within the
list. Therefore each node in a double-linked list has two link fields (pointers) to point to the left node (previous)
and the right node (next). This helps to traverse in the forward direction and backward direction.
A circular linked list is one, which has no beginning and no end. A single linked list can be made a circular
linked list by simply storing address of the very first node in the link field of the last node.
Program
void display()
1. {
2. struct node *ptr;
3. ptr = head;
4. if(ptr == NULL)
5. printf("Nothing to print");
6. else
7. {
8. printf("\nprinting values . . . . .\n");
9. while (ptr!=NULL)
10. {
11. printf("\n%d",ptr->data);
12. ptr = ptr -> next;
13. } }}