SlideShare a Scribd company logo
1 of 157
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
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
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
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
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
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
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
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
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
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
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
DATA STRUCTURE OPERATIONS:
•Traversing
•Searching
•Inserting
•Deleting
The following two operations, which are used in special
situations:
•Sorting
•Merging
Saturday, 28 November 2020 12
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
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
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
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
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
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
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
Contd…
Saturday, 28 November 2020 20
0 10
1 20
2 30
3 40
. …
. …
65535 …
dataAddress
m/m
locations
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
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
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
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
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
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
Logical representation
Saturday, 28 November 2020 27
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
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
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
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
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
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
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
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
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
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
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
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
NULL Pointer in relational expressions
• if(pi)
• if(!pi)
• if(pi == NULL)
• if(pi != NULL)
Saturday, 28 November 2020 40
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
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
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
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
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
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
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
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
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
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
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
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
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
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
Variations of the Structure Declaration
Saturday, 28 November 2020 55
Variations of the Structure Declaration
Saturday, 28 November 2020 56
Variations of the Structure Declaration
Saturday, 28 November 2020 57
Variations of the Structure Declaration
Saturday, 28 November 2020 58
Variations of the Structure Declaration
Saturday, 28 November 2020 59
Variations of the Structure Declaration
Saturday, 28 November 2020 60
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
Cont’d…
printf(“%dn”,cse.rollno);
Printf(“%sn”,cse.name);
printf(“%fn”,cse.average);
To read the values from user during execution of a program, we use
format specifiers and access the members of structure.
Eg) scanf(“%d”,&cse.rollno);
scanf(“%s”,cse.name);
scanf(“%f”,&cse.average);
Saturday, 28 November 2020 62
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
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
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
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
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
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
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
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
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
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
Contd…
• After the statements:
item1.link = &item2;
item2.link = &item3;
The list becomes:
Saturday, 28 November 2020 73
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
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
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
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
Cont’d…
Output:
Marks=100
Grade=A
Percentage=99.5
C program to show how union behaves:
#include<stdio.h>
int main()
typedef union
{
int marks;
char grade;
float percentage;
} student;
Saturday, 28 November 2020 78
Cont’d…
student cse;
cse.marks=100;
printf(“marks=%dn”, cse.marks);
cse.grade=‘A’
printf(“grade=%cn”, cse.grade);
cse.percentage=99.5;
printf(“percentage=%fn”, cse.percentage);
return 0;
}
Output:
Marks=100
Grade=A
Percentage=99.5
Saturday, 28 November 2020 79
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
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
Example: Union Declaration:
#include <stdio.h>
#include <string.h>
union student {
char name[20];
char subject[20];
float percentage;
};
Saturday, 28 November 2020 82
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
Contd …
printf("Union record1 values examplen");
printf(" Name : %s n", record1.name);
printf(" Subject : %s n", record1.subject);
printf(" Percentage : %f nn", record1.percentage);
// assigning values to record2 union variable
printf("Union record2 values examplen");
strcpy(record2.name, "Mani");
printf(" Name : %s n", record2.name);
strcpy(record2.subject, "Physics");
printf(" Subject : %s n", record2.subject);
record2.percentage = 99.50;
printf(" Percentage : %f n", record2.percentage);
return 0;
}
Saturday, 28 November 2020 84
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
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
Cont’d…
p=(int*)malloc(n*sizeof(int));
if(p==NULL)
printf(“No memory allocatedn”);
printf(“nEnter array elements:”);
for(i=0;i<n; i++)
{
scanf(“%d”, p+i);
sum+=*(p+i);
}
printf(“Sum=%dn”,sum);
free(p);
return 0;
}
Saturday, 28 November 2020 87
Cont’d…
Output:
Enter the number of elements:5
Enter array elements:10 20 30 40 50
Sum:150
Saturday, 28 November 2020 88
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
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
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
Cont’d…
Saturday, 28 November 2020 92
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
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
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
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
Two Dimensional Arrays:
•First, create an array of pointers of size r.
•Dynamically allocate memory for every row.
Saturday, 28 November 2020 97
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
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
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.
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:
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
Deletion at the End of the List A
•If n > 0, then simply decrement the the n value:
n--;
Saturday, 28 November 2020 103
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
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
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
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
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:
Array Operations: Sorting: Bubble Sort:
• Assume that the initial array contains the Seven elements as shown below:
Saturday, 28 November 2020 109
58 42 42 42 42 42 42 42 42 42 42 42 42
42 58 58 58 58 58 58 58 58 58 58 58 58
61 61 61 61 61 61 61 61 61 61 56 56 56
74 74 74 74 56 56 56 56 56 56 61 37 37
26 26 26 56 74 37 37 37 37 37 37 13 13
37 37 37 37 37 74 13 13 13 13 13 61 61
13 13 13 13 13 13 74 74 74 74 74 74 74
Pass 1 Pass 2
Array Operations: Sorting: Bubble Sort:
• Assume that the initial array contains the Seven elements as shown below:
Saturday, 28 November 2020 110
42 42 42 42 42 42 42 42 42
58 58 56 56 56 56 56 37 37
56 56 58 37 37 37 37 56 13
37 37 37 58 13 13 13 13 56
13 13 13 13 58 58 58 58 58
61 61 61 61 61 61 61 61 61
74 74 74 74 74 74 74 74 74
Pass 3 Pass 4
Array Operations: Sorting: Bubble Sort:
• Assume that the initial array contains the Seven elements as shown below:
Saturday, 28 November 2020 111
42 37 37 37 13 13
37 42 13 13 37 37
13 13 42 42 42 42
56 56 56 56 56 56
58 58 58 58 58 58
61 61 61 61 61 61
74 74 74 74 74 74
Pass 5 Pass 6 Sorted Array
Array Operations: Searching:
•Linear Search
•Binary Search
Saturday, 28 November 2020 112
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
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:
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
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
Representation of Two dimensional
array in Memory:
(i) Column Major representation and
(ii) Row Major representations
Saturday, 28 November 2020 117
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
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
• 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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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>
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
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
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
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
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
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
Example: Consider the following Sparse Matrix:
Col 0 Col 1 Col 2 Col 3 Col 4 Col 5
| ----- ---|
Row0 | 15 0 0 22 0 –15 |
| |
Row1 | 0 11 3 0 0 0 |
| |
Row2 | 0 0 0 –6 0 0 |
| |
Row3 | 0 0 0 0 0 0 |
| |
Row4 | 91 0 0 0 0 0 |
| |
Row5 | 0 0 28 0 0 0 |
|----- ----|
Saturday, 28 November 2020 145
Triplet Representation of the Sparse Matrix:
•Each element is characterized by <row, col, value>.
Saturday, 28 November 2020 146
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
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
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
Represent the above sparse matrix in Triplet form.
a[] Row # Col # Value
a[0] 6 6 8
a[1] 0 0 15
a[2] 0 3 22
a[3] 0 5 -15
a[4] 1 1 11
a[5] 1 2 3
a[6] 2 3 -6
a[7] 4 0 91
a[8] 5 2 28
Saturday, 28 November 2020 150
Transpose of the Sparse Matrix is:
Saturday, 28 November 2020 151
Col 0 Col 1 Col 2 Col 3 Col 4 Col 5
Row 0 15 6 0 0 91 0
Row 1 0 11 0 0 0 0
Row 2 0 3 0 0 0 28
Row 3 22 0 –6 0 0 0
Row 4 0 0 0 0 0 0
Row 5 –15 0 0 0 0 0
Triplex Representation of Transpose
b[] Row # Col # Value
b[0] 6 6 8
b[1] 0 0 15
b[2] 0 4 91
b[3] 1 1 11
b[4] 2 1 3
b[5] 2 5 28
b[6] 3 0 22
b[7] 3 2 -6
b[8] 5 0 -15
Saturday, 28 November 2020 152
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
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)
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;
}
}
}
Cont’d…
[0] [1] [2] [3] [4] [5]
rowterms = 2 1 2 2 0 1
startingpos = 1 3 4 6 8 8
Saturday, 28 November 2020 156
Cont’d…
b[] Row # Col # Value
b[0] 6 6 8
b[1] 0 0 15
b[2] 0 4 91
b[3] 1 1 11
b[4] 2 1 3
b[5] 2 5 28
b[6] 3 0 22
b[7] 3 2 -6
b[8] 5 0 -15
Saturday, 28 November 2020 157

