0% found this document useful (0 votes)
14 views32 pages

Dsa Module 1

dsa notes

Uploaded by

tulasimr60
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views32 pages

Dsa Module 1

dsa notes

Uploaded by

tulasimr60
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

lOMoARcPSD|50231097

Module 1 Notes DSA

DSA (Visvesvaraya Technological University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Tulasi M. R Tulasi ([email protected])
lOMoARcPSD|50231097

Data Structures and Applications [ BCS304]-3 Sem A Section Sankhya N Nayak


-------------------------------------------------------------------------------------------------------------------------------------

MODULE 1: INTRODUCTION

INTRODUCTION TO DATA STRUCTURES: Data Structures, Classifications (Primitive & Non-Primitive),


Data structure Operations
Review of pointers and dynamic Memory Allocation,
ARRAYS and STRUCTURES: Arrays, Dynamic Allocated Arrays, Structures and Unions, Polynomials,
Sparse Matrices, representation of Multidimensional Arrays, Strings
STACKS: Stacks, Stacks Using Dynamic Arrays, Evaluation and conversion of Expressions

Textbook: Chapter-1:1.2 Chapter-2: 2.1 to 2.7 Chapter-3: 3.1,3.2,3.6


Reference Book 1: 1.1 to 1.4

Textbook:
1. Ellis Horowitz, Sartaj Sahni and Susan Anderson-Freed, Fundamentals of Data Structures in C, 2nd
Ed, Universities Press, 2014
Reference Books:
1. Seymour Lipschutz, Data Structures Schaum's Outlines, Revised 1st Ed, McGraw Hill, 2014.

DATA STRUCTURES
Data may be organized in many ways. A data structure is a storage that is used to store and organize
data. It is a way of arranging data on a computer so that it can be accessed and updated efficiently.

The choice of a particular data structure used depends on the two considerations.
1. It must be rich enough in structure to mirror the actual relationships of the data in the real
world.
2. The structure should be simple enough that one can effectively process the data.
Basic Terminology: Elementary Data Organization:
• Data: Data are simply values or sets of values.
• Data items: Data items refers to a single unit of values.
• Data items that are divided into sub- • Data items that are not able to divide into
items are called Group items. sub-items are called Elementary items.
Ex: An Employee Name may be divided into Ex: SSN
three subitems- first name, middle name,
and last name.
• Entity: An entity is collection of attributes or properties which may assigned values.
Ex: Attributes- Names, Age, Sex, SSN
Values- Amitha K, 34, F, 134-34-5533
• Field is a single elementary unit of information.
• Record is the collection of field values.
• File is the collection of records.
Dept. of CSE, JNNCE, Shivamogga

Downloaded by Tulasi M. R Tulasi ([email protected])


lOMoARcPSD|50231097

Data Structures and Applications [ BCS304]-3 Sem A Section Sankhya N Nayak


-------------------------------------------------------------------------------------------------------------------------------------

Records may also be classified according to length.


A file can have fixed-length records or variable-length records.
• In fixed-length records, all the records contain the • In variable-length records file
same data items with the same amount of space records may contain different
assigned to each data item. lengths.

CLASSIFICATION OF DATA STRUCTURES

Data structures are generally classified as


• Primitive data Structures
• Non-primitive data Structures
1. Primitive data Structures: Primitive data structures are the fundamental data types which are
supported by a programming language. These data types consist of characters that cannot be
divided and hence they also called simple data types.
Ex: integer, real, character and Boolean etc.
2. Non- Primitive data Structures: Non-primitive data structures are those data structures which
are created using primitive data structures.
Ex: linked lists, stacks, trees, and graphs.
Based on the structure and arrangement of data, non-primitive data structures are further
classified into
• Linear Data Structure: A data structure is said to be • Non-linear Data Structure: A data
linear if its elements form a sequence or a linear list. structure is said to be non-linear if
There are basically two ways of representing such the data are not arranged in
linear structure in memory. sequence or a linear. The insertion
• One way is to have the linear relationships and deletion of data is not possible
between the elements represented by means of in linear fashion. This structure is
sequential memory location. mainly used to represent data

Dept. of CSE, JNNCE, Shivamogga

Downloaded by Tulasi M. R Tulasi ([email protected])


lOMoARcPSD|50231097

Data Structures and Applications [ BCS304]-3 Sem A Section Sankhya N Nayak


-------------------------------------------------------------------------------------------------------------------------------------

Ex: Arrays. containing a hierarchical


• The other way is to have the linear relationship relationship between elements.
between the elements represented by means of Ex: Trees and graphs
pointers or links.
Ex: Linked lists.

DATA STRUCTURES OPERATIONS


The data appearing in data structures are processed by means of certain operations.
The following four operations play a major role in this text:
1. Traversing: accessing each record/node exactly once so that certain items in the record may
be processed. (This accessing and processing is sometimes called “visiting” the record.)
2. Searching: Finding the location of the desired node with a given key value or finding the
locations of all such nodes which satisfy one or more conditions.
3. Inserting: Adding a new node/record to the structure.
4. Deleting: Removing a node/record from the structure.
The following two operations, which are used in special situations:
1. Sorting: Arranging the records in some logical order (e.g., alphabetically according to some
NAME key, or in numerical order according to some NUMBER key, such as social security
number or account number)
2. Merging: Combining the records in two different sorted files into a single sorted file.

C DYNAMIC MEMORY ALLOCATION


An array is a collection of items stored at contiguous memory locations.

In static memory allocation, the memory allocated to an array is fixed to a certain size and this may
lead to either wasting memory or not having sufficient memory.
For ex, if we take the array declared with 9 as size and in case only 4 locations are used, we would
waste 5 locations. In a situation there isa a need to enter 3 more elements, so the length (size) of
the array needs to be changed from 9 to 12.
Therefore, C Dynamic Memory Allocation can be defined as a procedure in which the size of a data
structure (like Array) is changed during the runtime.

C provides some functions to achieve these tasks. There are 4 library functions provided by C defined
under <stdlib.h> header file to facilitate dynamic memory allocation in C programming.

Dept. of CSE, JNNCE, Shivamogga

Downloaded by Tulasi M. R Tulasi ([email protected])


lOMoARcPSD|50231097

Data Structures and Applications [ BCS304]-3 Sem A Section Sankhya N Nayak


-------------------------------------------------------------------------------------------------------------------------------------

1. malloc() 2. calloc() 3. free() 4. realloc()

C malloc() method
The “malloc” or “memory allocation” method in C is used to dynamically allocate a single large
block of memory with the specified size. It returns a pointer of type void which can be cast into a
pointer of any form. It doesn’t Initialize memory at execution time so that it has initialized each
block with the default garbage value initially.
Syntax of malloc() in C For Example:
ptr = (cast-type*) malloc(byte-size) ptr = (int*) malloc(100 * sizeof(int));
If the size of int is 4 bytes, this statement will allocate 400 bytes of memory. And, the pointer ptr
holds the address of the first byte in the allocated memory.
If space is insufficient, allocation fails and returns a NULL pointer. We can include the code to
check whether memory is allocated or not.
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}

