1. Data Structures and Applications
(DSA)
By
SHRINIVASA
Assistant Professor(Senior)
Department of Computer Science and Engineering
Shri Madhwa Vadiraja Institute of Technology & Management,
Bantakal
Sunday, 07 April 2024 1
2. Text Books for Reference
1. Title : Fundamentals of Data Structures in C
Author : Ellis Horowitz and Sartaj Sahni,
Edition : 2nd Edition,
Publication : Universities Press, 2014
2. Title : Data Structures
Author : Seymour Lipschutz, Schaum's Outlines
Edition : Revised 1st Edition,
Publication : McGraw Hill, 2014
Sunday, 07 April 2024 2
3. MODULE–I SYLLABUS
• Introduction: Data Structures, Classifications (Primitive & Non
Primitive), Data structure Operations, Review of Arrays, Structures,
Self-Referential Structures, and Unions. Pointers and Dynamic
Memory Allocation Functions. Representation of Linear Arrays in
Memory, Dynamically allocated arrays.
• Array Operations: Traversing, inserting, deleting, searching, and
sorting. Multidimensional Arrays, Polynomials and Sparse Matrices.
• Strings: Basic Terminology, Storing, Operations and Pattern
Matching algorithms. Programming Examples.
Sunday, 07 April 2024 3
4. Introduction to Data Structure
• What is a program?
• Is a collection of instructions that can be executed by a computer to perform a specific task.
• Eg)Write a C program to find sum of two numbers.
• #include<stdio.h>
• main()
• {
• int a,b,sum=0;
• Printf(“nEnter two numbers:”);
• Scanf(“%d %d”,&a,&b);
• Sum=a+b;
• Printf(“Sum=%d”,sum);
• }
Sunday, 07 April 2024 4
5. Contd…
A program consists of 2 things…..
1)Algorithm
2)Data structure
i.e program=algorithm + data structure.
• What is data?
• Collection of raw facts.(eg: characters, strings, integers, symbols etc.)
• Eg)name shrinivasa is my-------data
• my name is shrinivasa-------meaningful data(Information).
• Structure: Way of organizing information in the computer so that it is
easier to use.
Sunday, 07 April 2024 5
6. Definition of Data Structure
• A data structure is the systematic way to organize data so that it
can be used efficiently.
• OR
• Data structure is representation of the logical relationship
existing between individual elements of data.
OR
Arranging the data in logical manner is called as data structure.
OR
• A data structure is a class of data that can characterized by its
organization and the operations that are defined on it. Hence
Data Structure= Organized Data + Allowed Operations
Sunday, 07 April 2024 6
7. Need for data structures
• The computers are electronic data processing devices.
• In-order to solve a particular problem, we need to know:
• 1)How to represent data in computer m/m.
• 2)How to access them.
• 3)What are the steps/operations to be performed to get the needed
output.
Sunday, 07 April 2024 7
8. CLASSIFICATIONS OF THE DATA STRUCTURES
if the data contains a single value, this can be organized using primitive data structure.
If the data contains set of values, they can be organized using non primitived.s.
Sunday, 07 April 2024 8
9. Primitive data structures
• These are the basic or fundamental data types(Builtin d.s).
• These are used to represent a single value..
• Example: char, int, float, double etc…
Sunday, 07 April 2024 9
10. Non-Primitive Data Structure
• Non-primitive data structures are more complicated data
structures and are derived from primitive data structures.
•These are used to store a group of values.
• Example: Arrays, Lists, Files,Structures,unions etc…
Sunday, 07 April 2024 10
11. Linear and Non Linear Data Structures
• A data structure is said to be linear if the elements form a
sequence, for example Array, Linked list, queue,stack etc.
• Elements in a nonlinear data structure do not form a
sequence.
• Elements are stored on hierarchical relationship among the
data.
• for example Tree, Graph, etc…
Sunday, 07 April 2024 11
13. DATA STRUCTURE OPERATIONS:
•Traversing: Accessing each record exactly once so that
certain items in the record may be processed. This
operation is also known as visiting the record.
•Searching: Finding the location of the record with a given
key value, or finding the locations of all records which
satisfy the one more conditions.
•Inserting: Adding a new record to the structure.
•Deleting: Removing a record from the structure.
Sunday, 07 April 2024 13
14. Operations used in special situations
• Sorting: Arranging the records in some logical order.
• Merging: Combining the records in two different
sorted files into a single record file.
Sunday, 07 April 2024 14
15. Review of Arrays
• The Simplest Type of data structure.
• Also called as Linear Array.
• It is a list of finite number of similar data elements.
• The number k in A[k] is called subscript and A[K] is
called subscripted variable.
Sunday, 07 April 2024 15
16. Arrays in C
• int list1[5];
• int *plist2[5];
• The first array defines five integers.
• Second array defines five pointers to integers.
• In C, All arrays start with the index 0.
Sunday, 07 April 2024 16
17. Pointers and dynamic memory allocation functions
•Pointer: is a variable whose value is the address of
another variable.
The Two operators used in the pointers:
•The Reference Operator (or An Address operator) : &
•The Dereference (or indirection) Operator: *
Sunday, 07 April 2024 17
18. Pointer declaration and initialization
• A pointer is declared with the help of * operator and initialized with
the help of & operator as shown below:
• int var=10;
• int *p; //or int *p=&var;
• p=&var;
• Logical representation of pointer for the above code:
Sunday, 07 April 2024 18
19. Contd…
• As we store any data/information in our brain(m/m), the computer
stores data in m/m.
• Computer m/m is divided into no. of cells called m/m locations.
• Each location is associated with address.
• Addresses of m/m locations ranges from 0 to 65535.
• We can’t change these addresses assigned by the computer and
hence these are constants but we can only use them to store data.
Sunday, 07 April 2024 19
21. Contd…
• Pointers can be explained using 3 fields:
• 1)pointer constant-address which is fixed.
• 2)pointer value address assigned to variable.
• 3)pointer variable variable that stores address of another variable.
Sunday, 07 April 2024 21
22. Programming examples on pointers
• #include<stdio.h>
• main()
• {
• int var=10;
• int *p=&var;
• Printf(“The value of var=%dn”,var);
• Printf(“The address of var=%pn”,&var);
• Printf(“The value of p=%pn”,p);
• Printf(“The address of p=%pn”,&p);
• }
Sunday, 07 April 2024 22
23. Output:
• The value of var=10
• The address of var=0x7ffeed8ec3e4
• The value of p=0x7ffeed8ec3e4
• The address of p=0x7ffeed8ec3e8
• Note: int takes 4 bytes.
Sunday, 07 April 2024 23
24. Example-2
• Given the following details
int a=10;
int b=20;
int *p=&a;
int *q=&b;
What is the value of each of the following expression?
i)++a
ii)++(*p)
iii)- - (*q)
iv)- - b
Sunday, 07 April 2024 24
25. Contd…
• #include<stdio.h>
• Main()
• {
• Int a=10;
• Int b=20;
• Int *p=&a;
• Int *q=&b;
• Printf(“The value of the expression ++a=%dn”,++a);
• Printf(“The value of the expression ++(*p)=%dn”,++(*p));
• Printf(“The value of the expression - -(*q)=%dn”,- -(*q));
• Printf(“The value of the expression - - b=%dn”,- -b);
• }
• Output:11 12 19 18
Sunday, 07 April 2024 25
26. Pointers to pointers
• Definition: A pointer variable which holds the address of another pointer variable.
• Here * operator be applied twice.
• Example: #include<stdio.h>
• void main()
• {
• int var=10;
• int *p;
• int **ptop;
• p=&var;
• ptop=&p;
• Printf(“n The value of var=%dn”,var);
• printf(“The value available at *p=%dn”,*p);
• printf(“The value available at *p=%dn”,*(&var));
• printf(“The value available at **ptop=%dn”,**ptop);
• }
• Out put:
Sunday, 07 April 2024 26
28. Memory allocation functions:
There are 2 types:1)static m/m allocation and 2)dynamic m/m
allocation.
Static m/m allocation: The allocation and deallocation of memory is performed
during compilation time of the program.
1)The size of the allocated m/m is fixed.
2)It cannot be altered during run-time/execution time.
Eg)int a[10];----allocates 10 blocks of m/m for an array.
int a[10][10];
Sunday, 07 April 2024 28
29. Dynamic m/m allocation:
The allocation and de-allocation of memory is performed during run-time or
execution time of the program.
Thus when program is getting executed at that time m/m is managed.
This is the efficient method when we compared to static m/m management.
Difference between static and dynamic m/m management:
static m/m dynamic m/m
1)m/m allocation is performed 1)m/m allocation is performed
at compile time. at run-time.
2)Prior to allocation , fixed size of 2)No need to know size of m/m prior
m/m has to be decided. to allocation.
3)Wastage/shortage of m/m occurs. 3)M/m is allocated as per requirements.
Eg)array Eg)linked list.
Sunday, 07 April 2024 29
30. Dynamic memory allocation
This technique has 4 predefined functions to allocate and de-allocate
memory.
i)malloc()
ii)calloc()
iii)realloc()
iv)free()
These functions are defined in the header stdlib.h
i)malloc(): The name malloc stands for memory allocation.
This function is used to allocate the required m/m space during run time.
Sunday, 07 April 2024 30
32. Program to illustrate working of malloc()
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
char *str;
str=(char *)malloc(20*sizeof(char));
printf(“value at memory is :%sn”,str);
If(str==NULL)
printf(“Error: no memory allocatedn”);
else
strcpy(str, ”C PROGRAMMING”);
printf(“stored value at memory:%sn”,str);
return 0;
}
Output: value at memory is:###################*^####
Stored value at memory :C PROGRAMMING
Sunday, 07 April 2024 32
33. Contd…
ii)calloc():It is similar to malloc, but it initializes the allocated m/m to zero.
This function takes two arguments, first no. of elements and second its type then
computes the no. of bytes to allocate.
If m/m is successfully allocated, then address of the first byte of allocated space is
returned.
If m/m allocation fails, then NULL is returned.
Syntax: data_type pointer_variable_name;
pointer_variable_name=(data_type*)calloc(n,size);
Eg) int *ptr;
ptr=(int*)calloc(20,sizeof(int));
The above function computes m/m required for 20 blocks & each block contain
2bytes.
Therefore 20*2 bytes for int=40bytes of m/m block is allocated.
Sunday, 07 April 2024 33
34. Program to illustrate working of calloc()
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
Int main()
{
Char *str;
str=(char*)calloc(20,sizeof(char));
If(str==NULL)
Printf(“Error: no memory allocatedn”);
else
{
printf(“Memory has:%sn”,str);
strcpy(str, “LABORATORY”);
printf(“New memory has:%sn”,str);
}
Return 0;
}
Output: Memory has:20 spaces
New memory has:LABORATORY
Sunday, 07 April 2024 34
35. Contd…
iii)realloc(): is used to modify the size of allocated block by malloc() or
calloc() functions to new size.
If the previously allocated m/m is insufficient or more than sufficient,
then you can change the m/m size using realloc().
Syntax: data_type pointer_variable_name;
pointer_variable_name=(data_type*)realloc(pointer_variable_name , newsize);
The above function allocates new m/m space of size ‘newsize’ to the
pointer variable name and returns a pointer to the first byte of the
m/m block.
The allocated new block may be or may not be at the same region.
Sunday, 07 April 2024 35
36. Program to illustrate working of realloc()
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
char *str;
str=(char*)malloc(20*sizeof(char));
if(str==NULL)
printf(“Error: No memory allocatedn”);
else
strcpy(str, “C PROGRAM”);
Printf(“stored value is:%sn”,str);
Str=(char*)realloc(str,40*sizeof(char));
Strcpy(str, “C PROGRAM IS EASY AND INTERESTING”);
Printf(“stored value after reallocation:%sn”, str);
Return 0;
}
Output: stored value is:C PROGRAM
Stored value after reallocation: C PROGRAM IS EASY AND INTERESTING.
Sunday, 07 April 2024 36
37. Contd…
iv)free():[Releasing the used m/m space]
Syntax: free(used_pointer_variable_name);
Eg)free(str);
Dynamically allocated m/m with either malloc() or calloc() does not get
return as its own.
The programmer must use free() explicitly to release allocated space.
Sunday, 07 April 2024 37
38. Program to illustrate working of free()
• #include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
char *str;
str=(char *)malloc(20*sizeof(char));
printf(“value at memory is :%sn”,str);
If(str==NULL)
printf(“Error: no memory allocatedn”);
else
strcpy(str, ”C PROGRAMMING”);
printf(“stored value at memory:%sn”,str);
free(str);
return 0;
}
Sunday, 07 April 2024 38
39. NULL Pointer in C
•Null pointer points to no object or function.
•Null pointer is represented by the integer 0.
•C Macro NULL is defined to the integer 0.
Sunday, 07 April 2024 39
41. Aliasing - Example
If two pointers are pointing to same memory
location or variable then the two pointers are
said to be aliases.
Example:
p1 = &i;
p2 = p1;
Here, p1 and p2 are aliases.
Sunday, 07 April 2024 41
42. What is the Output of the Program?
void main()
{
int a = 29;
int *p1, *p2;
p1 = &a;
*p1 = 3;
p2 = p1;
*p2 = 9;
printf(“%d t %d t %d”, a, *p1, *p2);
}
Sunday, 07 April 2024 42
43. Consider this Program
void main()
{
int *p1, *p2;
p1 = (int *)malloc(sizeof(int));
p2 = (int *)malloc(sizeof(int));
*p1 = 3;
p2 = p1;
free(p1);
printf(“%d n”, *p2);
}
Sunday, 07 April 2024 43
44. Dangling Reference
•Dangling pointers arise when an object is deleted or
de-allocated, without modifying the value of
the pointer, so that the pointer still points to the
memory location of the de-allocated memory.
•In short pointer pointing to non-existing memory
location is called dangling pointer.
•The pointer p2 in the previous program becomes
dangling reference after the instruction free(p1).
Sunday, 07 April 2024 44
45. Consider the Program below:
void main()
{
int *p1, *p2;
p1 = (int *)malloc(sizeof(int));
*p1 = 3;
p1 = (int *)malloc(sizeof(int));
*p1 = 9;
printf(“%d n”, *p1);
}
Sunday, 07 April 2024 45
46. Garbage:
• All the values that does not have a reference are
called garbage values.
• After second malloc function to the pointer p1,
the old location referred by p1 becomes Garbage.
Sunday, 07 April 2024 46
47. STRUCTURES
• Arrays are collection of data items of same type.
• Structures are the collection of data items of different types.
• Syntax:
struct tag_name
{
data_type1 member1;
data_type2 member2;
….. …..
data_typeN memberN;
};
Sunday, 07 April 2024 47
48. Cont’d…
• Structure can be defined as follows:
struct human
{
char name[10];
int age;
float salary;
};
struct human person;
• Here, person is a variable of type structure.
• What is structure variable?
• A variable which is used to access the members of the structure.
• A variable which is used to initialize the members of the structure.
Sunday, 07 April 2024 48
49. Using the members of Structure
• Using dot operator we can refer to the members.
person.name = “SHRINIVASA”;
person.age = 35;
person.salary= 55000;
Sunday, 07 April 2024 49
50. Creating our own structure data type
typedef struct
{
char name[10];
int age;
float salary;
} humanbeing;
• Here, humanbeing is a structure type (not a structure variable),
• We can create the structure variable as shown below:
humanbeing person1, person2;
Sunday, 07 April 2024 50
51. Variation 1 of Structure declaration
struct human
{
char name[10];
int age;
float salary;
};
The structure variable person can be create as shown below:
struct human person;
Now we can access the structure members using dot operator as :
person.salary = 55000;
person.age = 38;
Sunday, 07 April 2024 51
52. Variation 2 of Structure declaration
struct human
{
char name[10];
int age;
float salary;
} person;
Here, person is a structure variable of type human. Through this
structure variable we can access the structure member using dot
operation as in variation 1.
Sunday, 07 April 2024 52
53. Variation 3 of Structure declaration
struct humanbeing
{
char name[10];
int age;
float salary;
};
typedef struct humanbeing human;
Here, human is redefined structure type of humanbeing. So the structure
variable person can be create as: human person;
Now we can access the structure members using dot operator as :
person.salary = 55000;
person.age = 38;
Sunday, 07 April 2024 53
54. Variation 4 of Structure declaration
typedef struct
{
char name[10];
int age;
float salary;
} humanbeing;
Here, humanbeing is a structure type (not a structure variable), We can
create the structure variable as shown below:
humanbeing person1, person2;
Sunday, 07 April 2024 54
61. Accessing Structure members:
• To access the members of the structure, we specify the variable followed
by the dot operator then followed by the name of member.
Eg) struct student
{
int rollno;
char name[15];
float average;
};
struct student cse={1, ”shrinivasa” ,20.0};
Programming statements:
Sunday, 07 April 2024 61
63. Nested Structures in C:
• Structure within structure.
• One structure can be declared inside other structure as we declare
structure members inside a structure.
• The structure variables can be a normal structure variable or a pointer
variable to access the data.
• There are two ways, we can access the structure data:
1.Structure within structure in C using normal variable(using dot Operator).
2.Structure within structure in C using pointer variable(using->operator).
Sunday, 07 April 2024 63
64. Cont’d…
1. STRUCTURE WITHIN STRUCTURE IN C USING NORMAL VARIABLE:
#include <stdio.h>
struct student_college_detail
{
int college_id;
char college_name[30];
};
struct student_detail
{
int rollno;
char name[20];
float percentage;
// structure within structure
struct student_college_detail clg_data;
}stu_data;
Sunday, 07 April 2024 64
65. Cont’d…
int main()
{
struct student_detail stu_data = {1, "Shrinivasa", 90.5, 150, "SMVITM BANTAKAL"};
printf(" Roll number is: %d n", stu_data.rollno);
printf(" Name is: %s n", stu_data.name);
printf(" Percentage is: %f nn", stu_data.percentage);
printf(" College Id is: %d n", stu_data.clg_data.college_id);
printf(" College Name is: %s n", stu_data.clg_data.college_name);
return 0;
}
Sunday, 07 April 2024 65
66. Cont’d…
2. STRUCTURE WITHIN STRUCTURE (NESTED STRUCTURE IN C ) USING POINTER VARIABLE:
#include <stdio.h>
struct student_college_detail
{
int college_id;
char college_name[30];
};
struct student_detail
{
int rollno;
char name[20];
float percentage;
// structure within structure
struct student_college_detail clg_data;
}stu_data,*stu_data_ptr;
Sunday, 07 April 2024 66
67. Cont’d…
int main()
{
struct student_detail stu_data = {1, "Shrinivasa", 90.5, 150, "SMVITM BANTAKAL"};
stu_data_ptr=&stu_data;
printf(" Roll number is: %d n", stu_data.rollno);
printf(" Name is: %s n", stu_data.name);
printf(" Percentage is: %f n", stu_data.percentage);
printf(" College Id is: %d n", stu_data_ptr->clg_data.college_id);
printf(" College Name is: %s n",stu_data_ptr->clg_data.college_name);
return 0;
}
Sunday, 07 April 2024 67
68. Example
typedef struct
{
int date; int month; int year;
} Date;
typedef struct {
char name[10];
int age;
float salary;
Date DOB;
} humanbeing;
The structure variable can be created as follows:
humanbeing person1;
Sunday, 07 April 2024 68
69. Now we can access the fields from nested
structure Date as shown below:
Person1.DOB.date = 21;
Person1.DOB.month = 4;
Person1.DOB.year = 2017;
Sunday, 07 April 2024 69
70. Self-Referential Structures:
• One or more of the structure components (or fields) is a pointer
to itself.
Struct tag_name
{
data_type1 member1;
data_type2 member2;
…. ….
struct tag_name pointer_variable;
};
(Please Refer the Next Slide)
Sunday, 07 April 2024 70
71. Contd…
• Example: struct node
{
int data;
struct node *link;
};
Now create three variables of type node: item1, item2, and item3:
struct node item1,item2,item3;
Sunday, 07 April 2024 71
72. Now create three variables of type node:
item1, item2, and item3:
Struct node item1, item2, item3;
item1.data = ‘A’; item1.link = NULL;
item2.data = ‘B’; item2.link = NULL;
item3.data = ‘C’; item3.link = NULL;
item1.link = &item2;
item2.link = &item3;
Sunday, 07 April 2024 72
73. Analyzing the previous slide code
• The structure of the node After execution of the statement:
item1.data = ‘A’; item1.link = NULL;
• The structure of the node After execution of the statement:
item2.data = ‘B’; item2.link = NULL;
• The structure of the node After execution of the statement:
item3.data = ‘C’; item3.link = NULL;
Contd…
Sunday, 07 April 2024 73
74. Contd…
• After the statements:
item1.link = &item2;
item2.link = &item3;
The list becomes:
Sunday, 07 April 2024 74
75. Array of structures:
Definition: Structure is used to store information of one particular object and if one has to
store large number of such objects then array of structure is used.
Example: we need to store records of 10 students of a class, where each student record has
5 fields: roll number, sname,marksofds in test1,marksofds in test2,marksofds in test3.
An array of student structure can be defined and declared as:
struct student
{
int roll_no;
char sname[20];
float dmit1;
float dmit2;
float dmit3;
};
struct student stud[10];
Sunday, 07 April 2024 75
76. Unions
•A union is similar to a structure which is also collection of
data items of similar/dissimilar data types which are
identified by unique name using identifier(members of a
union).
•We can define a union with many members, but only one
member can contain a value at any given time.
•Unions provide an efficient way of using the same memory
location for multiple-purpose.
Sunday, 07 April 2024 76
77. Cont’d…
Syntax of union:
union tag_name
{
data_type1 member1;
data_type2 member2;
…. ….
};
Or using typedef:
typedef union
{
data_type1 member1;
data_type2 member2;
…. …..
}tag_name;
Sunday, 07 April 2024 77
78. Cont’d…
Example: union item
{
int i;
char c;
double d;
} x;
Memory representation: d=4bytes
c=1byte
i=2bytes
Note: maximum memory is highest size of member of a union i.e 4bytes of double data type d.
Sunday, 07 April 2024 78
79. C program to show how structure behaves
#include<stdio.h>
int main()
typedef struct
{
int marks;
char grade;
float percentage;
} student;
student cse={100, ’A’, 99.5};
printf(“marks=%dn”,cse.marks);
Printf(“grade=%cn”,cse.grade);
Printf(“percentage=%fn”,cse.percentage);
Return 0;
}
Sunday, 07 April 2024 79
82. The difference between structure and union
Sl. # Structure Union
1 The amount of memory required to
store a structure variable is the sum
of the size of all the members
The amount of memory required is
always equal to that required by its
largest member.
2 All the members can be accessed by
a single structure variable.
Only one member can be accessed
by a union variable.
3 All the members have different
storage.
All the members share a single
memory location whose size is
equal to the largest size of the
union member.
Sunday, 07 April 2024 82
83. Cont’d…
Sl. # Structure Union
4 Keyword struct is used to
define a structure
Keyword union is used to define a union.
5 Address of each member will be
in ascending order(Different
address)
Address is same for all the members of a
union.
6 Altering the value of a member
will not affect other members of
structure.
Altering value of any of the member will
alter other member values
Sunday, 07 April 2024 83
84. Dynamically allocated arrays:
The array can be dynamically allocated using malloc(),calloc() or realloc() functions.
Similarly allocated memory can be freed using free() function.
Advantage: memory for array of any desired size can be allocated, No need of fixed
sized array.
Eg) Write a C program for dynamic array
#include<stdio.h>
int main()
{
int n, i, sum=0;
int *p;
printf(“nEnter the number of elements:”);
scanf(“%d”,&n);
Sunday, 07 April 2024 84
87. Arrays: Linear arrays
It is a list of finite number ‘n’ of homogeneous elements of same type
such that: a) elements of array are referenced by respective index set
consisting of consecutive numbers.
b) Elements of array are stored respectively in successive memory
locations.
Number of elements are called length/size of array.
Length=UB – LB +1
Suppose if there are n=5 elements:
UB=4
LB=0
Therefore Length=4-0+1=5
Sunday, 07 April 2024 87
88. Cont’d…
Eg) An automobile company wants to store sales data in array from
1030 to 1084
AUTO[1030]=100
AUTO[1031]=105
….
AUTO[1084]=195
Length=UB-LB+1
=1084-1030+1
=54+1=55 locations
Sunday, 07 April 2024 88
89. Address Calculation in single (one) Dimension Array(LA):
Array of an element of an array say “A[ I ]” is calculated using the
following formula:
Address of A [ I ] = B + W * ( I – LB )
Where,
B = Base address
W = Storage Size of one element stored in the array (in byte)
I = Subscript of element whose address is to be found
LB = Lower limit / Lower Bound of subscript, if not specified assume
0 (zero)
Sunday, 07 April 2024 89
91. Cont’d…
Example:
Given the base address of an array B[1300…..1900] as 1020 and size of
each element is 2 bytes in the memory. Find the address of B[1700].
Solution:
The given values are: B = 1020, LB = 1300, W = 2, I = 1700
Address of A [ I ] = B + W * ( I – LB )
=1020 + 2 * (1700 – 1300)
= 1020 + 2 * 400
= 1020 + 800
= 1820 [Ans]
Sunday, 07 April 2024 91
92. Traversing arrays:
Let an array A be a collection of data elements, stored in memory of computer.
Suppose we want to print each content of A or want to count the number of
elements.
This can be accomplished by traversing the array.
Which means visiting each element of array A exactly once.
ALGORITH to traverse the array(using while loop)
Step 1: [initialize counter] set k=LB
Step 2: Repeat steps 3 and 4 while k<=UB
Step 3: [Visit element] Apply process to A[k]
Step 4: [Increase counter] set k=k+1
[End of step 2 loop]
Step 5: Exit
Sunday, 07 April 2024 92
93. ALGORITH to traverse the array(using for loop)
Step 1: Repeat for k=LB to UB
Apply process to A[k]
[End of for loop]
Step 2: Exit
Eg) Write a C program to traverse an array using while loop
#include<stdio.h>
int main()
{
int a[5]={10,20,30,40,50};
int i=0;
while(i<=4)
{
printf(“%dn”, a[i]);
i=i+1;
}
return 0;
}
Sunday, 07 April 2024 93
94. Write a C program to traverse an array using for loop
#include<stdio.h>
int main()
{
int a[5]={10,20,30,40,50};
int i;
for(i=0;i<=4;i++)
{
printf(“%dn”, a[i]);
}
return 0;
}
Sunday, 07 April 2024 94
95. Two Dimensional Arrays:
•First, create an array of pointers of size r.
•Dynamically allocate memory for every row.
Sunday, 07 April 2024 95
96. Array Operations: Traversing:
• It is the operation of accessing and processing each element
in the linear array exactly once.
• Example:
(i) Count the number of elements in the array
(ii) Display the elements of the array
(iii) Calculate sum of each elements in the array. Etc…
Sunday, 07 April 2024 96
97. ALGORITHM: Here LA is the Linear Array with lower bound
LB, and upper bound UB. This algorithm traverses LA applying
the operation PROCESS to each element in LA.
ONE ALGORITHM
[Initialize the Counter] SET K = LB
Repeat Step 3 and 4 while K <= UB
[Visit Element] Apply PROCESS to LA[K]
[Increase the Counter] K = K + 1
End of Step 2 Loop
Exit
ALTERNATE ALGORITHM
Repeat for K = LB to UB
[Visit Element] Apply PROCESS to LA[K]
End of Step 2 Loop
Exit
Sunday, 07 April 2024 97
98. Array Operations: Inserting and Deleting:
• Inserting refers to adding another element into the collection.
• Deleting refers to removing the one of the element from the
collection.
• Two Categories of Insertion and Deletion:
Sunday, 07 April 2024 98
INSERTION DELETION
Insertion at end of the list. Deletion at end of the list.
Insertion at middle or beginning
of the list.
Deletion at middle or beginning
of the list.
99. Insertion Operation
32
Assume that we
want to insert
the new element
41 at position 3;
First move 37 to
next position, the
array becomes
32
After
moving
the value
13 to next
position,
the array
becomes
32
After
moving
the value
59 to
next
position,
the array
becomes
32
Now insert
the new
element 41
to the
location 3,
the array
becomes
32
48 48 48 48 48
24 24 24 24 24
59 59 59 59 41
13 13 13 59 59
37 37 13 13 13
37 37 37 37
Sunday, 07 April 2024 99
• Let initial number of elements in the array is 6 as shown below:
100. Insertion at the End of the List A
•If n < MAXSIZE of Array, then simply insert the
element as : A[n] = element;
•Increment the n value: n++;
Sunday, 07 April 2024 100
101. Deletion at the End of the List A
•If n > 0, then simply decrement the the n value:
n--;
Sunday, 07 April 2024 101
102. Inserting at middle / Beginning of the List A
• Let k be the position of the new element to be inserted.
• nth element must be moved to n+1th position of the A
• n – 1th element must be moved to nth position of the A
• n – 2th element must be moved to n – 1th position of the A
• …………..
• and so on
• The element from kth position must be moved to k+1th position.
• Now insert the new element at kth position.
Sunday, 07 April 2024 102
103. The pseudo code for this
Let n be the total number of elements currently in the array A.
Let MAXSIZE is the maximum size declared to the array A.
Let k be the position of new element to be inserted.
Let x be the new element to be inserted.
Then the pseudo code for inserting the new element x into kth position
of the array will be:
for (i = n – 1 ; i >= k; i--)
{
a[i+1] = a[i];
}
a[k] = x;
n++;
Sunday, 07 April 2024 103
104. Deleting at middle/Beginning of the List A
• Let k be the position of the element to be deleted.
• k+1th element must be moved to kth position of the A
• k + 2th element must be moved to k+1th position of the A
• k + 3th element must be moved to k + 2th position of the A
• …………..
• and so on
• The element from n–1th position must be moved to n–2th position.
• Decrement the value of n by 1. (that is n – –)
Sunday, 07 April 2024 104
105. The pseudo code for this
Let n be the total number of elements currently in the array A.
Let MAXSIZE is the maximum size declared to the array A.
Let k be the position of the element to be deleted.
Then the pseudo code for deleting the element x from the kth position
of the array will be:
for (i = k + 1 ; i < n; i++)
{
a[i-1] = a[i];
}
n--;
Sunday, 07 April 2024 105
106. Deletion Operation
32
Assume that we
want to delete
the element 24
at position 2;
First move 59 to
previous
position, the
array becomes
32
After
moving the
value 13 to
previous
position,
the array
becomes
32
After
moving the
value 37 to
next
position,
the array
becomes
32
After
decrementing
the value of n
(that is n--),
the array
becomes
32
48 48 48 48 48
24 59 59 59 59
59 59 13 13 13
13 13 13 37 37
37 37 37 37
Sunday, 07 April 2024 106
• Let initial number of elements in the array is 6 as shown below:
111. Linear Search
•Definition: The process of searching a key element in
the given array Linearly element by element from the
beginning of the array to end of the array is known as
Linear Search
Sunday, 07 April 2024 111
112. Example
58 X 58 58 58 58 58 58
42 42 X 42 42 42 42 42
61 61 61 X 61 61 61 61
74 74 74 74 X 74 74 74
26 26 26 26 26 X 26 26
37 37 37 37 37 37 X 37
13 13 13 13 13 13 √ 13
Sunday, 07 April 2024 112
Assume that the key element to be searched in array is 13. The array given is
as shown below:
113. Binary Search
•Definition: It is the process of searching a ascending ordered
sorted array by repeatedly dividing the search interval in half. Begin
with an interval covering the whole array. If the value of
the search key is less than the item in the middle of the interval,
narrow the interval to the lower half. If the value of the search key is
greater than the item in the middle of the interval, narrow the
interval to the upper half.
Sunday, 07 April 2024 113
114. Multidimensional Arrays:
Two Dimensional Arrays:
•A two dimensional m x n array A is a collection of m*n
data elements such that each element is specified by a
pair of integers (say j and k) called subscripts with the
property that 1 <= j <= m and 1 <= k <= n.
•This element is denoted by the notation: A[j][k]
Sunday, 07 April 2024 114
115. Representation of Two dimensional
array in Memory:
(i) Column Major representation and
(ii) Row Major representations
Sunday, 07 April 2024 115
116. Column Major representation
•Some languages stores this array in column by
column. This type of memory representation for the
array is also known as column major memory
representation.
Sunday, 07 April 2024 116
117. Row Major representations
•Some languages stores this array in row by row
form. This type of memory representation for
the array is also known as row major memory
representation.
Sunday, 07 April 2024 117
118. • Consider an example of 3 x 4 integer array: The total
number of integer location required to store the data
elements of this array is 3 * 4 = 12 integer locations.
Sunday, 07 April 2024 118
119. Using Column Major Representation:
In C Language In PASCAL Language
0 1 A[0][0]
Column 0
1 2 A[1][0]
2 3 A[2][0]
3 4 A[0][1]
Column 1
4 5 A[1][1]
5 6 A[2][1]
6 7 A[0][2]
Column 2
7 8 A[1][2]
8 9 A[2][2]
9 10 A[0][3]
Column 3
10 11 A[1][3]
11 12 A[2][3]
Sunday, 07 April 2024 119
120. Using Row Major Representation:
In C Language In PASCAL Language
0 1 A[0][0]
Row 1
1 2 A[0][1]
2 3 A[0][2]
3 4 A[0][3]
4 5 A[1][0]
5 6 A[1][1]
6 7 A[1][2]
7 8 A[1][3]
8 9 A[2][0]
9 10 A[2][1]
10 11 A[2][2]
11 12 A[2][3]
Sunday, 07 April 2024 120
Row 0
Row 1
Row 2
Row 0
121. Address Calculation in Column Major
In C Language:
• The Address of A[0][0]
= BA+w*(3*0+0) = BA+w*0=BA
• The Address of A[0][1]
= BA+w*(3*1+0) = BA + w*3
• The Address of A[0][2]
= BA+w*(3*2+0) = BA + w*6
• The Address of A[0][3]
= BA+w*(3*3+0) = BA + w*9
In PASCAL Language:
• The Address of A[1][1]
= BA+w*(3*(1–1)+(1–1) = BA+w*0
• The Address of A[1][2]
= BA+w*(3*(2–1)+(1–1)) = BA + w*3
• The Address of A[1][3]
= BA+w*(3*(3–1)+(1–1)) = BA + w*6
• The Address of A[1][4]
= BA+w*(3*(4–1)+(1–1)) = BA + w*9
Sunday, 07 April 2024 121
m x n Array: m = 3, and n = 4. Assume that Base Address is 4000
122. Address Calculation in Column Major
•In C Language:
LOC(A[i][j] = Base(A) + w*(m * j + i)
Sunday, 07 April 2024 122
123. Address Calculation in Row Major
In C Language:
• The Address of A[0][0]
= BA+w*(4*0+0) = BA+w*0
• The Address of A[0][1]
= BA+w*(4*0+1) = BA + w*1
• The Address of A[0][2]
= BA+w*(4*0+2) = BA + w*2
• The Address of A[0][3]
= BA+w*(4*0+3) = BA + w*3
In PASCAL Language:
• The Address of A[1][1]
= BA+w*( (1–1)+4* (1–1) = BA+w*0
• The Address of A[1][2]
= BA+w*( (2–1)+4* (1–1)) = BA + w*1
• The Address of A[1][3]
= BA+w*( (3–1)+4* (1–1)) = BA + w*2
• The Address of A[1][4]
= BA+w*( (4–1)+4* (1–1)) = BA + w*3
Sunday, 07 April 2024 123
m x n Array: m = 3, and n = 4. Assume that Base Address is 4000
124. Address Calculation in Row Major
•In C Language:
LOC(A[i][j] = Base(A) + w*(n * i + j)
Sunday, 07 April 2024 124
125. Multi-Dimensional Arrays:
Two Dimensinal Array, which is the simplest form of C Multi Dimensional Array.
In C Programming Language, by placing n number of brackets [ ], we can declare
n-dimensional array where n is dimension number.
For example:
• int a[2][3][4] = Three Dimensional Array
• int a[2][2][3][4] = Four Dimensional Array
The basic syntax or, the declaration of multi dimensional array in C Programming is:
Data_type Array_Name[Tables][Row_Size][Column_Size];
Data_type: It will decide the type of elements it will accept. For example, If we
want to store integer values then we declare the Data type as int, If we want to
store Float values then we declare the Data type as float etc.
Sunday, 07 April 2024 125
126. Cont’d…
• Array_Name: This is the name you want to give it to Multi Dimensional array in C.
• Tables: It will decide the number of tables an array can accept. Two Dimensional
Array is always a single table with rows and columns. In contrast, Multi
Dimensional array in C is more than 1 table with rows and columns.
• Row_Size: Number of Row elements an array can store.
For example, Row_Size =10, the array will have 10 rows.
• Column_Size: Number of Column elements an array can store.
For example, Column_Size = 8, the array will have 8 Columns.
Sunday, 07 April 2024 126
127. Cont’d…
We can calculate the maximum number of elements in a Three Dimensional
using: [Tables] * [Row_Size] * [Column_Size]
For Example
• int Employees[2][4][3];
• Here, we used int as the data type to declare an array. So, the above
array will accept only integers. If you try to add float values, it throws
an error.
• Employees is the array name
• The number of tables = 2. So, this array will hold a maximum of 2
levels of data (rows and columns).
Sunday, 07 April 2024 127
128. Cont’d…
• The Row size of an Array is 4. It means Employees array only accept 4
integer values as rows.
• If we try to store more than 4, it throws an error.
• We can store less than 4. For Example, If we store 2 integer values, the
remaining two will assign with the default value (Which is 0).
• The Column size of an Array is 3. It means Employees array will only
accept 3 integer values as columns.
• If we try to store more than 3, it throws an error.
• We can store less than 3. For Example, If we store 1 integer values, the
remaining 2 values will assign with the default value (Which is 0).
• Finally, Employees array can hold a maximum of 24 integer values (2 *
4 * 3 = 24).
Sunday, 07 April 2024 128
129. C Multi Dimensional Array Initialization:
• int Employees[2][4][3] = { { {10, 20, 30}, {15, 25, 35}, {22, 44, 66},
{33, 55, 77} },
{ {1, 2, 3}, {5, 6, 7}, {2, 4, 6}, {3, 5, 7} } };
Here, We have 2 tables and the 1st table holds 4 Rows * 3 Columns,
and the 2nd table also holds 4 Rows * 3 Columns.
The first three elements of the first table will be 1st row, the second three
elements will be 2nd row, the next three elements will be 3rdrow, and the last
3 elements will be 4th row. Here we divided them into 3 because our column
size = 3, and we surrounded each row with curly braces ({}). It is always good
practice to use the curly braces to separate the rows.
Sunday, 07 April 2024 129
130. Polynomials
•Definition: Polynomial is a sum of terms
where each term has the form a*xn
where x is a variable, a is coefficient and
n is a exponent.
Sunday, 07 April 2024 130
131. Example:
•Consider A(x) and B(x) are two polynomials
having the values:
•A(x) = 3x20 + 2x5 +4 and
•B(x) = x4 + 10x3 + 3x2 +1
Sunday, 07 April 2024 131
132. Some Terminologies on Polynomial
•The largest (or leading) exponent of a
polynomial is called Degree of the polynomial.
Coefficient that are zero are not displayed (need
not be specified).
•The term with the exponent zero does not show
the variable. Since x0 = 1.
Sunday, 07 April 2024 132
133. Polynomial Addition Final Result
Let A, B, and D be the polynomial as shown below:
A = 12*x265 + 52*x11 + 8*x6 + 42
B = 63*x345 + 19*x25 + 47*x11 + 32*x + 74
----------------------------------------------------------------------------------
D = 63*x345 + 12*x265 + 19*x25 + 99*x11 + 8*x6 + 32*x + 116
Sunday, 07 April 2024 133
134. Polynomial Representation using structure:
#define MAX_TERMS 100 /* size of terms array */
typedef struct {
float coef;
int expon;
} polynomial;
polynomial terms[MAX_TERMS];
int avail = 0;
Sunday, 07 April 2024 134
135. Storing all the polynomial in one global array
Assume that A(x) and B(x) are two polynomials with the values:
A(x)=2x1000+1 and
B(x)=x4+10x3+3x2+1
Sunday, 07 April 2024 135
136. Array representation of two polynomials will be:
start A finish A start B finish B avail
Coef 2 1 1 10 3 1
Expon 1000 0 4 3 2 0
Index 0 1 2 3 4 5 6
Sunday, 07 April 2024 136
Specification representation
Poly <start, finish>
A <0, 1>
B <2, 5>
137. Assume the function COMPARE is defined as follows:
int COMPARE(int p, int q)
{
if(p < q) return -1;
else if(p == q) return 0;
else return 1;
}
Sunday, 07 April 2024 137
138. Add two polynomials: D = A + B
void padd(int startA, int finishA, int startB, int
finishB, int *startD, int *finishD)
{ /* add A(x) and B(x) to obtain D(x) */
float coefficient;
*startD = avail;
while (startA <= finishA && startB <= finishB)
{
switch(COMPARE(terms[startA].expon,terms[startB].expon))
{
case -1: /* a expon < b expon */
attach(terms[startB].coef,terms[startB].expon);
startB++
break;
Continuation is in the Next Slide
Sunday, 07 April 2024 138
139. Add two polynomials: D = A + B
case 0: /* equal exponents */
coefficient = terms[startA].coef + terms[startB].coef;
if (coefficient)
{
attach(coefficient, terms[startA].expon);
startA++; startB++;
}
break;
case 1: /* a expon > b expon */
attach(terms[startA].coef, terms[startA].expon);
startA++;
}/*end of switch*/
}/*end of while*/
Continuation is in the Next Slide
Sunday, 07 April 2024 139
140. Add two polynomials: D = A + B Cont’d…
/* add in remaining terms of A(x) */
for( ; startA<= finishA; startA++)
attach(terms[startA].coef, terms[startA].expon);
/* add in remaining terms of B(x) */
for( ; startB<= finishB; startB++)
attach(terms[startB].coef, terms[startB].expon);
*finishD =avail – 1;
}
Continuation is in the Next Slide
Sunday, 07 April 2024 140
141. The Function Attach()
void attach(float coefficient, int exponent)
{
/* add a new term to the polynomial */
if (avail >= MAX_TERMS)
{
fprintf(stderr, “Too many terms in the polynomialn”);
exit(1);
}
terms[avail].coef = coefficient;
terms[avail++].expon = exponent;
}
Sunday, 07 April 2024 141
142. Sparse Matrices.
•The matrix with more number of zeroes is known
as sparse matrix.
•Each element in the matrix requires the separate
storage.
•If the matrix contains zero element that means
there is a NULL element. Storage for NULL element
is waste of space.
Sunday, 07 April 2024 142
144. Triplet Representation of the Sparse Matrix:
•Each element is characterized by <row, col, value>.
Sunday, 07 April 2024 144
145. We can create sparse matrix by using the
structure as follows:
#define MAX_TERMS 101 /* maximum number of terms+1 */
typedef struct {
int col;
int row;
int value;
} term;
term a[MAX_TERMS];
Sunday, 07 April 2024 145
146. Rules to represent the sparse matrix
in Triplet representation:
• The First Tuple in the triplet representation must be Total number of
rows in the sparse matrix, Total number of columns in the sparse
matrix, and the total number of nonzero values in the sparse matrix.
• The remaining tuples contains the respective row, col and nonzero
values.
• The tuples must be entered in to the triplet form so that the row
must be in ascending order. If there are multiple items in the same
row, then column must be in ascending order.
Sunday, 07 April 2024 146
147. Example: Consider the following Sparse Matrix:
Sunday, 07 April 2024 147
Col 0 Col 1 Col 2 Col 3 Col 4 Col 5
Row 0 15 0 0 22 0 –15
Row 1 0 11 3 0 0 0
Row 2 0 0 0 –6 0 0
Row 3 0 0 0 0 0 0
Row 4 91 0 0 0 0 0
Row 5 0 0 28 0 0 0
151. Function / Algorithm for simple Transpose
void transpose (term a[], term b[]) /* b is set to the transpose of a */
{
int n, i, j, currentb;
n = a[0].value; /* total number of elements */
b[0].row = a[0].col; /* rows in b = columns in a */
b[0].col = a[0].row; /*columns in b = rows in a */
b[0].value = n;
if (n > 0)
{ /*non zero matrix */
currentb = 1;
for (i = 0; i < a[0].col; i++)
/* transpose by columns in a */
for(j = 1; j <= n; j++)
/* find elements from the current column */
if (a[j].col == i)
{
/* element is in current column, add it to b */
b[currentb].row = a[j].col; b[currentb].col = a[j].row;
b[currentb].value = a[j].value; currentb++
}
}
}
Sunday, 07 April 2024 151
152. Compared with 2-D array representation
O(columns + elements) vs. O(columns * rows)
Sunday, 07 April 2024 152
Triplet Representation 2-D array representation
Array contains x number of elements
where x = total number of nonzero
elements in the matrix
Array contains m * n number of
elements.
Algorithm scans the array only x
times
Algorithm scans the array m *n
number of times i.e., O(m*n)
153. Fast Transpose Algorithm
Sunday, 07 April 2024 153
void fast_transpose(term a[ ], term b[ ])
{
/* the transpose of a is placed in b */
int rowterms[MAX_COL], startingpos[MAX_COL];
int i, j, numcols = a[0].col, numterms = a[0].value;
b[0].row = numcols; b[0].col = a[0].row;
b[0].value = numterms;
if (numterms > 0)
{
/*nonzero matrix*/
for (i = 0; i < numcols; i++)
rowterms[i] = 0;
for (i = 1; i <= numterms; i++)
rowterm [a[i].col]++
startingpos[0] = 1;
for (i =1; i < numcols; i++)
startingpos[i]=startingpos[i-1] +rowterms [i-1];
for (i=1; i <= numterms, i++)
{
j = startingpos[a[i].col]++;
b[j].row = a[i].col; b[j].col = a[i].row; b[j].value = a[i].value;
}
}
}