More Related Content

What's hot

Query Processing and Optimisation - Lecture 10 - Introduction to Databases (1...
Query Processing and Optimisation - Lecture 10 - Introduction to Databases (1...Query Processing and Optimisation - Lecture 10 - Introduction to Databases (1...
Query Processing and Optimisation - Lecture 10 - Introduction to Databases (1...Beat Signer
 
DATA STRUCTURE AND ALGORITHMS
DATA STRUCTURE AND ALGORITHMS DATA STRUCTURE AND ALGORITHMS
DATA STRUCTURE AND ALGORITHMS Adams Sidibe
 
Introduction to Data Mining
Introduction to Data MiningIntroduction to Data Mining
Introduction to Data Miningsnoreen
 
Furnish an Index Using the Works of Tree Structures
Furnish an Index Using the Works of Tree StructuresFurnish an Index Using the Works of Tree Structures
Furnish an Index Using the Works of Tree Structuresijceronline
 
UNIT III NON LINEAR DATA STRUCTURES – TREES
UNIT III 	NON LINEAR DATA STRUCTURES – TREESUNIT III 	NON LINEAR DATA STRUCTURES – TREES
UNIT III NON LINEAR DATA STRUCTURES – TREESKathirvel Ayyaswamy
 
K Means Clustering Algorithm for Partitioning Data Sets Evaluated From Horizo...
K Means Clustering Algorithm for Partitioning Data Sets Evaluated From Horizo...K Means Clustering Algorithm for Partitioning Data Sets Evaluated From Horizo...
K Means Clustering Algorithm for Partitioning Data Sets Evaluated From Horizo...IOSR Journals
 
Network topology
Network topologyNetwork topology
Network topologytoramamohan
 
Multiplication of matrices and its application in biology
Multiplication of matrices and its application in biologyMultiplication of matrices and its application in biology
Multiplication of matrices and its application in biologynayanika bhalla
 
Data Mining: Concepts and Techniques (3rd ed.) - Chapter 3 preprocessing
Data Mining:  Concepts and Techniques (3rd ed.)- Chapter 3 preprocessingData Mining:  Concepts and Techniques (3rd ed.)- Chapter 3 preprocessing
Data Mining: Concepts and Techniques (3rd ed.) - Chapter 3 preprocessingSalah Amean
 
Data preprocessing
Data preprocessingData preprocessing
Data preprocessingkayathri02
 
Application of matrices in Daily life
Application of matrices in Daily lifeApplication of matrices in Daily life
Application of matrices in Daily lifeshubham mishra
 
Matrices in computer applications
Matrices in computer applicationsMatrices in computer applications
Matrices in computer applicationsRayyan777
 
1.7 data reduction
1.7 data reduction1.7 data reduction
1.7 data reductionKrish_ver2
 
Noise Driven Encryption Algorithm (NDEA) Version-1
Noise Driven Encryption Algorithm (NDEA) Version-1Noise Driven Encryption Algorithm (NDEA) Version-1
Noise Driven Encryption Algorithm (NDEA) Version-1AM Publications
 

What's hot (19)

Query Processing and Optimisation - Lecture 10 - Introduction to Databases (1...
Query Processing and Optimisation - Lecture 10 - Introduction to Databases (1...Query Processing and Optimisation - Lecture 10 - Introduction to Databases (1...
Query Processing and Optimisation - Lecture 10 - Introduction to Databases (1...
 
DATA STRUCTURE AND ALGORITHMS
DATA STRUCTURE AND ALGORITHMS DATA STRUCTURE AND ALGORITHMS
DATA STRUCTURE AND ALGORITHMS
 
Introduction to Data Mining
Introduction to Data MiningIntroduction to Data Mining
Introduction to Data Mining
 
Furnish an Index Using the Works of Tree Structures
Furnish an Index Using the Works of Tree StructuresFurnish an Index Using the Works of Tree Structures
Furnish an Index Using the Works of Tree Structures
 
Data Structures
Data StructuresData Structures
Data Structures
 
Data cube
Data cubeData cube
Data cube
 
UNIT III NON LINEAR DATA STRUCTURES – TREES
UNIT III 	NON LINEAR DATA STRUCTURES – TREESUNIT III 	NON LINEAR DATA STRUCTURES – TREES
UNIT III NON LINEAR DATA STRUCTURES – TREES
 
K Means Clustering Algorithm for Partitioning Data Sets Evaluated From Horizo...
K Means Clustering Algorithm for Partitioning Data Sets Evaluated From Horizo...K Means Clustering Algorithm for Partitioning Data Sets Evaluated From Horizo...
K Means Clustering Algorithm for Partitioning Data Sets Evaluated From Horizo...
 
Unit 4.1 (tree)
Unit 4.1 (tree)Unit 4.1 (tree)
Unit 4.1 (tree)
 
Network topology
Network topologyNetwork topology
Network topology
 
Multiplication of matrices and its application in biology
Multiplication of matrices and its application in biologyMultiplication of matrices and its application in biology
Multiplication of matrices and its application in biology
 
Data Mining: Concepts and Techniques (3rd ed.) - Chapter 3 preprocessing
Data Mining:  Concepts and Techniques (3rd ed.)- Chapter 3 preprocessingData Mining:  Concepts and Techniques (3rd ed.)- Chapter 3 preprocessing
Data Mining: Concepts and Techniques (3rd ed.) - Chapter 3 preprocessing
 
Application of matrices in real life
Application of matrices in real lifeApplication of matrices in real life
Application of matrices in real life
 
Data preprocessing
Data preprocessingData preprocessing
Data preprocessing
 
Application of matrices in Daily life
Application of matrices in Daily lifeApplication of matrices in Daily life
Application of matrices in Daily life
 
Matrices in computer applications
Matrices in computer applicationsMatrices in computer applications
Matrices in computer applications
 
1.7 data reduction
1.7 data reduction1.7 data reduction
1.7 data reduction
 
Noise Driven Encryption Algorithm (NDEA) Version-1
Noise Driven Encryption Algorithm (NDEA) Version-1Noise Driven Encryption Algorithm (NDEA) Version-1
Noise Driven Encryption Algorithm (NDEA) Version-1
 
Data Mining: Data processing
Data Mining: Data processingData Mining: Data processing
Data Mining: Data processing
 

Similar to Dsa module 1 ppt

DSA_Module 1-PPT for engineering students
DSA_Module 1-PPT for engineering studentsDSA_Module 1-PPT for engineering students
DSA_Module 1-PPT for engineering studentsriotsush12
 
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_II_08-08-2022_D...
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_II_08-08-2022_D...FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_II_08-08-2022_D...
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_II_08-08-2022_D...AntareepMajumder
 
Introduction of data science
Introduction of data scienceIntroduction of data science
Introduction of data scienceTanujaSomvanshi1
 
CHAPTER-1- Introduction to data structure.pptx
CHAPTER-1- Introduction to data structure.pptxCHAPTER-1- Introduction to data structure.pptx
CHAPTER-1- Introduction to data structure.pptxOnkarModhave
 
Iare ds lecture_notes_2
Iare ds lecture_notes_2Iare ds lecture_notes_2
Iare ds lecture_notes_2RajSingh734307
 
Introduction to DS.pptx
Introduction to DS.pptxIntroduction to DS.pptx
Introduction to DS.pptxOnkarModhave
 
Introduction to Datamining Concept and Techniques
Introduction to Datamining Concept and TechniquesIntroduction to Datamining Concept and Techniques
Introduction to Datamining Concept and TechniquesSơn Còm Nhom
 
2.02.Data_structures_and_algorithms (1).pptx
2.02.Data_structures_and_algorithms (1).pptx2.02.Data_structures_and_algorithms (1).pptx
2.02.Data_structures_and_algorithms (1).pptxDrBashirMSaad
 
II B.Sc IT DATA STRUCTURES.pptx
II B.Sc IT DATA STRUCTURES.pptxII B.Sc IT DATA STRUCTURES.pptx
II B.Sc IT DATA STRUCTURES.pptxsabithabanu83
 
Clustering of Big Data Using Different Data-Mining Techniques
Clustering of Big Data Using Different Data-Mining TechniquesClustering of Big Data Using Different Data-Mining Techniques
Clustering of Big Data Using Different Data-Mining TechniquesIRJET Journal
 

Similar to Dsa module 1 ppt (20)

DSA_Module 1-PPT for engineering students
DSA_Module 1-PPT for engineering studentsDSA_Module 1-PPT for engineering students
DSA_Module 1-PPT for engineering students
 
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_II_08-08-2022_D...
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_II_08-08-2022_D...FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_II_08-08-2022_D...
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_II_08-08-2022_D...
 
UNIT 3 PPT.ppt
UNIT 3 PPT.pptUNIT 3 PPT.ppt
UNIT 3 PPT.ppt
 
dsa.pptx
dsa.pptxdsa.pptx
dsa.pptx
 
Data Structures & Algorithms
Data Structures & AlgorithmsData Structures & Algorithms
Data Structures & Algorithms
 
Introduction of data science
Introduction of data scienceIntroduction of data science
Introduction of data science
 
CHAPTER-1- Introduction to data structure.pptx
CHAPTER-1- Introduction to data structure.pptxCHAPTER-1- Introduction to data structure.pptx
CHAPTER-1- Introduction to data structure.pptx
 
Iare ds lecture_notes_2
Iare ds lecture_notes_2Iare ds lecture_notes_2
Iare ds lecture_notes_2
 
algo 1.ppt
algo 1.pptalgo 1.ppt
algo 1.ppt
 
Introduction to DS.pptx
Introduction to DS.pptxIntroduction to DS.pptx
Introduction to DS.pptx
 
Introduction to Datamining Concept and Techniques
Introduction to Datamining Concept and TechniquesIntroduction to Datamining Concept and Techniques
Introduction to Datamining Concept and Techniques
 
dsa.ppt
dsa.pptdsa.ppt
dsa.ppt
 
dsa.ppt
dsa.pptdsa.ppt
dsa.ppt
 
dsa (1).ppt
dsa (1).pptdsa (1).ppt
dsa (1).ppt
 
2.02.Data_structures_and_algorithms (1).pptx
2.02.Data_structures_and_algorithms (1).pptx2.02.Data_structures_and_algorithms (1).pptx
2.02.Data_structures_and_algorithms (1).pptx
 
II B.Sc IT DATA STRUCTURES.pptx
II B.Sc IT DATA STRUCTURES.pptxII B.Sc IT DATA STRUCTURES.pptx
II B.Sc IT DATA STRUCTURES.pptx
 
Clustering of Big Data Using Different Data-Mining Techniques
Clustering of Big Data Using Different Data-Mining TechniquesClustering of Big Data Using Different Data-Mining Techniques
Clustering of Big Data Using Different Data-Mining Techniques
 
Intro_2.ppt
Intro_2.pptIntro_2.ppt
Intro_2.ppt
 
Intro.ppt
Intro.pptIntro.ppt
Intro.ppt
 
Intro.ppt
Intro.pptIntro.ppt
Intro.ppt
 

Recently uploaded

IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)dollysharma2066
 
Introduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxIntroduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxvipinkmenon1
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 

Recently uploaded (20)

IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
 
Introduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxIntroduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptx
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 

Dsa module 1 ppt

  • 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
  • 12. DATA STRUCTURE OPERATIONS: •Traversing •Searching •Inserting •Deleting The following two operations, which are used in special situations: •Sorting •Merging Saturday, 28 November 2020 12
  • 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
  • 20. Contd… Saturday, 28 November 2020 20 0 10 1 20 2 30 3 40 . … . … 65535 … dataAddress m/m locations
  • 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
  • 40. NULL Pointer in relational expressions • if(pi) • if(!pi) • if(pi == NULL) • if(pi != NULL) Saturday, 28 November 2020 40
  • 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
  • 62. Cont’d… printf(“%dn”,cse.rollno); Printf(“%sn”,cse.name); printf(“%fn”,cse.average); To read the values from user during execution of a program, we use format specifiers and access the members of structure. Eg) scanf(“%d”,&cse.rollno); scanf(“%s”,cse.name); scanf(“%f”,&cse.average); Saturday, 28 November 2020 62
  • 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
  • 78. Cont’d… Output: Marks=100 Grade=A Percentage=99.5 C program to show how union behaves: #include<stdio.h> int main() typedef union { int marks; char grade; float percentage; } student; Saturday, 28 November 2020 78
  • 79. Cont’d… student cse; cse.marks=100; printf(“marks=%dn”, cse.marks); cse.grade=‘A’ printf(“grade=%cn”, cse.grade); cse.percentage=99.5; printf(“percentage=%fn”, cse.percentage); return 0; } Output: Marks=100 Grade=A Percentage=99.5 Saturday, 28 November 2020 79
  • 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
  • 84. Contd … printf("Union record1 values examplen"); printf(" Name : %s n", record1.name); printf(" Subject : %s n", record1.subject); printf(" Percentage : %f nn", record1.percentage); // assigning values to record2 union variable printf("Union record2 values examplen"); strcpy(record2.name, "Mani"); printf(" Name : %s n", record2.name); strcpy(record2.subject, "Physics"); printf(" Subject : %s n", record2.subject); record2.percentage = 99.50; printf(" Percentage : %f n", record2.percentage); return 0; } Saturday, 28 November 2020 84
  • 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
  • 87. Cont’d… p=(int*)malloc(n*sizeof(int)); if(p==NULL) printf(“No memory allocatedn”); printf(“nEnter array elements:”); for(i=0;i<n; i++) { scanf(“%d”, p+i); sum+=*(p+i); } printf(“Sum=%dn”,sum); free(p); return 0; } Saturday, 28 November 2020 87
  • 88. Cont’d… Output: Enter the number of elements:5 Enter array elements:10 20 30 40 50 Sum:150 Saturday, 28 November 2020 88
  • 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:
  • 109. Array Operations: Sorting: Bubble Sort: • Assume that the initial array contains the Seven elements as shown below: Saturday, 28 November 2020 109 58 42 42 42 42 42 42 42 42 42 42 42 42 42 58 58 58 58 58 58 58 58 58 58 58 58 61 61 61 61 61 61 61 61 61 61 56 56 56 74 74 74 74 56 56 56 56 56 56 61 37 37 26 26 26 56 74 37 37 37 37 37 37 13 13 37 37 37 37 37 74 13 13 13 13 13 61 61 13 13 13 13 13 13 74 74 74 74 74 74 74 Pass 1 Pass 2
  • 110. Array Operations: Sorting: Bubble Sort: • Assume that the initial array contains the Seven elements as shown below: Saturday, 28 November 2020 110 42 42 42 42 42 42 42 42 42 58 58 56 56 56 56 56 37 37 56 56 58 37 37 37 37 56 13 37 37 37 58 13 13 13 13 56 13 13 13 13 58 58 58 58 58 61 61 61 61 61 61 61 61 61 74 74 74 74 74 74 74 74 74 Pass 3 Pass 4
  • 111. Array Operations: Sorting: Bubble Sort: • Assume that the initial array contains the Seven elements as shown below: Saturday, 28 November 2020 111 42 37 37 37 13 13 37 42 13 13 37 37 13 13 42 42 42 42 56 56 56 56 56 56 58 58 58 58 58 58 61 61 61 61 61 61 74 74 74 74 74 74 Pass 5 Pass 6 Sorted Array
  • 112. Array Operations: Searching: •Linear Search •Binary Search Saturday, 28 November 2020 112
  • 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
  • 145. Example: Consider the following Sparse Matrix: Col 0 Col 1 Col 2 Col 3 Col 4 Col 5 | ----- ---| Row0 | 15 0 0 22 0 –15 | | | Row1 | 0 11 3 0 0 0 | | | Row2 | 0 0 0 –6 0 0 | | | Row3 | 0 0 0 0 0 0 | | | Row4 | 91 0 0 0 0 0 | | | Row5 | 0 0 28 0 0 0 | |----- ----| Saturday, 28 November 2020 145
  • 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
  • 150. Represent the above sparse matrix in Triplet form. a[] Row # Col # Value a[0] 6 6 8 a[1] 0 0 15 a[2] 0 3 22 a[3] 0 5 -15 a[4] 1 1 11 a[5] 1 2 3 a[6] 2 3 -6 a[7] 4 0 91 a[8] 5 2 28 Saturday, 28 November 2020 150
  • 151. Transpose of the Sparse Matrix is: Saturday, 28 November 2020 151 Col 0 Col 1 Col 2 Col 3 Col 4 Col 5 Row 0 15 6 0 0 91 0 Row 1 0 11 0 0 0 0 Row 2 0 3 0 0 0 28 Row 3 22 0 –6 0 0 0 Row 4 0 0 0 0 0 0 Row 5 –15 0 0 0 0 0
  • 152. Triplex Representation of Transpose b[] Row # Col # Value b[0] 6 6 8 b[1] 0 0 15 b[2] 0 4 91 b[3] 1 1 11 b[4] 2 1 3 b[5] 2 5 28 b[6] 3 0 22 b[7] 3 2 -6 b[8] 5 0 -15 Saturday, 28 November 2020 152
  • 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; } } }
  • 156. Cont’d… [0] [1] [2] [3] [4] [5] rowterms = 2 1 2 2 0 1 startingpos = 1 3 4 6 8 8 Saturday, 28 November 2020 156
  • 157. Cont’d… b[] Row # Col # Value b[0] 6 6 8 b[1] 0 0 15 b[2] 0 4 91 b[3] 1 1 11 b[4] 2 1 3 b[5] 2 5 28 b[6] 3 0 22 b[7] 3 2 -6 b[8] 5 0 -15 Saturday, 28 November 2020 157