C calloc() method
1. “calloc” or “contiguous allocation” method in C is used to dynamically allocate the specified
number of blocks of memory of the specified type. it is very much similar to malloc() but has
two different points and these are:
2. It initializes each block with a default value ‘0’.
3. It has two parameters or arguments as compared to malloc().
Syntax of calloc() in C For Example:
ptr = (cast-type*)calloc(n, element-size); ptr = (float*) calloc(25, sizeof(float));
Here, n is the no. of elements and element- This statement allocates contiguous space in
size is the size of each element. memory for 25 elements each with the size of
the float.
If space is insufficient, allocation fails and returns a NULL pointer.

Dept. of CSE, JNNCE, Shivamogga

Downloaded by Tulasi M. R Tulasi ([email protected])


lOMoARcPSD|50231097

Data Structures and Applications [ BCS304]-3 Sem A Section Sankhya N Nayak


-------------------------------------------------------------------------------------------------------------------------------------

C realloc() method
“realloc” or “re-allocation” method in C is used to dynamically change the memory allocation of a
previously allocated memory. 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 will be initialized with
the default garbage value.
Syntax of realloc() in C Example
ptr = realloc(ptr, newSize); ptr = (int*)realloc(ptr, n * sizeof(int));
where ptr is reallocated with new size 'newSize'

If space is insufficient, allocation fails and returns a NULL pointer.

C free() method
“free” method in C is used to dynamically de-allocate the memory. The memory allocated using
functions malloc() and calloc() is not de-allocated on their own. Hence the free() method is used,
whenever the dynamic memory allocation takes place. It helps to reduce wastage of memory by
freeing it.
Syntax of free() in C
free(ptr);

Dept. of CSE, JNNCE, Shivamogga

Downloaded by Tulasi M. R Tulasi ([email protected])


lOMoARcPSD|50231097

Data Structures and Applications [ BCS304]-3 Sem A Section Sankhya N Nayak


-------------------------------------------------------------------------------------------------------------------------------------

ARRAY
1. It is a group of variables of similar data types stored in a contiguous memory location, referred to
by a single name.
2. The size of the array should be mentioned while declaring it in case of static memory allocation.
3. Array elements are always counted from zero (0) onward and Array elements can be accessed
using the position of the element in the array.
4. The array can have one or more dimensions.

