Professional Documents
Culture Documents
DS 18CS32 Module 1
DS 18CS32 Module 1
Definition:
Primitive data structures are the fundamental data types which are supported
by a programming language.
The term ‘data type’, ‘basic data type’ and ‘primitive data type’ are often used
interchangeably.
Non-primitive Data Structures:
Non-primitive data structures are those data structures which are created
In Non-linear data structures, the elements of a data structure are not stored
in a sequential order.
Character Stacks
Queues
Boolean
Trees
Graphs
Boolean: It is used to store true or false. Every non-zero value corresponds to true and
0 value corresponds to false and it is denoted by keyword ‘bool’.
Stacks: A stack is a linear data structure in which insertion and deletion of elements
are done at only one end, which is known as the top of the stack. Stack is also called as
Last-In, First-Out (LIFO).
Queues: A queue is a linear data structure in which the element that is inserted first is
the first one to be taken out. The elements in a queue are added at one end called the
rear and removed from the other end called the front. Queue is also called as First-In,
First-Out (FIFO).
Linked Lists: A linked list is a set of dynamically allocated nodes, arranged in such a
way that each node contains one value and one pointer. The pointer always points to
the next member of the list. If the pointer is NULL, then it is the last node in the list.
Non-primitive Data Structures (Contd…):
arranged in a hierarchical order. One of the nodes is designated as the root node and
the remaining nodes can be partitioned into disjoint sets such that each set is a sub-
structures are
Traversing
Searching
Inserting
Deleting
Sorting
Merging
Traversing: It means to access each data item exactly once so that it can be
processed.
Searching: It is used to find the location of one or more data items that satisfy
the given constraint. Such a data item may or may not be present in the given
Example: To find the names of all the students who secured 100 marks in
subject.
Inserting: It is used to add new data items to the given list of data items.
Example: To add the details of a new student who has recently joined the
course.
Deleting: It means to remove (delete) a particular data item from the given
Example: To delete/remove the name of a student who has left the course.
Sorting: Data items can be arranged in some order like ascending order or
Merging: Combing the records in two different sorted files into single sorted
file.
Today’s Class Assignment Questions.
Note: Write these assignment questions in 200 pages RULED long note book.
operations.
THANK YOU
|| JAI SRI GURUDEV ||
SRI ADICHUNCHANAGIRI SHIKSHANA TRUST ®
Functions
Pointer
Pointer is a variable that holds the address of another variable.
The two most important operators used with the pointer type are:
Address Operator (&)
Dereferencing (or Indirection) Operator (*)
Declaration of Pointer Variable:
Syntax : data_type *ptr_variable_name;
Example : int *ptr;
Initialization of Pointer Variable:
Syntax : ptr_variable_name = &variable_name;
Example:
int a = 10; a Variable Name
int *ptr;
10 Value
ptr = &a;
*ptr = a; 2010 Memory Address
Note: ptr holds the address of variable ‘a’.
int a = 10;
int *ptr;
Output
ptr = &a;
10
printf(“%d\n”,a);
printf(“%d\n”,&a); 2010
printf(“%d\n”,ptr); 2010
printf(“%d\n”,*ptr); 10
}
Uses of Pointers
To implement data structures like arrays, linked lists, stacks, queues, trees and
graphs.
Pointer to Pointer
Pointer is a variable that holds the address of another variable.
Pointer storing the address of another pointer variable . That is one pointer
variable pointing to another pointer variable.
Declaration of Pointer-to-Pointer Variable:
Syntax : data_type **ptr_variable_name;
Example : int **ptr;
Initialization of Pointer-to-Pointer Variable:
Syntax : ptr_variable_name = &another_ptr_variable_name;
Example:
int a = 10; ptr2 ptr1 a Variable Name
int *ptr1,**ptr2; 3000 2000 10 Value
ptr2 holds the address of pointer variable ‘ptr1’. 4000 3000 2000 Memory Address
*ptr2 holds the value of pointer variable ‘ptr1’ (value stored at ptr1 is address of ‘a’).
**ptr2 holds the value of variable ‘a’.
ptr1 holds the address of variable ‘a’. That is, ptr1 = 2000
*ptr1 holds the value of variable ‘a’.
Means *ptr1 = value(address(a)).
*ptr1 = value(2000)
That is, *ptr1 = 10
ptr2 holds the address of pointer variable ‘ptr1’. That is, ptr2 = 3000
*ptr2 holds the value of pointer variable ‘ptr1’.
Means *ptr2 = value(address(ptr1)).
*ptr2 = value(3000)
That is, *ptr2 = 2000
**ptr2 holds the value of variable ‘a’.
Means **ptr2 = value(value(address(ptr1))).
**ptr2 = value(value(3000))
**ptr2 = value(2000)
That is, **ptr2 = 10 (value stored in variable ‘a’)
NULL Pointer
A NULL pointer is a pointer that does not point to any memory location. It
NULL pointer.
Example:
main()
}
Uses of NULL Pointer
1. It is used to initialize a pointer when that pointer is not assigned any valid
memory address yet.
Example:
main()
{
int *ptr = NULL;
}
2. Useful for handling errors when using malloc() function.
Example:
main()
{
int *ptr;
ptr = (int*)malloc(2*sizeof(int));
if(ptr==NULL)
printf(“Memory could not be allocated”);
else
printf(“Memory allocated successfully”);
}
Facts about NULL Pointer
1. The value of NULL is 0. We can either use NULL or 0 but this 0 is written in
context of pointers and is not equivalent to the integer 0.
Example:
main()
{
int *ptr = NULL;
printf(“%d”, ptr);
}
Output: 0
2. Size of NULL pointer depends upon the platform and is similar to the size of
the normal pointers.
Example:
main()
{
printf(“%d”,sizeof(NULL));
}
Output: 8
Best Practices:
Example:
main()
int *ptr;
ptr = (int*)malloc(2*sizeof(int));
. . . .
. . . .
free(ptr);
}
THANK YOU
|| JAI SRI GURUDEV ||
SRI ADICHUNCHANAGIRI SHIKSHANA TRUST ®
Functions
Static Memory Allocation:
Example:
#include<stdio.h>
Here, the memory is
main()
allocated at compile
{
time and size is
int arr[5] = {1,2,3,4,5}; fixed.
}
Problems Faced in Static Memory Allocation:
If you are allocating memory for an array during compile time then you
have to fix the size at the time of declaration. Size is fixed and user
If the values stored by the user in the array at run time is less than the
If the values stored by the user in the array at run time is more than the
Memory Allocation.
pointers.
Dynamic Memory Allocation:
malloc()
Built-in Functions and these
calloc()
functions defined under “Stdlib.h”
realloc()
header file.
free()
Dynamic Memory Allocation using malloc():
Syntax:
Example: 2001 4
B
2002 Y
int *ptr; Memory T
2003
E
ptr = (int* )malloc(4); 2004 S
heap and the address of the first byte is stored in the pointer ptr.
Example Program:
Output 1:
#include<stdio.h> Enter an number
#include<stdlib.h> 100
Entered number is 100
main()
{
Output 2:
int *ptr; Memory not allocated
ptr = (int*)malloc(sizeof(int));
if(ptr==NULL) Here, assume size of integer is 4 bytes
{ 2001 100
printf(“Memory not allocated\n”); 4
exit(0);
2002 B
}
Y
printf(“Enter an number”);
T
scanf(“%d”,ptr); 2003
printf(“Entered number is %d”,*ptr); E
} S
2004
Example Program: Output 1:
#include<stdio.h> Enter the number of Integers
#include<stdlib.h> 3
main() Enter an integer: 10
{ Enter an integer: 20
int i,n, *ptr; Enter an integer: 30
printf(“Enter the number of Integers\n”); 10 20 30
scanf(“%d”,&n); Output 2:
ptr = (int* )malloc(n*sizeof(int)); Memory not allocated
if(ptr==NULL)
Here, assume size of integer is 2 bytes
{
printf(“Memory not allocated\n”); 2001 10
exit(0);
6
} 2002
for(i=0;i<n;i++) B
{ 2003 20 Y
printf(“Enter an integer: ”);
scanf(“%d”,ptr+i); 2004 T
} E
for(i=0;i<n;i++) 2005 30
S
printf(“%d\t”,*(ptr+i));
2006
}
THANK YOU
|| JAI SRI GURUDEV ||
SRI ADICHUNCHANAGIRI SHIKSHANA TRUST ®
0 0 0 0 0
2001 2005 2009 2013 2017
} 4 Bytes
Example Program: Output 1:
#include<stdio.h> Enter the number of Integers
#include<stdlib.h> 3
main() Enter an integer: 10
{ Enter an integer: 20
int i,n, *ptr; Enter an integer: 30
printf(“Enter the number of Integers\n”); 10 20 30
scanf(“%d”,&n); Output 2:
ptr = (int* )calloc(n,sizeof(int)); Memory not allocated
if(ptr==NULL)
{
printf(“Memory not allocated\n”); Here, assume size of integer is 2 bytes
exit(0); Block 1 Block 2 Block 3
}
for(i=0;i<n;i++) 0 0 0
{ 10 20 30
printf(“Enter an integer: ”);
scanf(“%d”,ptr+i); 2001 2003 2005
} 2 Bytes 2 Bytes 2 Bytes
for(i=0;i<n;i++)
printf(“%d\t”,*(ptr+i)); Total Memory Allocated = 6 Bytes
}
Dynamic Memory Allocation using realloc():
realloc() is a built-in function declared in the header file <stdlib.h>.
realloc() is the short name for “re-allocation” and is used to
change the size of the memory block without losing the old data.
Syntax:
(void* )realloc(void *ptr, size_t newsize);
Pointer to the Previously
Allocated Memory New Size
In other words, if the memory previously allocated with the help of malloc() or
calloc() is insufficient, realloc() can be used to dynamically re-allocate
memory.
re-allocation of memory maintains the already present value and new blocks.
If space is insufficient, allocation fails and returns a NULL pointer.
size_t is defined in <stdlib.h> as unsigned int.
Example: Assume size of ‘int’ data type is 4 bytes.
int *ptr;
ptr = (int* )malloc(size(int));
In the above example, malloc() allocates 4 bytes of memory in the heap
and the address of the first byte is stored in the pointer ptr.
ptr
2001 2004
4 Bytes
ptr = (int* )realloc(ptr, 2*sizeof(int));
In the above example, realloc() allocates (2*sizeof(int)) 8 bytes of
memory in the heap and the address of the first byte is stored in the
pointer ptr.
ptr
2001 2008
8 Bytes
This function (realloc()) moves the contents of the old block to new
block and the data of the old block is not lost.
We may lose the data when the new size is smaller than the old size.
Newly allocated bytes are uninitialized.
Example Program: printf(“Enter two more integers\n”);
#include<stdio.h> for(i=2;i<4;i++)
#include<stdlib.h> {
main() scanf(“%d”,ptr+i);
{ }
int i,*ptr; //Printing the integers which are stored
ptr = (int*)malloc(2*sizeof(int)); //in the memory
if(ptr==NULL) printf(“The stored integer nos are\n”);
{ for(i=0;i<4;i++)
printf(“Memory not allocated\n”); {
exit(0); printf(“%d\t”,*(ptr+i));
} }
printf(“Enter two integers\n”); } // Closing of main()
for(i=0;i<2;i++)
{
scanf(“%d”,ptr+i); Output:
} Enter two integers
//Suppose I want store 2 more integers 100
//then allocate memory for 2 more integers
200
ptr = (int*)realloc(ptr,4*sizeof(int));
Enter two more integers
if(ptr==NULL)
300
{
printf(“Memory not allocated\n”);
400
exit(0); The stored integer nos are
} 100 200 300 400
Releasing Dynamically Allocated Memory using free():
memory in heap.
using the memory. The space remains there and cannot be used.
Syntax:
free(pointer_variable_name);
Example: Assume size of ‘int’ data type is 2 bytes.
main()
{
int *ptr;
ptr = (int*)malloc(4*sizeof(int));
. . . .
. . . .
free(ptr);
ptr = NULL;
}
In the above example, malloc() allocates 8 bytes of memory in the
heap and the address of the first byte is stored in the pointer ptr.
Example Program:
#include<stdio.h>
#include<stdlib.h>
main()
{
int i,n, *ptr; Output 1:
printf(“Enter the number of Integers\n”);
scanf(“%d”,&n); Enter the number of Integers
ptr = (int* )malloc(n*sizeof(int)); 3
if(ptr==NULL)
Enter an integer: 10
{
printf(“Memory not allocated\n”); Enter an integer: 20
exit(0);
Enter an integer: 30
}
for(i=0;i<n;i++) The stored integer nos are
{ 10 20 30
printf(“Enter an integer: ”);
scanf(“%d”,ptr+i); Output 2:
} Memory not allocated
printf(“The stored integer nos are\n”);
for(i=0;i<n;i++)
printf(“%d\t”,*(ptr+i));
free(ptr);
ptr = NULL;
}
THANK YOU
|| JAI SRI GURUDEV ||
SRI ADICHUNCHANAGIRI SHIKSHANA TRUST ®
Example:
#include<stdio.h>
Output:
struct
arun
{
20
char name[10];
int age; 35000.000000
float salary;
}emp={“arun”,20,35000};
main()
{
printf(“%s\n%d\n%f\n”,emp.name,emp.age,emp.salary);
}
Initialization of Structure Members:
Example:
#include<stdio.h>
Output:
struct employee
arun
{
20
char name[10];
int age; 35000.000000
float salary;
};
main()
{
struct employee emp = {“arun”,20,35000};
printf(“%s\n%d\n%f\n”,emp.name,emp.age,emp.salary);
}
Example: Output:
#include<stdio.h> Enter an employee name
struct arun
{ Enter an employee age
20
char name[10];
Enter an employee salary
int age;
35000
float salary; Employee details are
}emp; arun
20
main() 35000.000000
{
printf(“Enter an employee name\n”);
scanf(“%s”,emp.name);
printf(“Enter an employee age\n”);
scanf(“%d”,&emp.age);
printf(“Enter an employee salary\n”);
scanf(“%f”,&emp.salary);
printf(“Employee details are\n”);
printf(“%s\n%d\n%f\n”,emp.name,emp.age,emp.salary);
}
Example:
Output:
#include<stdio.h> Employee1 details are
arun
struct 20
35000.000000
{
Employee2 details are
char name[10]; varun
22
int age; 40000.000000
float salary;
}emp1= {“arun”,20,35000},emp2={“varun”,22,40000};
main()
{
printf(“Employee1 details are\n”);
printf(“%s\n%d\n%f\n”,emp1.name,emp1.age,emp1.salary);
printf(“Employee2 details are\n”);
printf(“%s\n%d\n%f\n”,emp2.name,emp2.age,emp2.salary);
}
Example:
#include<stdio.h>
struct employee Output:
{ Employee1 details are
char name[10];
int age; arun
float salary; 20
};
35000.000000
main() Employee2 details are
{
struct employee emp1, emp2; varun
emp1.name=“arun”; 22
emp1.age=20;
emp1.salary=35000; 40000.000000
emp2.name=“varun”;
emp2.age=22;
emp2.salary=40000;
printf(“Employee1 details are\n”);
printf(“%s\n%d\n%f\n”,emp1.name,emp1.age,emp1.salary);
printf(“Employee2 details are\n”);
printf(“%s\n%d\n%f\n”,emp2.name,emp2.age,emp2.salary);
}
Example: Output: Output (Continued):
#include<stdio.h> Enter an employee1 name Employee1 details are
arun
struct arun
Enter an employee1 age
{ 20 20
char name[10]; Enter an employee1 salary 35000.000000
int age; 35000 Employee2 details are
Enter an employee2 name varun
float salary;
varun
}emp1,emp2; 22
Enter an employee2 age
22 40000.000000
main() Enter an employee2 salary
40000
{
printf(“Enter an employee1 name\n”); scanf(“%s”,emp1.name);
printf(“Enter an employee1 age\n”); scanf(“%d”,&emp1.age);
printf(“Enter an employee1 salary\n”); scanf(“%f”,&emp1.salary);
printf(“Enter an employee2 name\n”); scanf(“%s”,emp2.name);
printf(“Enter an employee2 age\n”); scanf(“%d”,&emp2.age);
printf(“Enter an employee2 salary\n”); scanf(“%f”,&emp2.salary);
printf(“Employee1 details are\n”);
printf(“%s\n%d\n%f\n”,emp1.name,emp1.age,emp1.salary);
printf(“Employee2 details are\n”);
printf(“%s\n%d\n%f\n”,emp2.name,emp2.age,emp2.salary);
}
Array of Structures:
Structure is used to store the information of one particular object but if we need
to store the information of multiple objects then array of structure is used.
Example:
struct
{
char name[10];
int age;
float salary;
}emp;
In the above example, we can read only one employee details using structure
variable ‘emp’ as emp.name, emp.age and emp.salary. If we want to read more
than one employee details using the same structure, then the structure variable
has to be declared as an array that is emp[20].
Example:
struct
{
char name[10];
int age;
float salary;
}emp[10];
In the above example, using structure variable emp[10], we can read 10 employee
details.
emp[0].name, emp[0].age and emp[0].salary stores the details of first employee.
emp[1].name, emp[1].age and emp[1].salary stores the details of second employee.
emp[2].name, emp[2].age and emp[2].salary stores the details of third employee.
-- - - - - - -
emp[9].name, emp[9].age and emp[9].salary stores the details of tenth employee.
Example: Write a C program to read and display N employee
(details like name, age and salary) details using structure.
#include<stdio.h>
struct employee
{
char name[10];
int age;
float salary;
};
main()
{
struct employee emp[50];
int i,n;
printf(“Enter the number of employees\n”);
scanf(“%d”,&n);
for(i=0;i<n;i++)
{
printf(“Enter the employee %d details\n”,i+1);
printf(“Enter employee name\n”);
scanf(“%s”,emp[i].name);
printf(“Enter employee age\n”);
scanf(“%d”,&emp[i].age);
printf(“Enter employee salary\n”);
scanf(“%f”,&emp[i].salary);
}
printf(“Employee details are\n”);
for(i=0;i<n;i++)
{
printf(“Details of employee %d\n”,i+1);
printf(“Name = %s\n”,emp[i].name);
printf(“Age = %d\n”,emp[i].age);
printf(“Salary = %f\n”,emp[i].salary);
}
} //closing of main()
It allows user to create their own data type (new data type).
Syntax:
Where,
typedef is a keyowrd.
originial_data_type represents data type like int, float, double and char.
Example:
typedef struct
main()
{
{
int day;
humanbeing person;
int month;
printf(“Enter employee name);
int year; scanf(“%s”,person.name);
}date; printf(“Enter employee age);
scanf(“%d”,person.age);
typedef struct
printf(“Enter employee name);
{ scanf(“%f”,person.salary);
char name[10]; printf(“Enter employee dob in dd mm yyyy format\n”);
int age; scanf(“%d%d%d”,&person.dob.day,&person.dob.month,
float salary; &person.dob.year);
date dob; }
}humanbeing;
Nested Structure (Structure within a Structure) without using typedef statement:
Example:
struct date
main()
{
{
int day;
struct employee person;
int month;
printf(“Enter employee name);
int year;
scanf(“%s”,person.name);
};
printf(“Enter employee age);
scanf(“%d”,person.age);
struct employee
printf(“Enter employee name);
{
scanf(“%f”,person.salary);
char name[10];
printf(“Enter employee dob in dd mm yyyy format\n”);
int age;
scanf(“%d%d%d”,&person.dob.day,&person.dob.month,
float salary;
&person.dob.year);
struct date dob;
}
};
Self-Referential Structures:
Example:
struct self
int p; Structure
Members
struct self *ptr;
};
Example: struct code { var1 var2
int i; i c ptr i c ptr
char c;
struct code *ptr; 65 ‘A’ NULL 66 ‘B’ NULL
};
1000 2000
main() Base Address Base Address
{
struct code var1;
struct code var2;
var1.i = 65;
var1.c = ‘A’; Access
var1.ptr = NULL; var1 var2
i c ptr i c ptr
var2.i = 66; 65 ‘A’ 2000 66 ‘B’ NULL
var2.c = ‘B’;
var2.ptr = NULL; 1000 2000
Base Address Base Address
var1.ptr = &var2;
printf(“%d\n”,var1.ptr->i);
printf(“%c\n”,var1.ptr->c); Output:
}
66
Note: we will see usefulness of Self-
B
Referential Structures in Linked List.
How Structure is different from Array OR Differences between Arrays and Structures:
Sl.
Arrays Structures
No.
Array refers to a collection consisting of Structure refers to a collection consisting of
1.
elements of homogeneous data type. elements of heterogeneous data type.
Syntax:
Array uses subscripts or square Structure uses dot (.) operator for
3.
bracket ([])for element access. element access.
Sl.
Arrays Structures
No.
Array size is fixed and is basically the Structure size is not fixed as each
5. number of elements multiplied by element of Structure can be of different
the size of an element. type and size.
Array elements are accessed by their Structure elements are accessed by their
9.
index number using subscripts. names using dot operator.
Unions
Definition:
A union is a collection of data items, where each item is identified as to its
type and name. The keyword used is ‘union’.
In other words, a union is a collection of one or more variables of same or
different data types .
Memory allocated is shared by individual members of union .
Syntax:
union union_name OR union
{ {
data_type1 variable1; data_type1 variable1;
data_type2 variable2; data_type2 variable2;
. . . . . . . .
data_typen variablen; data_typen variablen;
}; }union_variable;
Syntax: OR
union union_name union
{ {
data_type1 variable1; data_type1 variable1;
data_type2 variable2; data_type2 variable2;
. . . . . . . .
data_typen variablen; data_typen variablen;
}; }union_variable;
main() main()
{ {
union employee emp; . . . .
. . . . . . . .
. . . . . . . .
} User Defined Data Type Union Variable
}
Accessing the Members of Union:
Using union_variable and dot (.) operator, we can access the members
of the union. dot (.) operator
Syntax:
union_variable.union_member_name
Example:
union
{
char name[10];
int age;
float salary;
}person;
In the above example, union creates a variable whose name is ‘person’ and
which has 3 fields.
A name that is a character array.
An integer value representing the age of the person.
A float value representing the salary of the person.
We can assign values to fields using the dot (.) operator:
strcpy(person.age,”arun”);
person.age = 20;
person.salary = 35000;
Example:
#include<stdio.h>
Output:
union
{ 65
int a;
char b; A
}un;
main()
{
un.a = 10;
un.b = ‘A’;
printf(“%d\n%c\n”,un.a,un.b);
}
un.a un.b
Here, Assume size of ‘int’
un
data type 2 Bytes and size
2000 10 ‘A’
of ‘char’ data type 1 Byte.
2000
Base Address un.a and un.b are the
1 Byte for ‘char’ members of union.
2 Bytes for ‘int’
Example:
Output:
#include<stdio.h>
10
union
A
{
int a;
char b;
}un;
main()
{
un.a = 10;
printf(“%d\n”,un.a);
un.b = ‘A’;
printf(“%c\n”,un.b);
}
Differences between Structure and Union
Sl.
Structure Union
No.
The keyword ‘struct’ is used to define a The keyword ‘union’ is used to define a
1.
structure. union.
Syntax: Syntax:
struct union
{ {
data_type1 variable1; data_type1 variable1;
2.
data_type2 variable2; data_type2 variable2;
. . . . . . . .
data_typen variablen; data_typen variablen;
}structure_variable; }union_variable;
Example: Example:
struct union
{ {
3.
int a; int a;
char b; char b;
}S; }U;
Differences between Structure and Union
Sl.
Structure Union
No.
When a variable is associated with a When a variable is associated with a union,
structure, the compiler allocates the the compiler allocates the memory by
memory for each member. The size of considering the size of the largest memory. So,
structure is greater than or equal to the size of union is equal to the size of largest
sum of sizes of its members. member.
Example: Example:
struct union
{ Assume { Assume
4. int a; int a; int = 2 Bytes
int = 2 Bytes
char b; char b;
}S; char = 1 Byte }U; char = 1 Byte
U
S
2000
2000
2000 Base Address
2000 Base Address
1 Byte for char
2 Bytes 1 Byte
(int) (char)
2 Bytes for int
Total Memory Allocated for Structure = 3 Bytes Total Memory Allocated for Structure = 2 Bytes
Differences between Structure and Union
Sl.
Structure Union
No.
Each member within a structure is
Memory allocated is shared by individual
5. assigned unique storage area of
members of union.
location.
Several members of a structure can Only the first member of a union can be
8.
initialize at once. initialized.
Assignment Question:
1. Define Pointers. How to declare and initialize pointers, explain with
example.
2. What do you mean by dynamic memory allocation? List and explain various
functions supported by C to carryout dynamic memory allocation.
of the array and a subscript or index, which indicates the position of the
It can be used to store the values of different data types, such as int,
Multi-Dimensional Array
etc.,
One Dimensional Array (1D Array)
One Dimensional Array is used for storing the values of same data type
in a Linear List (only one row).
Syntax:
data_type array_name[size];
Where,
size represents the number of values of the data_type type that can
be stored in the array_name array.
One Dimensional Array (1D Array)
Example 1:
int a[10];
Where,
int represents data type.
a represents the name of the array.
10 represents size of the array.
Example 2:
float arr[5];
Where,
float represents data type.
arr represents the name of the array.
5 represents size of the array.
Structure of One Dimensional Array:
the array.
One Dimensional Array (1D Array)
Initialization of One Dimensional Array:
Syntax:
size represents the number of values of the data_type type that can
be stored in the array_name array.
Base Address
Memory Location Address
In the above example, int represents data type, a represents name of the
array, size represents size of the array and 10,20,30,40 and 50
represents array elements which is stored in a[0],a[1],a[2],a[3] and
a[4] respectively.
Example (continued):
int a[5];
In the above example, the array size is specified as 5 and its data
Here, an array is of the Integer type and of size 4 is having four elements
in it. Number of elements in array should not be greater than the array
size.
a[0] a[1] a[2] a[3]
22 31 43 56
Here, an array is of the floating point type and of size 5 is having three
elements in it and remaining two elements to zero (0).
not specified which means that array can hold any number
of elements.
Let us assume that a[0] holds the value 11, a[1] holds the value 12,
a[2] holds the value 13, a[3] holds the value 14 and a[4] holds the
value 15. What is the Code?
Syntax:
data_type array_name[row_size][column_size];
Where,
Example 2:
float arr[5][5];
Where,
float represents data type.
arr represents the name of the array.
5 represents number of rows.
5 represents number of columns.
Structure or Representation of Two Dimensional Array:
Here, we consider array variable or array name as ‘a’
C o l u m n s
o . . . . .
. . . . .
w . . . . .
. . . . .
s
a[m-1] a[m-1][0] a[m-1][1] . . . . a[m-1][n-1]
In the above figure, there are two index values, one for representing
of columns.
Row index start from 0 and ends with m-1, where m is the number of
rows.
Column index start from 0 and ends with n-1, where n is the number
of columns.
a[0][0] holds the element present in First Row and First Column,
a[0][1] holds the element present in First Row and Second Column
and so on.
Two Dimensional Array (2D Array)
Initialization of Two Dimensional Array:
Syntax:
data_type array_name[row_size][column_size]={list of values};
Where,
a[0]
10 20 30
a[0][0] a[0][1] a[0][2]
a[1] 40 50 60
a[1][0] a[1][1] a[1][2]
Example:
int a[2][3];
specified as 3 and its data type is int which occupies 2 Bytes per
Here, an array is of the Integer type and of row size 2 and column size 3
is having six elements in it. Number of elements in array should not be
greater than the array size.
a[0]
22 31 43
a[0][0] a[0][1] a[0][2]
a[1] 56 65 78
a[1][0] a[1][1] a[1][2]
Note:
Here, an array is of the Floating Point type and of row size 2 and column
size 3 is having three elements in it and remaining three elements to
zero (0).
a[0]
0.0 15.75 -10
a[0][0] a[0][1] a[0][2]
a[1] 0 0 0
a[1][0] a[1][1] a[1][2]
Note:
int arr[][] = {1,1,1,1,1,1,1,1};
Here, an array is of the Integer type and row size and
column size of the array is not specified which means that
array can hold any number of elements.
For Example:
int arr[2][3] = {1,1,1,1,1,1};
The above initialization can also be done row by row. The
above example can be equivalently written as
int arr[2][3] = {{1,1,1},{1,1,1}};
} the 2D array.
printf(“\n”);
}
}
Output 1
Enter the row size and column size of the array
2 3
Enter the array elements
10
20
30
40
50
60
The stored array elements are
10 20 30
40 50 60
Output 2
Enter the row size and column size of the array
4 4
Enter the array elements
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
The stored array elements are
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
THANK YOU
|| JAI SRI GURUDEV ||
SRI ADICHUNCHANAGIRI SHIKSHANA TRUST ®
Example:
DATA[4] 135
Note:
DATA[5] 87
In Figure(a), the array index starts with ‘1’.
DATA[6] 156
In Figure(b), the array index starts with ‘0’.
Figure (a)
DATA[0] DATA[1] DATA[2] DATA[3] DATA[4] DATA[5]
DATA[1] 246
246 56 429 135 87 156
DATA[2] 56
In this example, what is the Length of an array DATA?
DATA[3] 429 Here, the array is abbreviated as DATA[0:5]
Lower Bound (LB) = 0
DATA[4] 135
Upper Bound (UB) = 5
DATA[5] 87 The formula is
Length = UB – LB + 1
DATA[6] 156 Length = 5 – 0 + 1
Length = 6
Solution:
i. AAA(5:50)
Here, LB = 5 and UB = 50
Length = UB – LB + 1 => Length = 50 – 5 + 1 => Length = 46
ii. BBB(-5:10)
Here, LB = -5 and UB = 10
Length = UB – LB + 1 => Length = 10 – (-5) + 1 => Length = 16
iii. CCC(18)
Here, we assumed an array index starts with ‘1’. LB = 1 and UB = 18
Length = UB – LB + 1 => Length = 18 – 1 + 1 => Length = 18
Example:
Note:
Consider an array AAA[5:65], if
Base(AAA) = 300 and w = 4. Find The address of any element of Linear Array can be
the address of
determined by using below formula:
i. AAA[15]
ii. AAA[35] LOC(LA[K])=Base(LA)+w(K-Lower Bound)
iii. AAA[55]
Solution:
Given Data: Base(AAA) = 300, w = 4 and AAA[5:65], here LB = 5 and UB = 65
i. AAA[15], Here, K = 15
LOC(AAA[K]) = Base(AAA) + w(K-Lower Bound)
LOC(AAA[15]) = 300 + 4 (15 – 5) => LOC(AAA[15]) = 340
ii. AAA[35], Here, K = 35
LOC(AAA[K]) = Base(AAA) + w(K-Lower Bound)
LOC(AAA[35]) = 300 + 4 (35 – 5) => LOC(AAA[35]) = 420
iii. AAA[55], Here, K = 55
LOC(AAA[K]) = Base(AAA) + w(K-Lower Bound)
LOC(AAA[55]) = 300 + 4 (55 – 5) => LOC(AAA[55]) = 500
Multidimensional Arrays
The linear arrays discussed so far are also called One-dimensional arrays,
arrays. i.e, arrays where elements are referenced, respectively, by two and
three subscripts.
etc.,
Two-dimensional Arrays
Definition:
A two-dimensional m x n array A is collection of m*n data elements such that
each element is specified by a pair of integers (such as J, K), called subscripts,
with the property that
1 ≤ J ≤ m and 1 ≤ K ≤ n
The element of A with first subscript J and second subscript K will be denoted by
AJ,K or A[J, K]
Two-dimensional arrays are called matrices in mathematics and tables in
business applications, hence two-dimensional arrays are sometimes called
matrix arrays.
There is a standard way of drawing a two-dimensional m x n array A where the
elements of A form a rectangular array with m rows and n columns and where
the element A[J, K] appears in row J and column K (a row is a horizontal list of
elements and a column is a vertical list of elements).
Example:
The below example shows an two-dimensional array ‘A’ has 3 rows and 4
columns.
Columns
A[1,1]
A[2,1] Column 1
A[3,1]
A[1,2]
A[2,2] Column 2
A[3,2]
A[1,3]
A[2,3] Column 3
A[3,3]
A[1,4]
A[2,4] Column 4
A[3,4]
A[1,1]
A[1,2]
Row 1
A[1,3]
A[1,4]
A[2,1]
A[2,2]
Row 2
A[2,3]
A[2,4]
A[3,1]
A[3,2]
Row 3
A[3,3]
A[3,4]
the address LOC(A[J,K]) of array A[J,K] using the below formula (recall
Lower Bound))
Where,
Assistant Professor
22 October 2020
Date : 15-10-2020 (03:30PM TO 04:30PM)
General Multidimensional Arrays
Definition:
property that
1 ≤ K1 ≤ m1, 1 ≤ K2 ≤ m2, . . . . , 1 ≤ Kn ≤ mn
BK1,K2,….,Kn or B[K1,K2,….,Kn]
Example: Suppose B is a three-dimensional array .
Declaration of Three-dimensional Array:
Syntax:
data_type array_name[size1][size2][size3];
Where, size1 represents number of rows
size2 represents number of columns
size3 represents number of pages
Example:
int B[2][4][3];
In the above example, B is a three-dimensional array. It contains 2 rows, 4
columns and 3 pages. Column1 Column1 Column1 Column1
Row1
Row2
Example: Consider an three-dimensional array B[2][4][3]. The array B
pictured as in below figure. They appear in three layers called pages, where
each page consists of the 2*4 rectangular array of elements with the same third
subscript.
the first subscript varies first (most rapidly), the second subscript
[2,1,1]
B[2,1,3] B[2,2,3]
[1,2,1]
Page3
B[1,1,2] B[1,2,2]
[2,2,1]
[1,1,2]
B[2,1,2] B[2,2,2]
[2,1,2] Page2
[2,1,3]
[1,2,3]
[2,2,3]
[1,1,2]
B[2,1,3] B[2,2,3]
[1,1,3]
Page3
B[1,1,2] B[1,2,2]
[1,2,1]
[1,2,2]
B[2,1,2] B[2,2,2]
[1,2,3] Page2
[2,2,1]
[2,2,2]
[2,2,3]
B[2:4,-4:-3,6:7]
L1 = 4 – 2 +1 = 3
L2 = -3 – (-4) +1 = 2
L3 = 7 – 6 +1 = 2
Accordingly, B contains
L1 * L2 * L3 = 3 * 2 * 2 = 12 elements.
and Base(B)=200 and there are w=2 words per memory cell. Find the address of
B[3,-3,7].
Example (Continued): Suppose a three-dimensional array B is declared using
B[2:4,-4:-3,6:7]. That is B[3,2,2] = 3*2*2 = 12 elements.
The address of B[3,-3,7] is obtained as follows:
The effective indices are of the subscripts are, respectively.
By using equation, Ei = Ki – lower bound
E1 = 3 – 2 = 1
E2 = -3 –(-4) = 1
E3 = 7 – 6 = 1
Using row-major order , we have
LOC(B[3,-3,7]) = Base(B)+w[(E1L2+E2)L3 + E3]
E1L2 = 1 * 2 = 2
E1L2 + E2 = 2 + 1 = 3
(E1L2+E2)L3 = 3 * 2 = 6
(E1L2+E2)L3 + E3= 6 + 1 = 7
Therefore,
LOC(B[3,-3,7])= 200 + 2(7) = 214 (address)
Visualization of Previous Example:
Column -4 Column-3
Suppose a three-dimensional array B is declared using
B[2,-4,7] B[2,-3,7]
B[2:4,-4:-3,6:7]. That is B[3,2,2] = 3*2*2 = 12 elements. B[3,-4,7] B[3,-3,7]
B[4,-4,7] B[4,-3,7]
Using Row-Major Order:
Page7
Address B Subscripts Row2 B[2,-4,6] B[2,-3,6]
MAZE[2:8,-4:1,6:10]
Solution:
L1 = 8 – 2 + 1 = 7
L2 = 1 – (-4) + 1 = 6
L3 = 10 – 6 +1 = 5
L1 * L2 * L3 = 7 * 6 * 5 = 210 elements.
Example (Continued):
The address of MAZE[5,-1,8] is obtained as follows:
The effective indices are of the subscripts are, respectively.
By using equation, Ei = Ki – lower bound
E1 = 5 – 2 = 3
E2 = -1 –(-4) = 3
E3 = 8 – 6 = 2
Using row-major order , we have
LOC(MAZE[K1,K2,K3]) = Base(MAZE)+w[(E1L2+E2)L3 + E3]
E1L2 = 3 * 6 = 18
E1L2 + E2 = 18 + 3 = 21
(E1L2+E2)L3 = 21 * 5 = 105
(E1L2+E2)L3 + E3 = 105 + 2 = 107
Therefore,
LOC(MAZE[5,-1,8])= 200 + 4(107) = 200 + 428 = 628 (address)
Dynamically Allocated Arrays
Definition:
is the simplest type of array that contains only one row for storing data.
solution to this problem is to defer this decision to run time and allocate the
int i,n,*list;
printf(“Enter size of an array\n”);
Output:
scanf(“%d”,&n);
Enter size of an array
if(n<1)
5
{
Enter the elements
printf(“Improper value of n\n”);
1 2 3 4 5
exit(0);
The elements are
}
1 2 3 4 5
MALLOC(list, n*sizeof(int));
Example Program using calloc(): printf(“Enter the elements\n”);
#inlcude<stdio.h> for(i=0;i<n;i++)
#include<stdlib.h> {
scanf(“%d“,list+i);
#define CALLOC(p,n,s) \
}
if(!((p)= calloc(n,s))) { \
printf(“The elements are\n”);
printf(“Insufficient Memory\n”); \
for(i=0;i<n;i++)
exit(0); \ {
} printf(“%d\t“,*(list+i));
main() }
{ } // Closing of main()
int i,n,*list;
printf(“Enter size of an array\n”);
Output:
scanf(“%d”,&n);
Enter size of an array
if(n<1)
5
{
Enter the elements
printf(“Improper value of n\n”);
1 2 3 4 5
exit(0);
The elements are
}
1 2 3 4 5
CALLOC(list,n,sizeof(int));
Dynamically Allocated Arrays for 2D Array
multidimensional array.
For example:
int x[3][5];
x[0]
x[1]
x[2]
Traversing Operation
Inserting Operation
Deleting Operation
Sorting Operation
Searching Operation
Traversing Operation:
accomplished by Traversing.
Once.
Traversing Operation (Continued):
Hear LA is a linear array with the lower bound LB and upper bound UB. This
5. Exit.
Traversing Operation (Continued):
Hear LA is a linear array with the lower bound LB and upper bound UB. This
1. Repeat for K = LB to UB
[End of loop]
2. Exit.
Traversing Operation (Continued):
Example: Consider the array AUTO which records the number of automobiles
To find the number NUM of years during which more than 300 automobiles were
[End of loop.]
3.Return.
Traversing Operation (Continued):
Example: Consider the array AUTO which records the number of automobiles
sold each year from 1932 through 1936.
To find the number NUM of years during which more than 300 automobiles were
sold, involves traversing AUTO.
1.[Initialization step.] Set NUM := 0
2. Repeat for K = 1932 to 1936:
If AUTO [K] > 300, then: Set NUM := NUM + 1.
Index Value
[End of loop.]
3.Return. AUTO[1932] 300
AUTO[1933] 400
Here, NUM = 3
AUTO[1934] 350
AUTO[1935] 285
AUTO[1936] 310
Traversing Operation (Continued):
Example: Consider the array AUTO which records the number of automobiles
To print each year and the number of automobiles sold in that year.
Write: K, AUTO[K].
[End of loop]
2. Return
Inserting Operation:
Inserting an element at the “end” of the linear array can be easily done
provided the memory space allocated for the array is large enough to
Inserting an element in the middle of the array, then on average, half of the
Here LA is a linear array with N elements and K is a positive integer such that K ≤
7. Exit.
Deleting Operation:
Deleting an element at the “end” of the linear array can be easily done with
difficulties.
Here LA is a linear array with N elements and K is a positive integer such that K ≤
2.Repeat for J = K to N – 1
[End of loop]
4. Exit
Example: Inserting and Deleting:
Suppose NAME is an 8-element linear array, and suppose five names are in the array, as in Fig.(a).
Observe that the names are listed alphabetically, and suppose we want to keep the array names alphabetical at
all times. Suppose Ford is added to the array. Then Johnson, Smith and Wagner must each be moved downward
Next suppose Taylor is added to the array; then Wagner must be moved, as in Fig.(c).
Last, suppose Davis is removed from the array. Then the five names Ford, Johnson, Smith, Taylor and Wagner
Assistant Professor
31 October 2020
Date : 28-10-2020 (11:00AM TO 11:40AM)
Sorting Operation:
Sorting refers to the operation of rearranging the elements of a list. Here list be
order.
8, 4, 19, 2, 7, 13, 5, 16
2, 4, 5, 7, 8, 13, 16, 19
Sorting Operation (Continued):
Bubble Sort:
Suppose the list of numbers A[1], A[2], ... , A[N] is in memory. The
bubble sort algorithm works as follows:
Algorithm: (Bubble Sort) BUBBLE (DATA,N)
Here DATA is an array with N elements. This algorithm sorts
the elements in DATA.
1.Repeat Steps 2 and 3 for K = 1 to N – 1.
2. Set PTR: = 1.[Initializes pass pointer PTR.]
3. Repeat while PTR ≤ N - K: [Executes pass.]
(a) If DATA[PTR] > DATA[PTR + 1], then:
Interchange DATA [PTR] and DATA [PTR + 1].
[End of If structure.]
(b) Set PTR: = PTR + 1.
[End of inner loop.]
[End of Step 1 outer loop.]
4.Exit.
Example
Example (Continued)
Complexity of the Bubble Sort Algorithm:
which places the largest element in the last position; there are n - 2
comparisons in the second step, which places the second largest element in
Assistant Professor
31 October 2020
Date : 28-10-2020 (03:00PM TO 04:00PM)
Searching Operation:
Searching refers to the operation of finding the location LOC of ITEM in DATA,
unsuccessful otherwise.
Searching Operation (Continued):
Linear Search:
about DATA, The way to search for a given ITEM in DATA is to compare ITEM with
each element of DATA one by one. That is, first test whether DATA [l] = ITEM, and
then test whether DATA[2] = ITEM, and so on. This method, which traverses
Here DATA is a linear array with N elements, and ITEM is a given item of
information. This algorithm finds the location LOC of ITEM in DATA, or sets
[End of loop.]
5. Exit.
Searching Operation (Continued):
Linear Search (Continued):
Consider the array NAME in below figure (a), when n=6.
Example:
Suppose we want to know whether the name Paula appears in the array and if so, where.
Our algorithm temporarily places Paula at the end of the array, as pictured in below
figure(b), by setting NAME[7] = Paula.
Then the algorithm searches the array from top to bottom. Since Paula first appears in
NAME[N+1]. Paula is not in the original array.
Worst Case:
Average Case:
Searching Operation (Continued):
Binary Search:
algorithm, called Binary Search, which can be used to find the location LOC of a
Here DATA is a sorted array with lower bound LB and upper bound UB, and ITEM
is a given item of information. The variables BEG, END and MID denote, the
algorithm finds the location LOC of ITEM in DATA or sets LOC = NULL.
Searching Operation (Continued):
Binary Search (Continued):
Algorithm: (Binary Search) BINARY(DATA, LB, UB, ITEM, LOC)
1.[Initialize segment variables.]
Set BEG: = LB, END := UB and MID = INT((BEG + END)/2).
2.Repeat Steps 3 and 4 while BEG ≤ END and DATA [MID] ≠ ITEM.
3. If ITEM < DATA [MID], then:
Then ITEM can appear
Set END := MID – 1. only in the LEFT half of
Else: the segment
Set BEG := MID + 1.
[End of If structure.] Then ITEM can appear
4. Set MID := INT((BEG + END)/2). only in the RIGHT half of
[End of Step 2 loop.] the segment
5.If DATA[MID] = ITEM, then:
Set LOC := MID.
Else:
Set LOC := NULL.
[End of If structure.]
6.Exit.
Searching Operation (Continued):
Binary Search (Continued):
Let DATA be the following sorted 13 elements array:
DATA:11,22,30,33,40,44,55,60,66,77,80,88,99
Example:
Suppose ITEM=40. The search for ITEM in the array DATA, where the values of DATA[BEG]
and DATA[END] in each stage of the algorithm are indicated by circle and the value of
DATA[MID] by a square. Specifically, BEG, END and MID will have the following successive
values:
Searching Operation (Continued):
Binary Search (Continued):
Let DATA be the following sorted 13 elements array:
DATA:11,22,30,33,40,44,55,60,66,77,80,88,99
Example:
Suppose ITEM=85. Here BEG, END and MID will have the following successive values:
Complexity of the Binary Search Algorithm:
DATA where DATA contains n elements. Observe that each comparison reduces
the sample size in half. Hence we require at most f(n) comparisons to locate
ITEM where
That is, the running time for the worst case is approximately equal to log2n. One
can also show that the running time for the average case is approximately equal
ADT Polynomial is
Objects: p(x) = a1xe1 +....+ anxen; a set of ordered pairs of <ei,ai> where ai in
Coefficients and ei in Exponents, ei are integers >= 0
Functions:
for all poly, poly1, poly2 ϵ Polynomial, coef ϵ Coefficients, expon ϵ Exponents
Polynomial Zero() ::= return the polynomial, p(x)=0
end Polynomial
To preserve space an alternate representation that uses only one global array, terms to
store all polynomials.
The C declarations needed are:
MAX_TERMS 100 /*size of terms array*/
typedef struct{
float coef;
int expon;
} polynomial;
polynomial terms[MAX-TERMS];
int avail = 0;
Consider the two polynomials
A(x) = 2xl000+ 1
B(x) = x4 + 10x3 + 3x2 + 1
The below figure shows how these polynomials are stored in the array terms.
The index of the first term of A and B is given by startA and startB, while
finishA and finishB give the index of the last term of A and B.
The index of the next free location in the array is given by avail.
For above example, startA=0, finishA=1, startB=2, finishB=5, & avail=6.
Polynomial Addition
C function is written that adds two polynomials, A and B to obtain D =A + B.
To produce D(x), padd( ) is used to add A(x) and B(x) term by term. Starting at
position avail, attach( ) which places the terms of D into the array, terms.
If there is not enough space in terms to accommodate D, an error message is
printed to the standard error device & exits the program with an error condition
The below code represents Function to add two polynomials:
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;
*finishD = avail-1;
}
The below code represents Function to add a new term:
void attach(float coefficient, int exponent)
{
/* add a new term to the polynomial */
if (avail >= MAX-TERMS)
{
printf("Too many terms in the polynomial\n");
exit(0);
}
terms[avail].coef = coefficient;
terms[avail++].expon = exponent;
}
Example:
Consider the following two polynomials and perform addition
A(x) = 2xl000+ 1
B(x) = 3x2 + 1
Array representation of polynomial:
The number of non-zero terms in A and B is the most important factors in analyzing the
time complexity.
Let m and n be the number of non-zero terms in A and B, If m >0 and n > 0, the while loop
is entered. Each iteration of the loop requires O(1) time. At each iteration, the value of
startA or startB or both is incremented. The iteration terminates when either startA or
startB exceeds finishA or finishB. The number of iterations is bounded by m+n-1
The time for the remaining two for loops is bounded by O(n + m) because we cannot
iterate the first loop more than m times and the second more than n times. So, the
asymptotic computing time of this algorithm is O(n +m).
SPARSE MATRICES
In mathematics, a matrix contains m rows and n columns of elements as illustrated in
below figures. In this figure, the elements are numbers. The first matrix has five rows and
three columns and the second has six rows and six columns. We write m x n (read "m by
n") to designate a matrix with m rows and n columns. The total number of elements in such a
matrix is m*n. If m equals n, the matrix is square.
Important Note:
A sparse matrix can be represented in 1-Dimensional, 2- Dimensional and 3-
Dimensional array. When a sparse matrix is represented as a two-dimensional array as
shown in above Figure (b), more space is wasted.
Example: Consider the space requirements necessary to store a 1000 x 1000 matrix that has
only 2000 non-zero elements. The corresponding two-dimensional array requires space for
10,000,00 elements. The better choice is by using a representation in which only the
nonzero elements are stored.
ADT SparseMatrix is
Objects: a set of triples<row,column,value>, where row and column are
integers and form a unique combination and value comes from the set item.
Functions:
for all a,b ϵ SparseMatrix, x ϵ item, i,j,maxCol,maxRow ϵ index
Organize the triples so that the row indices are in ascending order.
The operations should terminate, so we must know the number of rows and columns,
and the number of nonzero elements in the matrix.
term a[MAX_TERMS];
the number of rows, a[0].col contains the number of columns and a[0].value contains
Positions 1 through 8 store the triples representing the nonzero entries. The row
index is in the field row, the column index is in the field col, and the value is in the
field value. The triples are ordered by row and within rows by columns.
Transposing a Matrix:
To transpose a matrix, interchange the rows and columns. This means that each element
a[i][j] in the original matrix becomes element a[j][i] in the transpose matrix.
If we process the original matrix by the row indices it is difficult to know exactly where to
place element <j, i, value> in the transpose matrix until we processed all the elements
This can be avoided by using the column indices to determine the placement of elements
Example:
Based on the following algorithm, by using the column indices to determine the placement
of elements in the transpose matrix.
for all elements in column j
place element <i, j, value> in
element <j, i, value>
Step1:
Step2:
Step3:
Step4:
Step5:
Step6:
Step7:
Step8:
Step9:
Note:
Asymptotic Time Complexity of this algorithm is O(columns.elements).
Assignment Questions:
1. Define an array. List all the array operations. Briefly explain them
along with algorithm and example.
2. Give the ADT for polynomial and sparse matrix.
3. What is a polynomial? What is the degree of the polynomial?
Consider two polynomial A(x)=4x15-3x4+5 and B(x)=x4+10x2+1. Show
diagrammatically how these polynomials can be stored in a 1-D
array. Write a function to add 2 polynomials A and B store the result
in polynomial C.
4. What is sparse matrix? Express the given sparse matrix as triplet and
find its transpose and also write a transpose algorithm to transpose a
sparse matrix.
5. Express the given sparse matrix as triplet and find its transpose.
FAST TRANSPOSE OF A SPARSE MATRIX
As its name suggests, it is a faster way to transpose a sparse matrix and also a little bit hard
to understand. Time complexity is O(columns + elements). Here, we require 2 arrays,
namely, rowTerms and startingPos.
The following code represents Fast Transpose of a Sparse Matrix:
void fastTranspose(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++)
rowTerms[a[i].col]++;
startingPos[0]=1;
for(i=1;i<numCols;i++)
startingPos = 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;
}
}/*Closing of if statement*/
}
Example:
Step2: Then, find two one dimensional arrays. That is, rowTerms
and startingPos
Find the rowTerms array:
Size of the rowTerms array = Number of columns present in the given sparse matrix.
Here, the size of rowTerms array = 6.
Find the startingPos array:
Size of the staringPos array = Size of rowTerms array + 1 6 + 1 7
Here, the size of rowTerms array = 7.
Each programming languages contains a character set that is used to communicate with the
computer.
Alphabet: ABCDEFGHIJKLMNOPQRSTUVWXYZ
Digits: 0 1 2 3 4 5 6 7 8 9
Concatenation: Let S1 and S2 be the strings. The string consisting of the characters of
Substring: A string Y is called substring of a string S if there exist string X and Z such that
S = X // Y // Z
Declaration 1:
s[0] s[1] s[2] s[3] t[0] t[1] t[2] t[3] t[4] t[4]
d o g \0 h o u s e \0
The above figure shows how these strings would be represented internally in memory.
Declaration 2:
char s[ ] = {“dog”};
char t[ ] = {“house”};
Using these declarations, the C compiler will allocate just enough space to hold each
word including the null character.
Storing Strings:
3. Linked structures
In fixed length structures each line of print is viewed as a record, where all have the
same length i.e., where each record accommodates the same number of characters.
Example: Suppose the input consists of the program. Using a record oriented, fixed
length storage medium (the length of each record occupied by 80 bytes), the input
data will appear in memory as pictured below.
Suppose, if new record needs to be inserted, then it requires that all succeeding records
be moved to new memory location. This disadvantage can be easily remedied as shown
in below figure.
That is, one can use a linear array POINT which gives the address of successive record,
so that the records need not be stored in consecutive locations in memory. Inserting a
new record will require only an updating of the array POINT.
The main advantages of this method are
1. The ease of accessing data from any given record
2. The ease of updating data in any given record (as long as the length of the new data
does not exceed the record length)
Example:
The other method to store strings one after another by using some separation marker,
such as the two dollar sign ($$) or by using a pointer giving the location of the string.
These ways of storing strings will save space and are sometimes used in secondary
memory when records are relatively permanent and require little changes.
These types of methods of storage are usually inefficient when the strings and their
lengths are frequently being changed.
3. Linked Storage:
Most extensive word processing applications, strings are stored by means of linked
lists.
In a one way linked list, a linearly ordered sequence of memory cells called nodes,
where each node contains an item called a link, which points to the next node in the
list, i.e., which consists the address of the next node.
Variables:
Each programming languages has its own rules for forming character variables. These
variables fall into one of three categories
1. Static: In static character variable, whose length is defined before the program is
executed and cannot change throughout the program.
2. Semi-static: The length of the variable may vary during the execution of the program
as long as the length does not exceed a maximum value determined by the program
before the program is executed.
3. Dynamic: The length of the variable can change during the execution of the program.
STRING OPERATIONS:
Substring:
The syntax denote the substring of a string S beginning in a position K and having a
length L.
Indexing:
Indexing also called pattern matching, refers to finding the position where a string
pattern P first appears in a given string text T. This operation is called INDEX
INDEX('Data Structure','Struct') = 6
If the pattern P does not appears in the text T, then INDEX is assigned the value 0.
The arguments “text” and “pattern” can be either string constant or string variable.
Concatenation:
Let S1 and S2 be string. The concatenation of S1 and S2 which is denoted by S1 // S2, is the
string consisting of the characters of S1 followed by the character of S2.
Example:
strcat( ) function is part of the "string.h" header file; hence it must be included at the
time of pre- processing
Length:
String length is determined in C language using the strlen( ) function, as shown below:
x = strlen("sunrise");
Similar to strcat(), strlen() is also a part of "string.h", hence the header file must be
included at the time of pre-processing.
The different C String Functions are:
Programming Examples:
Write a C program to find the concatenation of two strings using pointer (don't
use library function).
#include<stdio.h>
main()
int i,k=0;
gets(str1);
gets(str2);
a=str1; b=str2;
for(i=0;str1[i]!='\0';i++)
str3[k] = str1[i];
k++;
for(i=0;str2[i]!='\0';i++)
str3[k] = str2[i];
k++;
str3[k]='\0';
}
Write a C program to compare two strings data whether it is
same or not without using strcmp() built-in function.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void main()
scanf(“%s%s”,str1,str2);
len1 = strlen(str1);
len2 = strlen(str2);
if(len1 != len2)
else
if(str1[i]!=str2[i])
exit(0);
#include<stdio.h>
#include<string.h>
void main()
printf(“Enter a string\n”);
gets(str1);
k = strlen(str1);
str2[i] = str1[k-i-1];
str2[i] = ‘\0’;
x = strcmp(str1,str2);
if(x == 0)
else
#include<stdio.h>
void main()
printf(“Enter a string\n”);
scanf(“%s”,str1);
str2[i] = str1[i];
str2[i] = ‘\0’;
printf(“String2 = %s\n”,str2);
}
Write a C program to find the length of a given string
without using strlen() built-in function.
#include<stdio.h>
void main()
char str[20];
int len = 0;
printf(“Enter a string\n”);
gets(str);
len = len + 1;
}
Pattern Matching Algorithms
Pattern matching is the problem of deciding whether or not a given string pattern P
appears in a string text T. The length of P does not exceed the length of T.
Characters are denoted by lowercase letters (a,b,c,....) and exponents may be used to
denote repetition.
Example: a3b3ab2 for aaabbbabb
(cd)3 for cdcdcd
The empty string may be denoted by ˄, the Geek letter lambda and the concatenation of
strings X and Y may be denoted by X.Y or simply XY.
P with each of the substrings of T, moving from left to right, until a match is found.
Where, WK denote the substring of T having the same length as P and beginning with the
Kth character of T.
First compare P, character by character, with the first substring, W1. If all the characters
Suppose it is found that some character of P is not the same as the corresponding character
Immediately move on to the next substring, W2 That is, compare P with W2. If P ≠ W2 then
The process stops, When P is matched with some substring WK and so P appears in T and
INDEX(T,P) = K or When all the WK's with no match and hence P does not appear in T.
The maximum value MAX of the subscript K is equal to LENGTH (T) - LENGTH (P) +1.
Let us assume, P is a 4 character string and T is a 20 characters string. P and T appear in
That is,
W1 = T[1]T[2]T[3]T[4]
W2 = T[2]T[3]T[4]T[5]
. . . .
W17 = T[17]T[18]T[19]T[20]
P and T are strings with lengths R and S, and are stored as arrays with one character per
element. This algorithm finds the INDEX of P in T.
5. Set K := K + 1
7. Exit
Observation of Algorithms:
Algorithm contains two loops, one inside the other. The outer loop runs
of T.
The inner loop compares P with WK, character by character. If any character
does not match, then control transfers to Step 5, which increases K and then
If the outer loop completes all of its cycles, then P does not appear in T and
so INDEX = 0.
Time Complexity:
The time complexity of this pattern matching algorithm is equal to O(n2).
Examples:
Note: The First Pattern Matching Algorithm is also known as Brute Force Algorithm or
Slow Algorithm.
Problem:
Second Pattern Matching Algorithm:
The second pattern matching algorithm uses a table which is derived from a particular
pattern P but is independent of the text T.
Suppose P = aaba
This algorithm contains the table that is used for the pattern P = aaba.
The Pattern Matching Table is obtained as follows:
Let Qi denote the initial substring of P of length i, hence Q0 = ˄, Q1 = a, Q2 = a2, Q3 =
aab, Q4 = aaba = P (Here Q0 = ˄ is the empty string).
The rows of the table are labeled by these initial substrings of P, excluding P itself.
The columns of the table are labeled a, b and x, where x represents any character
that doesn't appear in the pattern P.
Let f be the function determined by the table; i.e., let f(Qi, t) denote the entry in the
table in row Qi and column t (where t is any character). This entry f(Qi, t) is defined
to be the largest Q that appears as a terminal substring in the string (Qit) the
concatenation of Qi and t.
Example:
For notational convenience, all arrows labeled x are omitted, which must lead to the
initial state Q0.
Time Complexity:
The time complexity of this pattern matching algorithm is equal to O(n).
Algorithm: (Pattern Matching)
The pattern matching table F(Q1,T)of a pattern P is in memory and the input is an
N-character string T = T1 T2 T3 …… TN. The algorithm finds the INDEX of P in T.
Let T = T1 T2 T3 .... TN denote the n-character-string text which is searched for the
pattern P. Beginning with the initial state Q0 and using the text T, we will obtain a
sequence of states S1, S2, S3, ... as follows.
Let S1 = Q0 and read the first character T1. The pair (S1, T1) yields a second state S2;
that is, F(S1, T1) = S2, Read the next character T2, The pair (S2, T2) yields a state S3,
and so on.
NOTE: The Second Pattern Matching Algorithm is also known as Knuth Morris Pratt
(KMP) pattern matching algorithm or Fast algorithm.
Problem1:
Consider the pattern P=aaba. Construct the table and the
corresponding labelled directed graph used in the ‘Fast” or second
pattern matching algorithm.
For each character t, the entry f(Qi,t) in the table is the largest Q which
appears as a terminal substring in the string Qit. We compute:
f(˄,a) = a
f(˄,b) = ˄
f(a,a) = a2
f(a,b) = ˄
f(a2,a) = a2
f(a2,b) = a2b
f(a2b,a) = P
f(a2b,b) = ˄
Problem2:
Consider the pattern P=aaabb. Construct the table and the
corresponding labelled directed graph used in the ‘Fast” or second
pattern matching algorithm.
The initial substrings of P are:
For each character t, the entry f(Qi,t) in the table is the largest Q which
appears as a terminal substring in the string Qit. We compute:
Problem3:
Find the table and corresponding graph for the second pattern
matching algorithm where the pattern is P = ababab.
The initial substrings of P are:
For each character t, the entry f(Qi,t) in the table is the largest Q which
appears as a terminal substring in the string Qit. We compute: