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
Saturday, 28 November 2020 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
Saturday, 28 November 2020 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.
Saturday, 28 November 2020 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);
• }
Saturday, 28 November 2020 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.
Saturday, 28 November 2020 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 OperationsSaturday, 28 November 2020 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.
Saturday, 28 November 2020 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 primitive d.s.
Saturday, 28 November 2020 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…
Saturday, 28 November 2020 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…
Saturday, 28 November 2020 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…
Saturday, 28 November 2020 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.
Saturday, 28 November 2020 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.
Saturday, 28 November 2020 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.
Saturday, 28 November 2020 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.
Saturday, 28 November 2020 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: *
Saturday, 28 November 2020 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:
Saturday, 28 November 2020 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.
Saturday, 28 November 2020 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.
Saturday, 28 November 2020 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);
• }
Saturday, 28 November 2020 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.
Saturday, 28 November 2020 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
Saturday, 28 November 2020 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
Saturday, 28 November 2020 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:
Saturday, 28 November 2020 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];
Saturday, 28 November 2020 28
29. Dynamic m/m allocation:
• The allocation and deallocation 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.
Saturday, 28 November 2020 29
30. Dynamic memory allocation
• This technique has 4 predefined functions to allocate and deallocate
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.
Saturday, 28 November 2020 30
31. Contd…
• Syntax: data_type pointer_variable_name;
• Pointer_variable_name=(data_type*)malloc(size_of_memory);
• Eg) int *ptr;
• ptr=(int *)malloc(10*sizeof(int));
• If m/m is successfully allocated then address of the first byte of
allocated m/m space is returned.
• if m/m allocation fails, then NULL is returned.
• The m/m space created with malloc() contain garbage values.
Saturday, 28 November 2020 31
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
Saturday, 28 November 2020 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 int blocks & allocates total m/m
required.
• Therefore 20*2 bytes for int=40bytes of m/m block is allocated.
Saturday, 28 November 2020 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(int));
• 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:00000000000000000000
New memory has:LABORATORY
Saturday, 28 November 2020 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.
Saturday, 28 November 2020 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.
Saturday, 28 November 2020 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.
Saturday, 28 November 2020 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;
}
Saturday, 28 November 2020 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.
Saturday, 28 November 2020 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.
Saturday, 28 November 2020 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);
}
Saturday, 28 November 2020 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);
}
Saturday, 28 November 2020 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).
Saturday, 28 November 2020 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);
}
Saturday, 28 November 2020 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.
Saturday, 28 November 2020 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;
};
Saturday, 28 November 2020 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.
Saturday, 28 November 2020 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;
Saturday, 28 November 2020 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;
Saturday, 28 November 2020 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;
Saturday, 28 November 2020 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.
Saturday, 28 November 2020 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;
Saturday, 28 November 2020 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;
Saturday, 28 November 2020 54
55. Variations of the Structure Declaration
Saturday, 28 November 2020 55
56. Variations of the Structure Declaration
Saturday, 28 November 2020 56
57. Variations of the Structure Declaration
Saturday, 28 November 2020 57
58. Variations of the Structure Declaration
Saturday, 28 November 2020 58
59. Variations of the Structure Declaration
Saturday, 28 November 2020 59
60. Variations of the Structure Declaration
Saturday, 28 November 2020 60
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:
Saturday, 28 November 2020 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).
Saturday, 28 November 2020 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;
Saturday, 28 November 2020 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;
}
Saturday, 28 November 2020 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;
Saturday, 28 November 2020 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;
}
Saturday, 28 November 2020 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;
Saturday, 28 November 2020 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;
Saturday, 28 November 2020 69
70. Self-Referential Structures:
• One or more of the structure components (or fields) is a pointer
to itself.
typedef struct
{
char data;
struct list *link;
} list;
• Now create three variables of type list: item1, item2, and item3:
(Please Refer the Next Slide)
Saturday, 28 November 2020 70
71. Now create three variables of type list:
item1, item2, and item3:
list 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;
Saturday, 28 November 2020 71
72. Analyzing the previous slide code
• The structure of the list After execution of the statement:
item1.data = ‘A’; item1.link = NULL;
• The structure of the list After execution of the statement:
item2.data = ‘B’; item2.link = NULL;
• The structure of the list After execution of the statement:
item3.data = ‘C’; item3.link = NULL;
Contd…
Saturday, 28 November 2020 72
73. Contd…
• After the statements:
item1.link = &item2;
item2.link = &item3;
The list becomes:
Saturday, 28 November 2020 73
74. 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.
Saturday, 28 November 2020 74
75. 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;
Saturday, 28 November 2020 75
76. 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.
Saturday, 28 November 2020 76
77. 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;
}
Saturday, 28 November 2020 77
80. 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.
Saturday, 28 November 2020 80
81. 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
Saturday, 28 November 2020 81
82. Example: Union Declaration:
#include <stdio.h>
#include <string.h>
union student {
char name[20];
char subject[20];
float percentage;
};
Saturday, 28 November 2020 82
83. Example: Main Function
int main()
{
union student record1;
union student record2;
// assigning values to record1 union variable
strcpy(record1.name, "Raju");
strcpy(record1.subject, "Maths");
record1.percentage = 86.50;
Saturday, 28 November 2020 83
85. The Result of the above Program will be:
Union record1 values example:
Name :
Subject :
Percentage : 86.500000;
Union record2 values example
Name : Mani
Subject : Physics
Percentage : 99.500000
Saturday, 28 November 2020 85
86. 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);
Saturday, 28 November 2020 86
89. 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
Saturday, 28 November 2020 89
90. 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
Saturday, 28 November 2020 90
91. 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)
Saturday, 28 November 2020 91
93. 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]
Saturday, 28 November 2020 93
94. 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
Saturday, 28 November 2020 94
95. 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;
}
Saturday, 28 November 2020 95
96. 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;
}
Saturday, 28 November 2020 96
97. Two Dimensional Arrays:
•First, create an array of pointers of size r.
•Dynamically allocate memory for every row.
Saturday, 28 November 2020 97
98. 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…
Saturday, 28 November 2020 98
99. 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
Saturday, 28 November 2020 99
100. 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:
Saturday, 28 November 2020 100
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.
101. 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
Saturday, 28 November 2020 101
• Let initial number of elements in the array is 6 as shown below:
102. 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++;
Saturday, 28 November 2020 102
103. Deletion at the End of the List A
•If n > 0, then simply decrement the the n value:
n--;
Saturday, 28 November 2020 103
104. 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.
Saturday, 28 November 2020 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 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++;
Saturday, 28 November 2020 105
106. 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 – –)
Saturday, 28 November 2020 106
107. 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--;
Saturday, 28 November 2020 107
108. 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
Saturday, 28 November 2020 108
• Let initial number of elements in the array is 6 as shown below:
113. 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
Saturday, 28 November 2020 113
114. 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
Saturday, 28 November 2020 114
Assume that the key element to be searched in array is 13. The array given is
as shown below:
115. 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.
Saturday, 28 November 2020 115
116. 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]
Saturday, 28 November 2020 116
117. Representation of Two dimensional
array in Memory:
(i) Column Major representation and
(ii) Row Major representations
Saturday, 28 November 2020 117
118. 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.
Saturday, 28 November 2020 118
119. 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.
Saturday, 28 November 2020 119
120. • 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.
Saturday, 28 November 2020 120
121. Using Column Major Representation:
In C Language In PASCAL Language
0 1 A[0][0]
Column 01 2 A[1][0]
2 3 A[2][0]
3 4 A[0][1]
Column 14 5 A[1][1]
5 6 A[2][1]
6 7 A[0][2]
Column 27 8 A[1][2]
8 9 A[2][2]
9 10 A[0][3]
Column 310 11 A[1][3]
11 12 A[2][3]
Saturday, 28 November 2020 121
122. 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]
Saturday, 28 November 2020 122
Row 0
Row 1
Row 2
Row 0
123. 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
Saturday, 28 November 2020 123
m x n Array: m = 3, and n = 4. Assume that Base Address is 4000
124. Address Calculation in Column Major
•In C Language:
LOC(A[j][k] = Base(A) + w*(m * k + j)
•In Pascal Language:
LOC(A[j][k] = Base(A) + w*(m*(k–1)+(j–1))
Saturday, 28 November 2020 124
125. 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
Saturday, 28 November 2020 125
m x n Array: m = 3, and n = 4. Assume that Base Address is 4000
126. Address Calculation in Row Major
•In C Language:
LOC(A[j][k] = Base(A) + w*(n * j + k)
•In Pascal Language:
LOC(A[j][k] = Base(A) + w*(n*(j–1)+(k–1))
Saturday, 28 November 2020 126
127. 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.
Saturday, 28 November 2020 127
128. 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.
Saturday, 28 November 2020 128
129. 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).
Saturday, 28 November 2020 129
130. 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).
Saturday, 28 November 2020 130
131. 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.
Saturday, 28 November 2020 131
132. 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.
Saturday, 28 November 2020 132
133. 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
Saturday, 28 November 2020 133
134. 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.
Saturday, 28 November 2020 134
135. 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
Saturday, 28 November 2020 135
136. 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;
Saturday, 28 November 2020 136
137. 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
Saturday, 28 November 2020 137
138. 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
Saturday, 28 November 2020 138
Specification representation
Poly <start, finish>
A <0, 1>
B <2, 5>
139. 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;
}
Saturday, 28 November 2020 139
140. 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
Saturday, 28 November 2020 140
141. 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
Saturday, 28 November 2020 141
142. 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
Saturday, 28 November 2020 142
143. 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;
}
Saturday, 28 November 2020 143
144. 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.
Saturday, 28 November 2020 144
146. Triplet Representation of the Sparse Matrix:
•Each element is characterized by <row, col, value>.
Saturday, 28 November 2020 146
147. 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];
Saturday, 28 November 2020 147
148. 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.
Saturday, 28 November 2020 148
149. Example: Consider the following Sparse Matrix:
Saturday, 28 November 2020 149
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
153. 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++
}
}
}
Saturday, 28 November 2020 153
154. Compared with 2-D array representation
O(columns + elements) vs. O(columns * rows)
Saturday, 28 November 2020 154
Triplex 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)
155. Fast Transpose Algorithm
Saturday, 28 November 2020 155
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;
}
}
}