Declaration of 1D array
int *list1, list2[5] ;
Both these declarations are pointers to int but list2 reserves 5 locations statically, whereas for list1
memory can be assigned dynamically.
list1=(int*)malloc(n*sizeof(int)); where n is accepted from the user during run time.
To access 3rd element, we can use list1[2] or *(list1+2);
Example program to find sum of n float array members.
#define MAX_SIZE 100 float sum(float list[], int n)
float sum(float [], int); {
float input[MAX_SIZE], answer; int i;
void main(void) float tempsum = 0;
{ for(i=0; i<n; i++)
int i; tempsum = tempsum + list[i];
for( i=0; i<MAX_SIZE; i++) return tempsum;
input[i]= i; }
answer = sum(input, MAX_SIZE);
printf(“\n The sum is: %f \n”, answer);
}
When sum is invoked, input=&input[0] is copied into a temporary location and associated with the
formal parameter list.
A function that prints out both the address of the ith element of the array and the value found at
that address can written as shown in below program.
void print1 (int *ptr, int rows)
{
int i;
printf(“ Address contents \n”);
for(i=0; i<rows; i++)
printf(“% 8u %5d \n”, ptr+i, *(prt+i));
printf(“\n”);
}
Dept. of CSE, JNNCE, Shivamogga

Downloaded by Tulasi M. R Tulasi ([email protected])


lOMoARcPSD|50231097

Data Structures and Applications [ BCS304]-3 Sem A Section Sankhya N Nayak


-------------------------------------------------------------------------------------------------------------------------------------

Array of an element of an array say “Array[ 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).

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

Multi-Dimensional Array (Array of Array) :Array having more than one subscript is called Multi-
Dimensional array. Multi-Dimensional Array is also called as Matrix.
Ex: Two-dimensional array, Three dimensional array, four dimensional array etc.

For example, float x[3][4]; Here, x is a two-dimensional (2d) array. The array can hold 12 elements.
User can think the array as table with 3 row and each row has 4 columns.

2D array: The Two-Dimensional array is used for representing the elements of the array in the form
of the rows and columns and these are used for representing the matrix. Two-Dimensional Array uses
the two subscripts for declaring the elements of the Array
syntax : data_type array_name[num_of_rows][num_of_column];
Array declaration syntax: data_type arr_name [num_of_rows][num_of_column];
Array initialization syntax: Different ways to initialize two dimensional array
int arr_name[2][2] = {{0,0},{0,1},{1,0},{1,1}};
int c[2][3] = {{1, 3, 0}, {-1, 5, 9}};
int c[][3] = {{1, 3, 0}, {-1, 5, 9}};
int c[2][3] = {1, 3, 0, -1, 5, 9};
Array accessing syntax: arr_name[index][index];
Ex: int arr[2][2];
Dept. of CSE, JNNCE, Shivamogga

Downloaded by Tulasi M. R Tulasi ([email protected])


lOMoARcPSD|50231097

Data Structures and Applications [ BCS304]-3 Sem A Section Sankhya N Nayak


-------------------------------------------------------------------------------------------------------------------------------------

int arr[2][2] = {1,2, 3, 4};


arr [0] [0] = 1; arr [0] ]1] = 2; arr [1][0] = 3; arr [1] [1] = 4;

Array Advantage/ Benefits:


1. Simple to access, traverse and sort data, user need a few lines of code only.
2. Random Access: User can access any element randomly using the array.
3. Arrays are used to implement other data structures like linked lists, stacks, queues, trees,
graphs etc.
4. Iterating the array using their index is faster compared to any other methods like linked list
etc.
5. It allows storing the elements in any dimensional array - supports multidimensional array.

Array Disadvantages:
1. User must know in advance that how many elements are to be stored in array.
2. Array is static structure. It means that array is of fixed size. The memory which is allocated
to array cannot be increased or reduced.
3. Since array is of fixed size, if user allocate more memory than requirement then the memory
space will be wasted. And if user allocates less memory than requirement, then it will create
problem.
4. Insertions and deletions are very difficult and time consuming.

STRUCTURES
In C, a way to group data that permits the data to vary in type. This mechanism is called the structure,
for short struct. A structure (a record) is a collection of data items, where each item is identified as
to its type and name.

The above example creates a structure and variable name is Person and that has three fields:
name = a name that is a character array
age = an integer value representing the age of the person
salary = a float value representing the salary of the individual

Assign values to fields :


Type-Defined Structure

Dept. of CSE, JNNCE, Shivamogga

Downloaded by Tulasi M. R Tulasi ([email protected])


lOMoARcPSD|50231097

Data Structures and Applications [ BCS304]-3 Sem A Section Sankhya N Nayak


-------------------------------------------------------------------------------------------------------------------------------------

typedef is the keyword used at the beginning of the definition and by using typedef user defined
data type can be obtained.

In above example, humanBeing is the name of the type and it is a user defined data type.

Declarations of structure variables:


humanBeing person1, person2;
This statement declares the variable person1 and person2 are of type humanBeing.

Accessing members of structure There are two ways to access structure members:
By . (member or dot operator)
By -> (structure pointer operator)
The code to access the id member of p1 variable by . (member) operator. p1.id

Structure Operation
Dept. of CSE, JNNCE, Shivamogga

Downloaded by Tulasi M. R Tulasi ([email protected])


lOMoARcPSD|50231097

Data Structures and Applications [ BCS304]-3 Sem A Section Sankhya N Nayak


