Dsa Module 1
Dsa Module 1
MODULE 1: INTRODUCTION
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
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.
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.
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'
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);
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
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
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
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.
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
comparison can be done in the following way in older versions of C using following method.
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;
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
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");
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;
}
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:
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.
• 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
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.
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.
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.
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.
strcat( ) :
The strcat predefined
function is used to
concatenate/join two
strings together.
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.
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
strrev( ):
The strrev function is used to
reverse a given string.
Some of the other predefined functions available in the string.h header file are shown in the below table:
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.
• 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;
}
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]);
}
}
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.
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 +
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>
push(‘#’);
while(top != 0)
printf(‘%c”,pop());
}
-------------------------------------------------------------------------------------------------------------------------