DS_Notes unit 1
DS_Notes unit 1
Syllabus: Revision of Function and Structure, Revision of concept of types of pointers and its applications,
Memory Allocation- Static and Dynamic. Introduction: Basic Terminology, Elementary Data Organization,
Arrays: Definition, Single and Multidimensional Arrays, Representation of Arrays: Row Major Order, and
Column Major Order, Application of arrays, Sparse Matrices and their representations.
• A function that is designed for user specific task is Actual Arguments: Arguments which are mentioned
called user defined function. Every user define function in the function call.
has three parts as: Prototype or Declaration, Calling, Formal Arguments: Arguments which are mentioned
Definition in function definition are called dummy or formal
argument. These arguments are used to just hold the
• Function Declaration OR Function Prototype: It is
value that is sent by calling function. Formal arguments
also known as function prototype. It informs the
are like other local variables of the function which are
computer about the three things 1. Name of the function
created when function call starts and destroyed when
2. Number and type of arguments received by the
end function.
Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 4
Parameter passing methods-
There are two ways to pass value or data to function in C language which is given below;
• call by value
• call by reference
Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 5
Passing Array to a function:
Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 6
• Recursion: When a function calls itself then that int sum(int n)
function is called Recursive function. { if (n != 0)
return n + sum(n-1); // sum()
void recurse() function calls itself
{ recurse();
else
}
int main() return n;
{ recurse(); }
}
Output
Example: Sum of Natural Numbers Using Enter a positive integer:3
Recursion sum = 6
#include <stdio.h>
int sum(int n);
int main() • Advantage of Recursion
{ a) Function calling related information will be
int number, result; maintained by recursion.
printf("Enter a positive integer: "); b) Stack evaluation will be take place by using
recursion.
scanf("%d", &number);
c) In fix prefix, post-fix notation will be
result = sum(number); evaluated by using recursion.
printf("sum = %d", result);
return 0; • Disadvantage of Recursion
} 1. It is a very slow process due to stack
overlapping.
2. Recursive programs can create stack
overflow.
3. Recursive functions can create as loops.
Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 7
[T-2] Prerequisites of Subject [Structure]
Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 8
In this example, the address of person1 is Output
stored in the personPtr pointer Name : Tata
using personPtr = &person1; Now, you Price : 1021
can access the members of person1 using
Example 2: Using Call By Reference
the personPtr pointer. Method
By the way,
personPtr->age is equivalent // C program to pass structure as an argument to
to (*personPtr).age the functions using Call By Reference
personPtr->weight is equivalent Method
#include <stdio.h>
to (*personPtr).weight
struct student {
char name[50];
int roll;
How to Pass or Return a Structure To or From a float marks;
Function in C? };
void display(struct student* student_obj)
Example 1: Using Call By Value Method {
printf("Name: %s\n", student_obj->name);
printf("Roll: %d\n", student_obj->roll);
// C program to pass structure as an printf("Marks: %f\n", student_obj->marks);
argument to the functions using Call By }
Value Method int main()
{ struct student st1 = { "Aman", 19, 8.5 };
#include <stdio.h> display(&st1);
struct car return 0;
{ }
char name[30];
int price; Output
}; Name: Aman
Roll: 19
void print_car_info(struct car c) Marks: 8.500000
{
printf("Name : %s", c.name);
printf("\nPrice : %d\n", c.price);
}
int main()
{
struct car c = { "Tata", 1021 };
print_car_info(c);
return 0;
}
Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 9
[T-3] Pointers and its applications (DMA)
• Every variable in C has a name and a value associated with it. When a variable is declared, a specific block of
memory within the computer is allocated to hold the value of that variable.
Consider the declaration, int i = 3 ;
This declaration tells the C compiler to:
(a) Reserve space in memory to hold the integer value.
(b) Associate the name i with this memory location.
(c) Store the value 3 at this location.
We may represent i’s location in memory by the following memory map.
• We see that the computer has selected memory location 65524 as the place to store the value 3. The location
number 65524 is not a number to be relied upon, because some other time the computer may choose a
different location for storing the value 3. The important point is, i’s address in memory is a number.
• A pointer is a variable that contains the memory location of another variable.
• Pointers applications include:
a) Pointers are used to pass information back and forth between functions.
b) Pointers enable the programmers to return multiple data items from a function via function arguments.
c) Pointers provide an alternate way to access the individual elements of an array.
d) Pointers are used to pass arrays and strings as function arguments.
e) Pointers are used to create complex data structures, such as trees, linked lists, linked stacks, linked
queues, and graphs.
f) Pointers are used for the dynamic memory allocation of a variable
• The general syntax of declaring pointer variables can be given as below.
data_type *ptr_name;
• Now we can say—pointers are variables that contain addresses, and since addresses are always whole
numbers, pointers would always contain whole numbers.
• Every time a pointer is incremented it points to the immediately next location of its type.
• Thus, the following operations can be performed on a pointer:
(a) Addition of a number to a pointer. For example,
int i = 4, *j, *k ; j = &i ; j = j + 1 ; j = j + 9 ; k = j + 3 ;
(b) Subtraction of a number from a pointer. For example,
j = &i ; j = j - 2 ; j = j - 5 ; k = j - 6 ;
(c) Subtraction of one pointer from another.
One pointer variable can be subtracted from another provided both variables point to elements of the same
array.
(d) Comparison of two pointer variables
Pointer variables can be compared provided both variables point to objects of the same data type. Such
comparisons can be useful when both pointer variables point to elements of the same array.
• **A word of caution! Do not attempt the following operations on pointers... they would never work out.
(a) Addition of two pointers
(b) Multiplication of a pointer with a constant
(c) Division of a pointer with a constant
Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 10
Memory Allocation- Static and Dynamic
• Dynamic memory management refers to manual memory management. This allows you to obtain more
memory when required and release it when not necessary.
• Although C inherently does not have any technique to allocate memory dynamically, there are 4 library
functions defined under <stdlib.h> for dynamic memory allocation.
• malloc()
The name malloc stands for "memory allocation".The function malloc() reserves a block of memory of
specified size and return a pointer of type void which can be casted into pointer of any form.
Syntax of malloc()➔ ptr = (cast-type*) malloc(byte-size)
Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of memory with size of
byte size. If the space is insufficient, allocation fails and returns NULL pointer.
ptr = (int*) malloc(100 * sizeof(int));
This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes respectively and the
pointer points to the address of first byte of memory.
• calloc()
The name calloc stands for "contiguous allocation".The only difference between malloc() and calloc() is
that, malloc() allocates single block of memory whereas calloc() allocates multiple blocks of memory
each of same size and sets all bytes to zero.
Syntax of calloc()➔ptr = (cast-type*)calloc(n, element-size);
This statement will allocate contiguous space in memory for an array of n elements. For example:
ptr = (float*) calloc(25, sizeof(float));
This statement allocates contiguous space in memory for an array of 25 elements each of size of float, i.e,
4 bytes.
• free()
Dynamically allocated memory created with either calloc() or malloc() doesn't get freed on its own. You
must explicitly use free() to release the space.
syntax of free()➔free(ptr); //This statement frees the space allocated in the memory pointed by ptr.
Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 11
Example #1: Using C malloc() and free() printf("Enter elements of array: ");
Write a C program to find sum of n elements entered for(i = 0; i < num; ++i)
by user. To perform this program, allocate memory {
dynamically using malloc() function. scanf("%d", ptr + i);
#include <stdio.h> sum += *(ptr + i);
#include <stdlib.h> }
int main() printf("Sum = %d", sum);
{ int num, i, *ptr, sum = 0; free(ptr);
printf("Enter number of elements: "); return 0;
scanf("%d", &num); }
ptr = (int*) malloc(num * sizeof(int)); //memory
allocated using malloc • realloc()
if(ptr == NULL) If the previously allocated memory is
{ printf("Error! memory not allocated."); insufficient or more than required, you can
exit(0); change the previously allocated memory size
} using realloc().
printf("Enter elements of array: "); Syntax of realloc() ➔ptr = realloc(ptr,
for(i = 0; i < num; ++i) newsize);
{ scanf("%d", ptr + i); Here, ptr is reallocated with size of newsize.
sum += *(ptr + i);
} Example #3: Using realloc()
printf("Sum = %d", sum); #include <stdio.h>
free(ptr); #include <stdlib.h>
return 0; int main()
} {
int *ptr, i , n1, n2;
Example #2: Using C calloc() and free() printf("Enter size of array: ");
Write a C program to find sum of n elements entered scanf("%d", &n1);
by user. To perform this program, allocate memory ptr = (int*) malloc(n1 * sizeof(int));
dynamically using calloc() function. printf("Address of previously allocated memory:
#include <stdio.h> ");
#include <stdlib.h> for(i = 0; i < n1; ++i)
int main() printf("%u\t",ptr + i);
{ printf("\nEnter new size of array: ");
int num, i, *ptr, sum = 0; scanf("%d", &n2);
printf("Enter number of elements: "); ptr = realloc(ptr, n2 * sizeof(int));
scanf("%d", &num); for(i = 0; i < n2; ++i)
ptr = (int*) calloc(num, sizeof(int)); printf("%u\t", ptr + i);
if(ptr == NULL) return 0;
{ }
printf("Error! memory not allocated.");
exit(0);
}
Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 12
[T-4] Introduction: Basic Terminology, Elementary Data Organization
• A good program is defined as a program that runs correctly, easy to read and understand, easy to debug and
easy to modify.
• A program is said to be efficient when it executes in minimum time and with minimum memory space.
• In order to write efficient programs, we need to apply certain data management concepts.
• Data structure is a crucial part of data management.
• A data structure is basically a group of data elements that are put together under one name, and which defines
a particular way of storing and organizing data in a computer so that it can be used efficiently.
• Data: Data are simply values or sets of values.
• Data items: Data items refers to a single unit of values. Data items that are divided into sub-items are called
Group items. Ex: An Employee Name may be divided into three subitems- first name, middle name, and last
name.
• Data items that are not able to divide into sub-items are called Elementary items. Ex: SSN
• Entity: An entity is something that has certain attributes or properties which may be assigned values. The
values may be either numeric or non-numeric. Ex: Attributes- Names, Age, Sex, SSN Values- Rohland Gail,
34, F, 134-34-5533 Entities with similar attributes form an entity set. Each attribute of an entity set has a
range of values, the set of all possible values that could be assigned to the particular attribute.
• The term “information” is sometimes used for data with given attributes, of, in other words meaningful or
processed data.
• Field is a single elementary unit of information representing an attribute of an entity.
• Record is the collection of field values of a given entity.
• File is the collection of records of the entities in a given entity set.
• Each record in a file may contain many field items but the value in a certain field may uniquely determine
the record in the file. Such a field K is called a primary key.
• Records may also be classified according to length. A file can have fixed-length records or variable-length
records.
• In fixed-length records, all the records contain the same data items with the same amount of space assigned
to each data item.
• In variable-length records file records may contain different lengths. Example: Student records have
variable lengths, since different students take different numbers of courses. Variable-length records have a
minimum and a maximum length.
Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 13
What do you mean by the term “Data Structure”?
• Organizing the data in memory.
• A data structure is a way of organizing the data so that it can be used efficiently. Here, we have used the
word efficiently, which in terms of both the space and time.
• It is a set of algorithms that we can use in any programming language to structure the data in the memory.
Static data structure: Static data structure has a fixed memory size. It is easier to access the elements in a static
data structure. An example of this data structure is an array.
Dynamic data structure: In dynamic data structure, the size is not fixed. It can be randomly updated during the
runtime which may be considered efficient concerning the memory (space) complexity of the code. Examples of
this data structure are queue, stack, etc.
• The major or the common operations that can be performed on the data structures are:
o Searching: We can search for any element in a data structure.
o Sorting: We can sort the elements of a data structure either in an ascending or descending order.
o Insertion: We can also insert the new element in a data structure.
o Updation: We can also update the element, i.e., we can replace the element with another element.
o Deletion: We can also perform the delete operation to remove the element from the data structure.
Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 14
• Advantages of Data structures
The following are the advantages of a data structure:
o Efficiency: If the choice of a data structure for implementing a particular ADT is proper, it makes the
program very efficient in terms of time and space.
o Reusability: The data structure provides reusability means that multiple client programs can use the data
structure.
o Abstraction: The data structure specified by an ADT also provides the level of abstraction. The client cannot
see the internal working of the data structure, so it does not have to worry about the implementation part.
The client can only see the interface.
• An abstract data type (ADT) is the way we look at a data structure, focusing on what it does and ignoring how
it does its job. For example, stacks and queues are perfect examples of an ADT. We can implement both these
ADTs using an array or a linked list. This demonstrates the ‘abstract’ nature of stacks and queues.They are not
concerned about how they work.
Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 15
[T-5] Arrays: Definition, Declaration, Initialization & Processing of Single and Multidimensional Arrays
Syntax
Creating an array in C language –Arrays are declared using the following syntax:
type name[size];
For example, if we write,
int marks[10];
In the memory, the array will be stored as shown
1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th
element element element element element element element element element element
marks [0] marks[1] marks[2] marks[3] marks[4] marks[5] marks[6] marks[7] marks[8] marks[9]
Types of arrays:
There are following types of arrays:
• One-dimensional array (1-D arrays): You can imagine a 1d array as a row, where elements are stored one
after another.
1D array
• Two-dimensional array: 2-D Multidimensional arrays can be considered as an array of arrays or as a matrix
consisting of rows and columns.
2D array
• Three-dimensional array: A 3-D Multidimensional array contains three dimensions, so it can be considered
an array of two-dimensional arrays.
3D array
Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 16
Declaration, Initialization & Processing of Single and Multidimensional Arrays
One Dimensional Array
Declaration:
Syntax: ➔data_type array_name[size];
data_type represents the type of elements present in the array. array_name represents the name of the array.
Size represents the number of elements that can be stored in the array.
Example:➔int age[100]; float sal[15]; char grade[20];
Here age is an integer type array, which can store 100 elements of integer type. The array sal is floating type array
of size 15, can hold float values. Grade is a character type array which holds 20 characters.
Initialization:
Syntax: ➔data_type array_name[size]={value1, value2,……..valueN};
Value1, value2, valueN are the constant values known as initializers, which are assigned to the array elements one
after another.
Example: ➔int marks[5]={10,2,0,23,4};
The values of the array elements after this initialization are: marks[0]=10, marks[1]=2, marks[2]=0, marks[3]=23,
marks[4]=4
Note-:
In 1-D arrays it is optional to specify the size of the array. If size is omitted during initialization, then the
compiler assumes the size of array equal to the number of initializers. Example:int marks []={10,2,0,23,4};Here
the size of array marks is initialized to 5.
We can’t copy the elements of one array to another array by simply assigning it. Example:
int a[5]={9,8,7,6,5}; int b[5];
b=a; //not valid
we have to copy all the elements by using for loop.
for(a=i; i<5; i++) b[i]=a[i];
Processing:
For processing arrays we mostly use for loop. The total no. of passes is equal to the no. of elements present in the
array and in each pass one element is processed.
Example:
#include<stdio.h>
main()
{
int a[3],i;
for(i=0;i<=2;i++) //Reading the array values
{
printf(“enter the elements”);
scanf(“%d”,&a[i]);
}
for(i=0;i<=2;i++) //display the array values
{ printf(“%d”,a[i]);
printf(“\n”);
}
}
Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 17
Two Dimensional Arrays-
Arrays that we have considered up to now are one dimensional array, a single line of elements. Often data come
naturally in the form of a table, e.g. spreadsheet, which need a two-dimensional array.
Declaration:
Syntax: ➔data_type array_name[rowsize][columnsize];
Rowsize specifies the no.of rows ,Columnsize specifies the no.of columns.
Example: ➔int a[4][5];
This is a 2-D array of 4 rows and 5 columns. Here the first element of the array is a[0][0] and last element of the
array is a[3][4] and total no.of elements is 4*5=20.
Initialization:
2-D arrays can be initialized in a way similar to 1-D arrays.
Example: ➔int m[4][3]={1,2,3,4,5,6,7,8,9,10,11,12};
Note:
In 2-D arrays it is optional to specify the first dimension but the second dimension should always be present.
Example: int m[][3]={
{1,10},
{2,20,200},
{3}, {4,40,400} };
Here the first dimension is taken 4 since there are 4 roes in the initialization list. A 2-D array is known as matrix.
Processing:
For processing of 2-D arrays we need two nested for loops. The outer loop indicates the rows and the inner loop
indicates the columns.
Example: ➔
int a[4][5];
Reading values in a
for(i=0;i<4;i++)
for(j=0;j<5;j++)
scanf(“%d”,&a[i][j]);
Displaying values of a
for(i=0;i<4;i++)
for(j=0;j<5;j++)
printf(“%d”,a[i][j]);
This program reads and displays 3 elements of integer type.
Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 18
Representation of Arrays: Row Major Order, and Column Major Order
• When it comes to organizing and accessing elements in a multi-dimensional array, two prevalent methods
are Row Major Order and Column Major Order.
• These approaches define how elements are stored in memory and impact the efficiency of data access in
computing.
To find the address of the element using row-major order uses the following formula:
Address of A[I][J] = B + W * ((I – LR) * N + (J – LC))
I = Row Subset of an element whose address to be found,
J = Column Subset of an element whose address to be found,
B = Base address,
W = Storage size of one element store in an array(in byte),
LR = Lower Limit of row/start row index of the matrix(If not given assume it as zero),
LC = Lower Limit of column/start column index of the matrix(If not given assume it as zero),
N = Number of column given in the matrix.
Q-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))
Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 19
Column Major Order
If elements of an array are stored in a column-major fashion means moving across the column and then to the next
column then it’s in column-major order.
To find the address of the element using column-major order use the following formula:
Address of A[I][J] = B + W * ((J – LC) * M + (I – LR))
I = Row Subset of an element whose address to be found,
J = Column Subset of an element whose address to be found,
B = Base address,
W = Storage size of one element store in any array(in byte),
LR = Lower Limit of row/start row index of matrix(If not given assume it as zero),
LC = Lower Limit of column/start column index of matrix(If not given assume it as zero),
M = Number of rows given in the matrix.
To find the address of any element in 3-Dimensional arrays there are the following two ways:
• Row Major Order
• Column Major Order
Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 20
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[I][J][K] =B + W (M * N(i-x) + N *(j-y) + (k-z))
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 = 5 +5 + 1 = 11
N (column)= Upper Bound – Lower Bound + 1 = 5 + 10 + 1 = 16
Formula used:
Address of[i][j][k] = B + W(M * N(i – x) + M * (j-y) + (k – z))
Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 21
= 400 + 4 * ((176*2 + 11*8 + 13)
= 400 + 4 * (453)
= 400 + 1812
= 2212
Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 22
4.Search &Update
3.Deletion #include<stdio.h>
Write a program to delete a number from a given int main()
location in an array. { int i,t,a[10],n,m,s,j=0,b[10];
printf("\nEnter the Limit:");
#include <stdio.h> scanf("%d",&n);
int main() printf("\nEnter the Values:");
{ for(i=0i<n;i++)
int i, n, pos, arr[10]; { scanf("%d",&a[i]);
clrscr(); }
printf("\n Enter the no of elements in the array : "); printf("\nGiven values are:");
scanf("%d", &n); for(i=0;i<n;i++)
for(i=0;i<n;i++) { printf("a[%d]=%d",i,a[i]);
{ }
printf("\n arr[%d] = ", i); printf("\nEnter the position to be update:");
scanf("%d", &arr[i]); scanf("%d",&t);
} printf("\nEnter the value to be update:");
printf("\nEnter the position from which the number scanf("%d",&s);
has to be deleted : "); for(i=0;i<n;i++)
scanf("%d", &pos); {
for(i=pos; i<n–1;i++) if(i==t)
arr[i] = arr[i+1]; { a[i]=s;
n– –; }
printf("\n The array after deletion is : "); }
for(i=0;i<n;i++) printf("\nUpdated value is:");
printf("\n arr[%d] = %d", i, arr[i]); for(i=0;i<n;i++)
return 0; { printf("\na[%d]=%d",i,a[i]);
} }
Output return 0;
Enter the number of elements in the array : 5 }
arr[0] = 1 Output
arr[1] = 2 Enter the limit:5
arr[2] = 3 Enter the values:1 2 3 4 5
arr[3] = 4 Given values are:
arr[4] = 5 a[0]=1
Enter the position from which the number has to be a[1]=2
deleted : 3 a[2]=3
The array after deletion is : a[3]=4
arr[0] = 1 a[4]=5
arr[1] = 2 Enter the position to be update:3
arr[2] = 3 Enter the value to be update:5
arr[3] = 5 Inserted value is:
a[0]=1
a[1]=2
a[2]=3
a[3]=5
a[4]=4
a[5]=5
Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 23
2. Write a program to input two m x n matrices
Basic Operations on 2D array: and then calculate the sum of their corresponding
elements and store it in a third m x n matrix.
1.Write a program to transpose a 3 x 3 matrix. #include <stdio.h>
int main()
#include <stdio.h> {
int main() int i, j;
{ int rows1, cols1, rows2, cols2, rows_sum, cols_sum;
int i, j, mat[3][3], transposed_mat[3][3]; int mat1[5][5], mat2[5][5], sum[5][5];
clrscr(); clrscr();
printf("\n Enter the elements of the matrix "); printf("\n Enter the number of rows in the first
for(i=0;i<3;i++) matrix : ");
{ scanf("%d",&rows1);
for(j=0;j<3;j++) printf("\n Enter the number of columns in the first
{ matrix : ");
scanf("%d", &mat[i][j]); scanf("%d",&cols1);
} printf("\n Enter the number of rows in the second
} matrix : ");
printf("\n The elements of the matrix are "); scanf("%d",&rows2);
for(i=0;i<3;i++) printf("\n Enter the number of columns in the second
{ matrix : ");
printf("\n"); scanf("%d",&cols2);
for(j=0;j<3;j++) if(rows1 != rows2 || cols1 != cols2)
printf("\t %d", mat[i][j]); {
} printf("\n Number of rows and columns of both
for(i=0;i<3;i++) matrices must be equal");
{ exit(0);
for(j=0;j<3;j++) }
transposed_mat[i][j] = mat[j][i]; rows_sum = rows1;
} cols_sum = cols1;
printf("\n The elements of the transposed matrix are printf("\n Enter the elements of the first matrix ");
"); for(i=0;i<rows1;i++)
for(i=0;i<3;i++) {
{ for(j=0;j<cols1;j++)
printf("\n"); {
for(j=0;j<3;j++) scanf("%d",&mat1[i][j]);
printf("\t %d",transposed_ mat[i][j]);} }
return 0; }
} printf("\n Enter the elements of the second matrix ");
Output for(i=0;i<rows2;i++)
Enter the elements of the matrix {
123456789 for(j=0;j<cols2;j++)
The elements of the matrix are {
123 scanf("%d",&mat2[i][j]);
456 }
789 }
The elements of the transposed matrix are for(i=0;i<rows_sum;i++)
147 {
258 for(j=0;j<cols_sum;j++)
369 sum[i][j] = mat1[i][j] + mat2[i][j];
}
printf("\n The elements of the resultant matrix are ");
for(i=0;i<rows_sum;i++)
{
Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 24
printf("\n"); {
for(j=0;j<cols_sum;j++) scanf("%d",&mat1[i][j]);
printf("\t %d", sum[i][j]); }
} }
return 0; printf("\n Enter the elements of the second matrix ");
} for(i=0;i<rows2;i++)
{
Output for(j=0;j<cols2;j++)
Enter the number of rows in the first matrix: 2 {
Enter the number of columns in the first matrix: 2 scanf("%d",&mat2[i][j]);
Enter the number of rows in the second matrix: 2 }
Enter the number of columns in the second matrix: 2 }
Enter the elements of the first matrix for(i=0;i<res_rows;i++)
1234 {
Enter the elements of the second matrix for(j=0;j<res_cols;j++)
5678 Arrays 103
The elements of the resultant matrix are {
68 res[i][j]=0;
10 12 for(k=0; k<res_cols;k++)
res[i][j] += mat1[i][k] * mat2[k][j];
3.Write a program to multiply two m x n }
matrices. }
#include <stdio.h> printf("\n The elements of the product matrix are ");
int main() for(i=0;i<res_rows;i++)
{ {
int i, j, k; printf("\n");
int rows1, cols1, rows2, cols2, res_rows, res_cols; for(j=0;j<res_cols;j++)
int mat1[5][5], mat2[5][5], res[5][5]; printf("\t %d",res[i][j]);
clrscr(); }
printf("\n Enter the number of rows in the first return 0;
matrix : "); }
scanf("%d",&rows1); Output
printf("\n Enter the number of columns in the first Enter the number of rows in the first matrix: 2
matrix : "); Enter the number of columns in the first matrix: 2
scanf("%d",&cols1); Enter the number of rows in the second matrix: 2
printf("\n Enter the number of rows in the second Enter the number of columns in the second matrix: 2
matrix : "); Enter the elements of the first matrix
scanf("%d",&rows2); 1234
printf("\n Enter the number of columns in the second Enter the elements of the second matrix
matrix : "); 5678
scanf("%d",&cols2); The elements of the product matrix are
if(cols1 != rows2) 19 22
{ 43 50
printf("\n The number of columns in the first matrix
must be equal
to the number of rows in the second matrix");
exit();
}
res_rows = rows1;
res_cols = cols2;
printf("\n Enter the elements of the first matrix ");
for(i=0;i<rows1;i++)
{
for(j=0;j<cols1;j++)
Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 25
Pointer and 2D Array: Pointer and 3D Array
Write a program to read and display a 3 x 3 Write a program which illustrates the use of a
matrix. pointer to a three-dimensional array.
#include <stdio.h> #include <stdio.h>
#include <conio.h> int main()
void display(int (*)[3]); {
int main() int i,j,k;
{ int arr[2][2][2];
int i, j, mat[3][3]; int (*parr)[2][2]= arr;
clrscr(); clrscr();
printf("\n Enter the elements of the matrix"); printf("\n Enter the elements of a 2 \ 2 \ 2 array: ");
for(i=0;i<3;i++) for(i = 0; i < 2; i++)
{ {
for(j = 0; j < 3; j++) for(j = 0; j < 2; j++)
{ {
scanf("%d", &mat[i][j]); for(k = 0; k < 2; k++)
} scanf("%d", &arr[i][j][k]);
} }
display(mat); }
return 0; printf("\n The elements of the 2 \ 2 \ 2 array are: ");
} for(i = 0; i < 2; i++)
void display(int (*mat)[3]) {
{ for(j = 0; j < 2; j++)
int i, j; {
printf("\n The elements of the matrix are"); for(k = 0; k < 2; k++)
for(i = 0; i < 3; i++) printf("%d", *(*(*(parr+i)+j)+k));
{ }
printf("\n"); }
for(j=0;j<3;j++) return 0;
printf("\t %d",*(*(mat + i)+j)); }
} Output
} Enter the elements of a 2 \ 2 \ 2 array: 1 2 3 4 5 6 7 8
Output The elements of the 2 \ 2 \ 2 array are: 1 2 3 4 5 6 7 8
Enter the elements of the matrix
123456789 Note In the printf statement, you could also have used
The elements of the matrix are * ( * ( * ( a r r + i ) + j + ) + k ) instead of
123 *(*(*(parr+i)+j)+k)).
456
789
Disadvantages of Array:
• As arrays have a fixed size, once the memory is allocated to them, it cannot be increased or decreased,
making it impossible to store extra data if required. An array of fixed size is referred to as a static array.
• Allocating less memory than required to an array leads to loss of data.
Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 26
• An array is homogeneous in nature so, a single array cannot store values of different data types.
• Arrays store data in contiguous memory locations, which makes deletion and insertion very difficult to
implement. This problem is overcome by implementing linked lists, which allow elements to be accessed
sequentially.
Application of arrays
• They are used in the implementation of other data structures such as array lists, heaps, hash tables, vectors,
and matrices.
• Database records are usually implemented as arrays.
• It is used for different sorting algorithms such as bubble sort insertion sort, merge sort, and quick sort.
• It is used for implementing matrices.
• Graphs are also implemented as arrays in the form of an adjacency matrix.
Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 27
[T-6] Sparse Matrices and their representations
• A matrix is a two-dimensional data object made of m rows and n columns, therefore having total m x n
values.
• If most of the elements of the matrix have 0 value, then it is called a sparse matrix.
Representing a sparse matrix by a 2D array leads to wastage of lots of memory as zeroes in the matrix are of no
use in most of the cases. So, instead of storing zeroes with non-zero elements, we only store non-zero elements.
This means storing non-zero elements with triples- (Row, Column, value).
Sparse Matrix Representations can be done in many ways following are two common representations:
1. Array representation
2. Linked list representation*
Implementation in C
Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 28
int size = 0;
for (int i = 0; i < 4; i++)
for (int j = 0; j < 5; j++)
if (sparseMatrix[i][j] != 0)
size++;
// number of columns in compactMatrix (size) must be equal to number of non - zero elements in sparseMatrix
int compactMatrix[3][size];
printf("\n");
}
return 0;
}
Output
001133
242312
345726
Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 29
Programs/Questions
Lecture Notes (Source: Books & Multiple Online Resources) ||Data Structure Using C [UCS1001] || Sarvesh @IILMU 30