-------------------------------------------------------------------------------------------------------------------------------------

The various operations can be performed on structures and structure members.


1. Structure Equality Check:
Here, the equality or inequality
check of two structure
variables of same type or
dissimilar type is not allowed in
older version of C.

comparison can be done in the following way in older versions of C using following method.

Assignment operation on Structure variables:


person1 = person2 Member wise copying can be done as given
The above statement means that the value of below:
every field of the structure of person 2 is strcpy(person1.name, person2.name);
assigned as the value of the corresponding field person1.age = person2.age;
of person 1. This is allowed in Newer versions person1.salary = person2.salary;
of C only.

Structure within a structure:


There is possibility to embed a structure within a structure. There are 2 ways to embed structure.
1. The structures are defined
separately, and a variable of
structure type is declared inside
the definition of another
structure. The accessing of the
variable of a structure type that
are nested inside another
structure in the same way as
accessing other member of that
structure.

Dept. of CSE, JNNCE, Shivamogga

Downloaded by Tulasi M. R Tulasi ([email protected])


lOMoARcPSD|50231097

Data Structures and Applications [ BCS304]-3 Sem A Section Sankhya N Nayak


-------------------------------------------------------------------------------------------------------------------------------------

2. The complete definition of a


structure is placed inside the
definition of another structure.

SELF-REFERENTIAL STRUCTURES
A self-referential structure is one in which one or more of its components is a pointer to itself. Self-
referential structures usually require dynamic storage management routines (malloc and free) to
explicitly obtain and release memory.

Each instance of the structure list will have two components data and link.
• Data: is a single character,
• Link: link is a pointer to a list structure. The value of link is either the address in memory
of an instance of list or the null pointer.
Consider these statements, which create three structures and assign values to their respective
fields:
list item1, item2, item3;
item1.data = 'a';
item2.data = 'b';
item3.data = 'c';
item1.link = item2.1ink = item3.link =
NULL;

Structures item1, item2 and item3 each contain the data item a, b, and c respectively, and the null
pointer. These structures can be attached together by replacing the null link field in item 2 with one
that points to item 3 and by replacing the null link field in item 1 with one that points to item 2.
item1.link = &item2;
item2.1ink = &item3;

Dept. of CSE, JNNCE, Shivamogga

Downloaded by Tulasi M. R Tulasi ([email protected])


lOMoARcPSD|50231097

Data Structures and Applications [ BCS304]-3 Sem A Section Sankhya N Nayak


-------------------------------------------------------------------------------------------------------------------------------------

UNIONS:
A union is similar to a structure, it is collection of data similar data type or dissimilar. A union
declaration is like a structure, but the fields of a union must share their memory space. This means
that only one field of the union is "active" at any given time.

Union Declaration:
union{
char name;
int age;
float salary;
}u;
The major difference between a union and a structure is that unlike structure members which are
stored in separate memory locations, all the members of union must share the same memory
space. This means that only one field of the union is "active" at any given time.

Output:
Enter name: Albert
Enter salary: 45678.90
Displaying
Name: f%gupad (Garbage Value)
Salary: 45678.90

Array of Structures in C There can be array of structures in C programming to store many information
of different data types. The array of structures is also known as collection of structures.
Syntax for declaring structure array Ex:
struct struct-name #include<stdio.h>
{ struct student {
datatype var1; int rollno;
---------- char name[10];
datatype varN;
};
};
struct struct-name obj [ size ];
Dept. of CSE, JNNCE, Shivamogga

Downloaded by Tulasi M. R Tulasi ([email protected])


lOMoARcPSD|50231097

Data Structures and Applications [ BCS304]-3 Sem A Section Sankhya N Nayak


-------------------------------------------------------------------------------------------------------------------------------------

The example of structure with array that stores information of 3 students and displays the result.
void main()
{
int i;
struct student st[3];
printf("Enter Records of 3 students");

EXAMPLE FOR ARRAY WITHIN STRUCTURE

In the example, user created an


array Marks[] inside structure
representing 3 marks of a single
student. Marks[ ] is now a member
of structure student and to access
Marks[ ] user used dot operator(.)
along with object S.

Dept. of CSE, JNNCE, Shivamogga

Downloaded by Tulasi M. R Tulasi ([email protected])


lOMoARcPSD|50231097

Data Structures and Applications [ BCS304]-3 Sem A Section Sankhya N Nayak


-------------------------------------------------------------------------------------------------------------------------------------

POINTERS
A pointer is a variable which contains the address in memory of another variable.
The two most important operator used with the pointer type are
& - The unary operator & which gives the address of a variable
* - The indirection or dereference operator gives the content of the object pointed to by a pointer.
Declaration
int i, *pi; // Here, i is the integer variable and pi are a pointer to an integer
pi = &i; // Here, &i returns the address of i and assigns it as the value of pi

Null Pointer
• The null pointer points to no object or function.
• The null pointer is represented by the integer 0.
The null pointer can be used in relational expression, where it is interpreted as false.
Ex: if (pi = = NULL) or if (!pi)
EX:
#include<stdio.h
>
void main()
{
int a = 3;
int *ptr;
ptr = &a;
}

Ex:
#include<stdio.h> Point Variable 'a' Variable Variable 'pptr'
void main() 'ptr'
{ Name of Variable a ptr pptr
int a = 3; Type of Value that it Integer Address of Address of 'ptr'
int holds 'a'
*ptr,**pptr; Value Stored 3 2001 4001
ptr = &a; Address of Variable 2001 4001 6001
pptr = &ptr;
}

Dept. of CSE, JNNCE, Shivamogga

Downloaded by Tulasi M. R Tulasi ([email protected])


lOMoARcPSD|50231097

Data Structures and Applications [ BCS304]-3 Sem A Section Sankhya N Nayak


-------------------------------------------------------------------------------------------------------------------------------------

Pointer can be very dangerous if they are misused.


The pointers are dangerous in following situations:
1. Pointer can be dangerous when an attempt is made to access an area of memory that is either
out of range of program or that does not contain a pointer reference to a legitimate object.
Ex: main ()
{ int *p;
int pa = 10;
p = &pa;
printf(“%d”, *p); //output = 10;
printf(“%d”, *(p+1)); //accessing memory which is out of range
}
2. It is dangerous if a NULL pointer is de-referenced, because on some computer it may return
0 and permitting execution to continue, or it may return the result stored in location zero, so
it may produce a serious error.
3. Pointer is dangerous when use of explicit type casts in converting between pointer types
Ex: pi = malloc (sizeof (int));
pf = (float*) pi;
4. In some system, pointers have the same size as type int, since int is the default type specifier,
some programmers omit the return type when defining a function. The return type defaults
to int which can later be interpreted as a pointer. This has proven to be a dangerous practice
on some computer and the programmer is made to define explicit types for functions.
Pointers to Pointers
A variable which contains address of a pointer variable is called pointer-to-pointer.

DYNAMICALLY ALLOCATED ARRAYS


One Dimensional Array
While writing computer programs, if finds ourselves in a situation where we cannot determine how
large an array to use, then a good solution to this problem is to defer this decision to run time.
Example: int i, n, *list;
printf(“Enter the number of numbers to generate:”);
scanf(“%d”, &n);
if(n<1)
{ fprintf (stderr, “Improper value of n \n”);
exit(EXIT_FAILURE);
}
list=(int *)malloc ( n*sizeof(int));
Dept. of CSE, JNNCE, Shivamogga

Downloaded by Tulasi M. R Tulasi ([email protected])


lOMoARcPSD|50231097

Data Structures and Applications [ BCS304]-3 Sem A Section Sankhya N Nayak


-------------------------------------------------------------------------------------------------------------------------------------

Two Dimensional Arrays


C uses array-of-arrays representation to represent a multidimensional array. The two-dimensional
arrays is represented as a one-dimensional array in which each element is itself a one-dimensional
array.

Creation of Two-Dimensional Array Dynamically


int **myArray;
myArray = make2dArray(5,10);
myArray[2][4]=6;

int ** make2dArray(int rows, int cols)


{ /* create a two dimensional rows X cols array */
int **x, i;
x=(int *)malloc( rows * sizeof (*x)); /*get memory for row pointers*/
for (i= 0;i<rows; i++) /* get memory for each row */
x[i]=(int**)malloc(cols * sizeof(**x));
return x;
}
The second line allocates memory for a 5 by 10 two-dimensional array of integers and the third line
assigns the value 6 to the [2][4] element of this array.

POLYNOMIALS
“A polynomial is a sum of terms, where each term has a form axe, where x is the variable, a is the
coefficient and e is the exponent.”

The largest exponent of a polynomial is called its degree. Coefficients that are zero are not displayed.
The term with exponent equal to zero does not show the variable since x raised to a power of zero is
1.
Assume there are two polynomials,

Polynomial Representation
One way to represent polynomials in C is to use typedef to create the type polynomial as below:

Dept. of CSE, JNNCE, Shivamogga

Downloaded by Tulasi M. R Tulasi ([email protected])


lOMoARcPSD|50231097

Data Structures and Applications [ BCS304]-3 Sem A Section Sankhya N Nayak


-------------------------------------------------------------------------------------------------------------------------------------

To preserve space an alternate representation that uses only one global array, terms to store all
polynomials.
The C declarations needed are:

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.

Dept. of CSE, JNNCE, Shivamogga

Downloaded by Tulasi M. R Tulasi ([email protected])


lOMoARcPSD|50231097

Data Structures and Applications [ BCS304]-3 Sem A Section Sankhya N Nayak


-------------------------------------------------------------------------------------------------------------------------------------

• 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

Dept. of CSE, JNNCE, Shivamogga

Downloaded by Tulasi M. R Tulasi ([email protected])


lOMoARcPSD|50231097

Data Structures and Applications [ BCS304]-3 Sem A Section Sankhya N Nayak


-------------------------------------------------------------------------------------------------------------------------------------

What is Sparse Matrix?


A matrix which contains many zero entries or very few non-zero entries is called as Sparse matrix.
In the figure B contains only 8 of 36 elements are nonzero and that is sparse.

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 1,000,000
elements. The better choice is by using a representation in which only the nonzero elements are
stored.

Sparse Matrix Representation


• An element within a matrix can characterize by using the triple <row, col, value> This means
that, an array of triples is used to represent a sparse matrix.
• 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.

The figure shows the representation of matrix in the array “a”.


a[0].row contains the number of rows,
a[0].col contains the number of columns
and a[0].value contains the total number of nonzero entries.
• 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.

Dept. of CSE, JNNCE, Shivamogga

Downloaded by Tulasi M. R Tulasi ([email protected])


lOMoARcPSD|50231097

Data Structures and Applications [ BCS304]-3 Sem A Section Sankhya N Nayak


-------------------------------------------------------------------------------------------------------------------------------------

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 that precede
it.
This can be avoided by using the column indices to determine the placement of elements in the
transpose matrix. This suggests the following algorithm:

The columns within each row of the transpose matrix will be arranged in ascending order.

Dept. of CSE, JNNCE, Shivamogga

Downloaded by Tulasi M. R Tulasi ([email protected])


lOMoARcPSD|50231097

Data Structures and Applications [ BCS304]-3 Sem A Section Sankhya N Nayak


-------------------------------------------------------------------------------------------------------------------------------------

STRINGS:
A string is a collection/sequence of characters, stored in an array followed by null ('\0') character with
in an double quotes. Null character represents the end of string.

Declaration of String or Character array Declaration of array means creating sequential blocks of
memory to hold fixed number of values. Syntax for string declaration: char String-name[size of String
]; Note: Strings can also be declared using pointer.

Declaration of String or Character array Declaration of array means creating sequential blocks of
memory to hold fixed number of values.
Syntax for string declaration: char String-name[size of String ];
Example : char Str [25]; //Statement 1 In the above example user declared a character array which
can hold twenty-five characters at a time.

Note: Strings can also be declared using pointer.


char *str ; // Memory can be allocated dynamically
Note: The difference between scanf and gets is, scanf can read strings which does not contain any
white spaces. Whereas gets can read strings both without spaces and with spaces.

C provides predefined functions for performing all the above operations or manipulations on
strings. Most of these predefined functions are available in string.h header file.

FUNCTION SYNTAX and EXAMPLE

strcat( ) :
The strcat predefined
function is used to
concatenate/join two
strings together.

Dept. of CSE, JNNCE, Shivamogga

Downloaded by Tulasi M. R Tulasi ([email protected])


lOMoARcPSD|50231097

Data Structures and Applications [ BCS304]-3 Sem A Section Sankhya N Nayak


-------------------------------------------------------------------------------------------------------------------------------------

strcmp( ) : used to
compare two strings.
If the two strings are
equal, then the function
returns a 0.
If the first string comes
before the second string in
alphabetical order, the
function returns a -1.
If the first string comes
after the second string in
alphabetical order, the
function returns a 1 as the
return value.

strcpy( ): copy one string


into another string.

strlen( ):
The strlen function is used to
retrieve the length of a given
string. The return type of this
function will be an integer.
Length=5
strtstr( ) : returns a
character pointer of the first
occurrence of the given
substring in the string. If the
substring is not found in the
string, the
function strstr returns NULL

Dept. of CSE, JNNCE, Shivamogga

Downloaded by Tulasi M. R Tulasi ([email protected])


lOMoARcPSD|50231097

Data Structures and Applications [ BCS304]-3 Sem A Section Sankhya N Nayak


-------------------------------------------------------------------------------------------------------------------------------------

strrev( ):
The strrev function is used to
reverse a given string.

Other predefined functions

Some of the other predefined functions available in the string.h header file are shown in the below table:

Function Purpose Syntax


strncat To concatenate n number of left most characters strncat(str1, str2, n)
strncmp To compare n number of left most characters strncmp(str1, str2, n)
strncpy To copy n number of left most characters strncpy(str1, str2, n)

STACKS
“A stack is an ordered list in which insertions (pushes) and deletions (pops) are made at one end
called the top.”

• The elements are added in the stack in the order 10,20,30, 40,50, then 50 is the first element
that is deleted from the stack and the last element is deleted from stack is 10.
• Since the last element inserted into a stack is the first element removed, a stack is also known
as a Last-In-First-Out (LIFO) list.

ARRAY REPRESENTATION OF STACKS


• Stacks may be represented in the computer in various ways such as one-way linked list (Singly
linked list) or linear array.
• Stacks are maintained by the two variables such as TOP and MAX_STACK_SIZE.
• TOP which contains the location of the top element in the stack. If TOP= -1, then it indicates
stack is empty.

Dept. of CSE, JNNCE, Shivamogga

Downloaded by Tulasi M. R Tulasi ([email protected])


lOMoARcPSD|50231097

Data Structures and Applications [ BCS304]-3 Sem A Section Sankhya N Nayak


-------------------------------------------------------------------------------------------------------------------------------------

• MAX_STACK_SIZE which gives maximum number of elements that can be stored in stack.

STACK OPERATIONS
1. push : Adds an element to the top of the stack.
2. pop : Removes the topmost element from the stack.
3. isEmpty : Checks whether the stack is empty.
4. isFull : Checks whether the stack is full.

/* Declarations */
int stack[100], top=-1, max; Assume max=5;
Demonstration of isfull and Push
Operation
void push(int ele)
{
if( top == max-1 )
printf("\n Stack OVERFLOW :");
else
stack[++top] = ele;
}

Demonstration of isempty and Pop


Operation
int pop()
{ int ele;
if( top == -1 )
{
printf("\n Stack is UNDERFLOW");
return -1;
}
else
{ ele= stack [top];
top--;
return(ele) ;
}
}
Dept. of CSE, JNNCE, Shivamogga

Downloaded by Tulasi M. R Tulasi ([email protected])


lOMoARcPSD|50231097

Data Structures and Applications [ BCS304]-3 Sem A Section Sankhya N Nayak


-------------------------------------------------------------------------------------------------------------------------------------

Display Function
void disp()
{
int i;
if(top==-1)
printf("\n No elements in the Stack ");
else
{
printf("\n The Contents of the stack are \n ");
for( i=top ; i>=0 ; i-- )
printf("%d\n",stack[i]);
}
}

STACKS USING DYNAMIC ARRAYS

The array is used to implement stack, but the bound (MAX_STACK_SIZE) should be known during
compile time. The size of bound is impossible to alter during compilation hence this can be overcome
by using dynamically allocated array for the elements and then increasing the size of array as needed.

Dept. of CSE, JNNCE, Shivamogga

Downloaded by Tulasi M. R Tulasi ([email protected])


lOMoARcPSD|50231097

Data Structures and Applications [ BCS304]-3 Sem A Section Sankhya N Nayak


-------------------------------------------------------------------------------------------------------------------------------------

The new code shown below, attempts to increase the capacity of the array stack so that new
element can be added into the stack. Before increasing the capacity of an array, decide what the new
capacity should be.
In array doubling, array capacity is doubled whenever it becomes necessary to increase the capacity
of an array.

---------------------------------------------------------------------------------------------------------------------
STACK APPLICATIONS
Expressions: It is sequence of operators and operands that reduces to a single value after evaluation
is called an expression.
X=a/b–c+d*e–a*c
In above expression contains operators (+, –, /, *) operands (a, b, c, d, e).
Expression can be represented in in different format such as
• Prefix Expression or Polish notation
• Infix Expression
• Postfix Expression or Reverse Polish notation
Infix Expression: In this expression, the binary operator is placed in-between the operand. The
expression can be parenthesized or un- parenthesized.
Example: A + B

Prefix or Polish Expression: In this expression, the operator appears before its operand.
Example: + A B

Postfix or Reverse Polish Expression: In this expression, the operator appears after its operand.
Example: A B +

Precedence of the operators


The first problem with understanding the meaning of expressions and statements is finding out the
order in which the operations are performed.

Dept. of CSE, JNNCE, Shivamogga

Downloaded by Tulasi M. R Tulasi ([email protected])


lOMoARcPSD|50231097

Data Structures and Applications [ BCS304]-3 Sem A Section Sankhya N Nayak


-------------------------------------------------------------------------------------------------------------------------------------

Example: assume that a =4, b =c =2, d =e =3 in below expression

Infix Expression: A+ (B*C-(D/E^F)*G)*H, where ^ is an exponential operator.

Resultant Postfix Expression: ABC*DEF^/G*-H*+

Advantage of Postfix Expression over Infix Expression


An infix expression is difficult for the machine to know and keep track of precedence of operators.
On the other hand, a postfix expression itself determines the precedence of operators (as the
placement of operators in a postfix expression depends upon its precedence).Therefore, for the
machine it is easier to carry out a postfix expression than an infix expression.

Algorithm infix to postfix.


start
1. Scan the infix expression from left to right.
2. REPEAT steps 2-6 until infix expression is scanned.
3. IF the scanned character is an operand THEN output it
4. ELSE
3.1 IF the precedence of the scanned operator is greater than the precedence of the operator
in the stack(or the stack is empty or the stack contains a ‘(‘ ), THEN push it.
4.2 ELSE Pop all the operators from the stack which are greater than or equal to in
precedence than that of the scanned operator.
4.3 After doing that Push the scanned operator to the stack. (If you encounter parenthesis
while popping then stop there and push the scanned operator in the stack.).
5. IF the scanned character is an ‘(‘, THEN push it to the stack.
Dept. of CSE, JNNCE, Shivamogga

Downloaded by Tulasi M. R Tulasi ([email protected])


lOMoARcPSD|50231097

Data Structures and Applications [ BCS304]-3 Sem A Section Sankhya N Nayak


-------------------------------------------------------------------------------------------------------------------------------------

6. IF the scanned character is an ‘)’, THEN pop the stack and and output it until a ‘(‘ is
encountered, and discard both the parenthesis.
7. Print the output
8. Pop and output from the stack until it is not empty.
Stop

Program

#include<stdio.h>
#include<ctype.h>

char Stack[25]; //Operator stack


int top=-1;

void push(char ele) char pop()


{ { if(top==-1)
Stack[++top] = ele; return -1;
} else
return(Stack [top--]);
}
int stack_priority(char x) int sym_priority(char x)
{ if(x== '#') { if(x== '(')
return -1; return 9;
if(x== '(') if(x=='+'||x=='-')
return 0; return 1;
if(x=='+'||x=='-') if(x=='*'||x=='/'||x=='%')
return 2; return 3;
if(x=='*'||x=='/'||x=='%') if(x=='^' ||x=='$’)
return 4; return 6;
if(x=='^' ||x=='$’) }
return 5;
}
void main()
{
char Infix20],sym,x;
int i;
printf("\n\n\t\tEnter the Valid Infix Expression: ");
scanf("%s",Infix);

push(‘#’);

printf(“\n The postfix expression is :”);

Dept. of CSE, JNNCE, Shivamogga

Downloaded by Tulasi M. R Tulasi ([email protected])


lOMoARcPSD|50231097

Data Structures and Applications [ BCS304]-3 Sem A Section Sankhya N Nayak


-------------------------------------------------------------------------------------------------------------------------------------

for(i=0; Infix[i] !=’\0’;i++)


{
sym=Infix[i];
if(isalnum(sym))
printf(‘%c”,Infix[i]);
else if(sym==’(‘)
push(sym);
else if(sym==’)‘)
{
while((x==pop()) != ‘(‘)
printf(‘%c”,x);
}
else
{
while((stack_priority(Stack[top])>=sym_priority(sym))
printf(‘%c”,pop());
push(sym);
}
} //end of while

while(top != 0)
printf(‘%c”,pop());
}
-------------------------------------------------------------------------------------------------------------------------

EVALUATION OF POSTFIX(SUFFIX) EXPRESSIONS USING STACK


As discussed in Infix To Postfix Conversion Using Stack, the compiler finds it convenient to evaluate
an expression in its postfix form. The virtues of postfix form include elimination of parentheses which
signify priority of evaluation and the elimination of the need to observe rules of hierarchy,
precedence, and associativity during evaluation of the expression.
As Postfix expression is without parenthesis and can be evaluated as two operands and an operator
at a time, this becomes easier for the compiler and the computer to handle.
Dept. of CSE, JNNCE, Shivamogga

Downloaded by Tulasi M. R Tulasi ([email protected])


lOMoARcPSD|50231097

Data Structures and Applications [ BCS304]-3 Sem A Section Sankhya N Nayak


-------------------------------------------------------------------------------------------------------------------------------------

Evaluation rule of a Postfix Expression states:


1. While reading the expression from left to right, push the element in the stack if it is an operand.
2. Pop the two operands from the stack, if the element is an operator and then evaluate it.
3. Push back the result of the evaluation. Repeat it till the end of the expression.
Example : Expression: 456*+

Program void evaluate()


#include<math.h> {
#include<ctype.h> int i;
#include<stdio.h> for ( i=0 ; suffix[i] !=’\0’ ; i++ )
{
int top = -1 ; symbol=suffix[i];
int res, op1, op2, s[25]; if ( isdigit ( symbol ) )
char symbol, suffix[25]; s[++top]=symbol-'0';
else
int compute(int op1, char symbol , int op2) { op2 = s[top--];
{ switch(symbol) op1 = s[top--];
{ res = compute( op1 ,symbol, op2 );
case '+' : return(op1 + op2 ); s[++top]=res;
case '-' : return(op1 - op2 ); }
case '*' : return(op1 * op2 ); }//end of for
case '/' : return(op1 / op2 ); if(top ==0)
case '%' : return( (int)op1 % (int)op2); printf(" \n The Result is=%lf",s[top]);
case '^' : return( pow ( op1 , op2 )); else
} printf(" \nWrong expression");
} }
void main()
{
printf(" \n\n Enter the valid Suffix expression\n");
scanf("%s",suffix);
evaluate();
}
Dept. of CSE, JNNCE, Shivamogga

Downloaded by Tulasi M. R Tulasi ([email protected])


lOMoARcPSD|50231097

Data Structures and Applications [ BCS304]-3 Sem A Section Sankhya N Nayak


-------------------------------------------------------------------------------------------------------------------------------------

Dept. of CSE, JNNCE, Shivamogga

Downloaded by Tulasi M. R Tulasi ([email protected])

You might also like