0% found this document useful (0 votes)
17 views47 pages

Ds Module 1 Notes 2020

Uploaded by

VIJAY C P IS&E
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)
17 views47 pages

Ds Module 1 Notes 2020

Uploaded by

VIJAY C P IS&E
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/ 47

1

What is data structure?


Data structure is a particular way of organizing data in a computer, so that it can be accessed and
modified efficiently.

Why data structure is used?


Data is stored, so that it can be used in future. When we store data, we should make sure that, it can be
retrieved easily whenever we need it. Hence make use of appropriate data structure to store & retrieve the
data efficiently.

Classification of data structure:

Primitive & Non Primitive data structures:


• Primitive: basic data types that are available in most of the programming
languages.
• Represent single values.
• Predefined or built-in type : example, int, float, char
• Non-Primitive: The data types that are derived from primary data types are
known as non-Primitive data types.
Store group of values
Linear data structure: traverses the data elements sequentially
 in which only one data element can directly be reached.
 Ex: Arrays, Linked Lists, stacks ,Queues
2

Non-Linear data structure: Every data item is attached to several other


data items in a way that is specific for reflecting relationships. Elements are not
stored in sequential order.
 Ex: Trees, Graphs

Operations that can be performed on data structures:

1. Create

2. Traversal

3. Search

4. Insertion

5. Deletion

6. Sorting

1. Create: Creating new record with set of values

2. Traversal- The process of accessing each data item of a record exactly once.

3. Search- Finding a required data in existing record.

4. Insertion- adding a new data item in the given collection of data items.

5. Deletion- deleting an existing data item from the given collection of data items.

6. Sorting- arranging the data items in some order i.e. in ascending or descending order in
case of numerical data and in dictionary order in case of alphanumeric data.

Review of Arrays:

In C programming, one of the frequently arising problems is to handle similar types of data. For
example, if the user wants to store marks of 100 students. This can be done by creating 100
variables individually but, this process is rather tedious and impracticable. This type of problem
can be handled in C programming using arrays.
3

An array is a sequence of data item of homogeneous value (same type).


Arrays are of two types: One-dimensional arrays, Multidimensional arrays
Declaration of one-dimensional array[Linear Arrays]: data_type array_name [array_size];
For example: int LA[5];
Here, the name of array is LA. The size of array is 5, i.e., there are 5 items (elements) of array
age. All elements in an array are of the same type (int, in this case).
Array elements
Size of array defines the number of elements in an array. Each element of array can be accessed
and used by user according to the need of program.
For example: int LA[3];
200
LA[0]
201 (2 bytes)
203
LA[1]
203
204
LA[2]
205

Each cell of one bytes and two cells for each element
Note that, the first element is numbered 0 and so on. That means array indexing always starts
from 0 to n-1.(but in some it is 1)
Here, the size of array is 5 times the size of int because there are 5 elements.
Suppose, the starting address of the array LA[0] is 2120d and the size of int be 4 bytes. Then, the
address of next location (address of a[1]) will be 2124d, address of a[2] will be 2128d and so on.
Initialization of one-dimensional array
Arrays can be initialized at declaration time
as: int LA[3]={2,4,34};
It is not necessary to define the size of arrays during initialization. Below instruction justifies it.
int LA[]={2,4,34};
In this case, the compiler determines the size of array by calculating the number of elements
of an array
200
2 LA[0]
201 (2 bytes)
203
4 LA[1]
204
205
34 LA[2]
206
4

Five consecutive memory allocation are allotted and each location is large enough to hold a single
integer .

The address of the first element LA[0], is called base address ,LA->Linear Array

Suppose address of first location is 1000

i.e address of LA[0]=1000.

&LA[1]=1002 =100+2=1000+(1*2). Or LOC(LA[1])= 1000+2(1-0)=1002

&LA[2]=1004=1000+4=1000(2*2). Or LOC(LA[2])= 1000+2(2-0)=1004

&LA[3]=1006=1000+6=1000+(3*2), or Or LOC(LA[2])= 1000+2(3-0)=1006

&LA[4]=1008=1000+8=1000+(4*2). Or LOC(LA[1])= 1000+2(4-0)=1008

Therefore, if base address is α ,then the formula to calculate the address of the ith location is given as
follows. Base_address+(index* sizeof(datatype));

Or α+ (index*sizeof(datatype)) or
LOC(LA[k])=Base(LA)+w(K-Lower bound) where w is no.of words
for each cell,k is index and lower bound is 0
Accessing array elements
In C programming, arrays can be accessed and treated like variables in C. For
example:
scanf("%d", &LA[2]); // statement to insert value in the third position of array LA
scanf("%d", &LA[i]); // statement to insert value in ith position of array LA
printf("%d", LA[0]); // statement to print first element of an array LA
printf("%d", LA[i]); // statement to print ith element of an array LA

Array operations:
1. Traversing
2. Searching
3. Sorting
4. insert
5. delete
5

1.searching:
It is a process of finding the location of element ( element to be search) in the array.
Some searching techniques are,
1. Linear searching
2. Binary search
1. Linear search:
In this technique the element is searched sequentially. Key element is compared with every
element of an array till the end of the array ,if the key element is matched before reaching the
end of the array ,process get terminated.
Algorithm:
Searching a key element by comparing each element of an array with key element
Algorithm: LINEAR(LA[],key,n,i,flag)( if the flag value is set to 1 it means element is found
,otherwise element is not found)
1. [initialize flag] flag=0.
5 6 8 2 7 9
2. repeat for i=0 to i<n if LA[i]=key
If key=2
Set flag:=1;
[end of loop ] Algorithms search for the key element 2 linearly (sequentially)
3. if flag=1 by comparing key element with every element of the array.
write: "successful”. If key element matches with element of array it returns the
else position of the element otherwise it prints unsuccessful.
write: "unsuccessful”.
4. exit. In the example when it compares key element with the
element having index 3 it founds that both are same and it
C-Function for linear search
returns as successful.
void linear(int LA[],int n,int key)
{
int flag=0,i;
for(i=0;i<n;i++)
{
if(LA[i]==key)
flag=1
}
if(flag==1)
printf(“successful”)
else
printf(“unsuccessful”)
}
6

Binar Search:
When an array sorted in increasing order or equivalently, alphabetically .Then there is an
extremely efficient searching algorithm, called binary search, which can be used to find the
position of the element in the array.
In this method key element is searched by dividing the array in to two halves.
Example: if LA is an array which will be divide in to two halves by finding the mid element
LA[0],LA[1]……LA[MID-1] LA[MID] ,LA[MID+1]……LA[N-1]

Algorithm: BINARY(LA,mid,Low,high,n,flag,key).
1.[initialize flag,low and high] Low=0,high=n-1,flag=0
void binarys(int LA[],int low,int mid,int high)
2. While(low<=high) {
int flag=0;
mid=(low+high)/2. low=0,high=n-1
while(low<=high)
{
if LA[mid]=key mid=(low+high)/2
if (LA[mid]==key)
write: ”successful”. And Set Flag:=1 {
printf(“successful”)
break; flag=1;
return
else if key>LA[mid] }
else if(key LA[ id])
low=mid+1;
low= id+1
else else
ig = id 1
high=mid-1; }
if(flag==0)
[while loop ends] printf(“unsuccessful”)
}
3. if flag=0
write:”unsucessful”
4. Exit
Sorting:
It is the process of arranging the elements in logical order i.e either in increasing or decreasing
order and non-numerical data in alphabetical order.
There are many sorting algorithms are available each one is different from other by the means
of time complexity and space complexity. here we discussed only two algorithms.
1. Selection sort
2. Bubble sort
7

Algorithm for selection sort:


Algorithm: Selection (LA[],n,min,i,j)
1. Repeat for i=0 to i<=n-1
2. min=i
3. Repeat for j=i+1 to j<n
4. if LA[j]<LA[min]
5. min=j;
[end of j loop]
6. swap(LA[i],LA[min],temp)
[end of i loop]
7.Exit.
Algorithm for bubblesort:
• Algorithm: BUBBLE(LA[],n.i,j)
1. Repeat for i=1 to i<=n-1
2. Repeat for j=0 to j<=n-1-i
3. if LA[j]>LA[j+1]
4. swap(LA[j],LA[j+1],temp)
[end of loop j]
[end of loop i]
5. Exit.
Note:The major difference b/w selection sort and bubble sort is calling swap process.
Selection sort algorithm calls swap process only once in every pass whereas bubble sort
calls swap process more than once in every pass.
Traversing:
• Traversing is the process of visiting each element of an array exactly once.
Algorithm: 1. [Intialize counter] Set K:=LB
2.Repeat Steps 3 and 4 while K<=UB
3. [visit element] Apply PROCESS to LA[K].
4. [increase counter] set K:=K+1.
8

[end of step 2 loop]


5. Exit.
Example:
1.Find the number of NUM years during which more than 300 automobiles were sold.[range
of year is 2000 to 2017
[where NUM is an counter variable AUTO is an array which stores details of
automobiles were sold in every year ….example AUTO[2000]=350,AUTO[2001]=320…… year is
an index of array]
1.[initialization step.] set NUM=0.
2.Repeat for K=2000 to 2017
if AUTO[K]>300 ,then: Set NUM=NUM+1.
[end of loop]
3.Return.

Insert:
It is the process of inserting a new element in a valid position of an existing
array.
1. Input a position of an array
2. Check position is valid
3. If position is valid insert new element in the specified position by shifting existing
elements to right. otherwise ask user to enter valid position.
4. Aftervoidinserting
insert() new element in the specified position increment the number of
elements
{
count i.e n=n+1
printf("enter pos\n");
scanf("%d",&pos);
if(pos n || pos<0) // c ecks position is valid or not

{
printf("invalid\n"); // if position is invalid, it ter inate t e
return;
}
printf("enter ele \n"); // if position is valid ask user to enter ite
scanf("%d",&ele );
for(i=n 1;i =pos;i ) // insert new item in to array by shifting elements to right
a[i+1]=a[i];
a[pos]=ele ;
n=n+1;
}
9

Delete:

The process of removing an element with valid position form an existing array.
1. Input a position of an array
2. Check position is valid
3. If position is valid remove that element from specified position by shifting
existing elements to left. Otherwise ask user to enter valid position.
4.After deleting element in the specified position decrement the number of elements
count i. e n=n-1

void delete()
{
printf("enter pos\n");
scanf("%d",&pos);
if(pos =n || pos<0)
{
printf("invalid position: Enter valid position\n");
return;
}
ele =a[pos];
printf("deleted ite is %d\n",ele );
for(i=pos;i<n;i++)
a[i]=a[i+1];
n=n 1;
}

Representation of two dimensional arrays:


10

Structures:
Definition of Structures: A structure is a collection of one or more variables of similar or
dissimilar data types, grouped together under a single name.i.e. A structure is a user defined type
containing multiple variable of homogeneous or heterogeneous data types. The structure is
defined using the keyword struct followed by an identifier. This identifier is called struct_tag.
The syntax and example is as follows:

Syntax for Defining Structure:


struct struct_tag
{
type var_1;
type var_2;
------------
------------
type var_n;
};

Where,
The word struct is a keyword in C
The item identified as struct_tag is called a tag and identifies the structure later in the program
Each type1, ------typen can be any data type in C including structure
The item var_1,var_2,-----var_n are the members of the structure.

Example :
11

struct student
{
char name[20];
int roll_number;
float average_marks;
};

Declaring Structure Variables: The syntax of declaring structure variables is shown below :

struct struct_tag v1,v2,v3,------vn;

Example: struct student s1,s2,s3;


The complete structure definition along with structure declaration is as shown below :

struct student
{
char name[10];
int roll_number;
float average_marks;
};
struct student cse, ise;

Structure Initialization: Assigning the values to the structure member fields is known as
structure initialization.

The syntax of initializing ,

struct struct_tag variable = { v1,v2,v3 ------- vn}; where v1,v2..vn are the values for each
member.

Example : struct student cse = {“xyz”,18, 87.5};

The complete structure definition, declaration and initialization is as shown below:

Structure Definition :
struct employee
{
char name[20];
int salary;
int id;
};
Structure Declaration
struct employee emp1,emp2;

Structure Initialization :
struct employee emp1 = {“abc”,20000,1000};
struct employee emp2 = {“xyz”,10050,200};
12

Defining Structure Data types using typedef (Type Defined Structure):


The structure defined using the keyword typedef is called type defined structure. The syntax of
the typedefined structure along with example is as given below:

Syntax:
typdef struct
{
data_type1 member1;
data_type2 member2;
----------------------
} struct_ID ;

Example :
typedef struct
{
char name[10];
int USN;
float Percentage_Marks;
} Student ;

Here Student is the new datatype using which variables can be declared like.
Student S1, S2,S3;

When structure is defined by using typedef then the structure variables are declared without
using struct keyword. But when structures are defined without using typedef ,such structure
variables should be declared with the help of struct keyword.

Variable declaration when structure defined with typedef,


Student s1,s2;

Variable declaration when structure defined without typedef,


struct Strudent s1,s2;

Nested Structures :
A structure can be a member of another structure. This is called a nested structure .i.e. A
structure which includes another structure is called nested structure.
Example: Consider the structure date which includes the details like date,month and year

struct date
{
int dd;
int mm;
int yyyy;
};
13

The above structure date can be nested in the structure say Employee as follows:

struct Employee
{
char empname[20];
int empid;
float salary;
struct date date_of_joining;
};
In the above example the structure date is nested within the structure Employee .In order to
access the member of the structure date, first we need to create a variable of Employee structure.
struct Employee E1;
Now we can access member of date structure as follows:
E1.date_of_joining.dd =20;
E1.date_of_joining.mm=3

Structure and Functions: Just like the way normal variables can be passed to the functions
it is possible to pass even structure variables to functions. Structure variable can be passed to
functions using two techniques:

1. Pass by value
2. Pass by Reference

1. Passing structure by value: A structure variable can be passed to the function as an argument
just like normal variables are passed to functions. Consider the following example :

#include<stdio.h>
#include<conio.h>
void disp (struct student stu);
struct student
{
char name[50];
int usn;
};

void main()
{
struct student s1;
clrscr();
printf(“\n Enter student name \n‖);
scanf(“%s”,s1.name);
printf(“\n Enter student usn\n‖);
scanf(“%d”,&s1.usn);
disp(s1);
getch();
}
void disp(struct student stu)
{
14

Printf(“nName is %s\n”,stu.name);
printf(“\n USN is %d\n”,stu.usn);
}
As illustrated in the above example the structure variable s1 is passed as an argument of disp(s1)
function. The value of the members variables are displayed in disp(struct student stu) function.

2. Passing Structures by Reference: It is also possible to pass structures by references just like
normal variables are passed by references. In case of pass by reference the address of the
structure is passed . When the address is passed , pointer should collect the address .
To access the member of a structure , arrow operator (->) should be used. If structure is passed
by reference , change made in structure variable in function definition reflects in original
structure variable in the calling function as illustrated in the example below :

#include<stdio.h>
#include<conio.h>
void display (struct student *stu);
struct student
{
char name[50];
int marks;
};
void main()
{
struct student s1;
clrscr( );
printf(“\n Enter the student name:\n”);
scanf(“%s”,s1.name);
printf(“\nEnter Marks:”);
scanf(“%d”,&s1.marks);
disp(&s1);
printf(“\n In main Function\n”);
printf(“\n Name is %s \n”,s1.name);
printf(“\n USN is : %d\n”,s1.marks);

}
void disp(struct student *stu)
{
stu->usn=30;
strcpy(s1->name,”hi”);
printf(“\n In Display Function\n”);
printf(“\Name is : %s\n”,stu->name);
printf(“\n USN is : %d\n”,stu->Marks);
}
15

SELF REFRENTIAL STRUCTURES

A self referential data structure is essentially a structure definition which includes at least one
member that is a pointer to the structure of its own kind. A chain of such structures can thus be
expressed as follows.

struct name
{
member 1;
member 2;
...
struct name *pointer;
};

The above illustrated structure prototype describes one node that comprises of two logical
segments. One of them stores data/information and the other one is a pointer indicating where the
next component can be found. .Several such inter-connected nodes create a chain of structures.

The following figure depicts the composition of such a node. The figure is a simplified
illustration of nodes that collectively form a chain of structures or linked list.

Such self-referential structures are very useful in applications that involve linked data structures,
such as lists and trees. Unlike a static data structure such as array where the number of elements
that can be inserted in the array is limited by the size of the array, a self-referential structure can
dynamically be expanded or contracted. Operations like insertion or deletion of nodes in a self-
referential structure involve simple and straight forward alteration of pointers.

Example:

struct node Address Address 40 NULL


20 30
{ of node2 of node3
int data; node3
struct node *link; node1 node2 node3
}node1, node2,node3;
node1.data=20,node2.data=30,node3.data=40;
node1.link=node2.link;
node2.link=node3.link;
node3.link=NULL;

OR
struct node
16

{
int data;
struct node *link;
} *n1,*n2,*n3;

n1->data=20,n2->data=30,n3->data=40;
n1->link=n2;
n2->link=n3;
n3->link=NULL

Unions:
A union is a special data type available in C that enables to store different types in same memory
location
We can define a union with many members, but only one member can contain a value at any
given time.
Syntax:
union tagname
{
type var1;
type var2;
-
-
};
Example:
Union gender
{
int male;
int female;
};
In the above example either male or female can be active at a time, but both cannot be active
at the same time.
Defining union variables and accessing a union member is same as structures
Unions can also be defined as nested unions
Example:
#include <stdio.h>
#include <string.h>
17

union Data
{
int i; float f; char str[20];
};
int main( )
{
union Data data;
data.i = 10; data.f = 220.5;
strcpy( data.str, "C Programming");
printf( "data.i : %d\n", data.i);
printf( "data.f : %f\n", data.f);
printf( "data.str : %s\n", data.str);
return 0;
}
Output:

data.i : 1917853763
data.f : 412236058032779486045368.000000 Only one member i.e. str is
data.str : C Programming
isactive(which active(which is the largest member)
18

Difference b/w Structure and Union

Structure Union
Structure declaration starts with keyword Union declaration starts with keyword union
Struct
Structure reserves memory for each data Union reserves memory i.e., equal to maximum
member separately data member size amongst all.
Any data member can be accessed at Only one data member can be accessed at a
any time Time
Ex: struct Book{ Ex: union Book{
int isbn; int isbn;
float price; float price;
char title[20]; char title[20];
}book; }book;
Total memory reserved will be Total memory reserved will be
sizeof(int)+sizeof(flaot)+(20*sizeof(char) Max(sizeof(int),sizeof(float),(20*sizeof(char))
19

POINTERS:
• Variable used to store the address of another variable
Declaration : datatype *ptr_identifier;
Ex: int *pi,*ptr;
Operators used : & address operator
* dereferencing pointer
Initialization : int a,*p; or int a;
p=&a; int *p=&a;
a=10,b=20
*pa=&a , *pb=&b
Address of a= 1000 Value of a = 10
Address of b= 1002 Value of b =20
printf(“%d%d%d%d”,*pa,*pb,pa,pb); output: 10 20 1000 1002
Pointer may contain the address of another pointer as well(Double pointer)
int *a;
int b;
int **c;
b=5; a=&b; c=&a;//pointer c contains address of a which is a pointer

operations on pointers
int *p,*q;
1.a pointer can be assigned to another pointer
2.Arithmatic operation like addition,division,multiplication are not allowed b/w pointers,but
substraction is possible.(p*q, p+q, p/q are illegal but p-q is legal)
3.pointer can be added with constant,( p+2 is valid p*2,P/2 are not valid)
3.pointers can be converted to integers explicitly.(int *)p
20

Dynamic Memory Management Functions:


The exact size of an array is unknown until the compile time, i.e., time when a compiler compiles code
written in a programming language into an executable form. The size of array you have declared initially
can be sometimes insufficient and sometimes more than required. Dynamic memory allocation allows
a programmer to obtain more memory space, while running or to release space when no space is
required.
Although, C language inherently does not have any technique to allocate memory dynamically, there
are 4 library functions under "stdlib.h" for dynamic memory allocation.

int *ptr;

malloc(): The name malloc stands for "memory allocation". The function malloc()reserves a block of
memory of specified size and return a pointer of type void which can be casted into pointer of any form.

Syntax of malloc():- ptr=(cast-type*)malloc(n*sizeof(data))

Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of memory with size
of byte size. If the space is insufficient, allocation fails and returns NULL pointer.

ptr=(int*)malloc(100*sizeof(int));

This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes respectively and the
pointer points to the address of first byte of memory.

calloc(): The name calloc stands for "contiguous allocation". The only difference between malloc() and
calloc() is that, malloc() allocates single block of memory whereas calloc() allocates multiple blocks of
memory each of same size.

Syntax of calloc():

ptr=(cast-type*)calloc(n,sizeof(data));

This statement will allocate contiguous space in memory for an array of n elements. For
example:

ptr=(float*)calloc(25,sizeof(float));

This statement allocates contiguous space in memory for an array of 25 elements each of size of
float, i.e, 4 bytes.

Note: The difference b/w malloc and calloc is,calloc initialize all the memory locations to zero but
malloc doesn’t initialize any memory location.
21

realloc(): The C library function void *realloc(void *ptr, size_t size) attempts to resize the memory
block pointed to by ptr that was previously allocated with a call to malloc or calloc.

Declaration
Following is the declaration for realloc() function.

void *realloc(void *ptr, size_t size)

Parameters
 ptr -- This is the pointer to a memory block previously allocated with malloc, calloc or realloc to
be reallocated. If this is NULL, a new block is allocated and a pointer to it is returned by the
function. 

 size -- This is the new size for the memory block, in bytes. If it is 0 and ptr points to an existing
block of memory, the memory block pointed by ptr is deallocated and a NULL pointer is returned. 

This function returns a pointer to the newly allocated memory, or NULL if the request fails.

ptr=(int *)realloc(ptr,200)// if previously allocated memory is lesser than 200 bytes then it allocates
remaining(200-previously allocated memory)bytes

free(); it deallocates the memory allocated by malloc,calloc or realloc functions.

Syntax: free(ptr);

Problems in pointers:
1. Dangling pointers
2. Memory leakage

Dangling Pointers:
Dangling pointers arise when an object is deleted or deallocted without modifying the value of the
pointers, so that pointer still points to the memory location of the deallocated memory
or
after an object is destroyed(memory deallocated) still that object is pointing to a non-existing
(invalid)memory location is called dangling ponters.

Example: char *ptr= malloc(100); After memory allocation


ptr 1526

free(ptr);
After deallocation

now ptr is an dangling pointer. ptr ?

To avoid dangling pointer, initialize the pointers to null, when they are not required.
ptr=NULL(case sensitive).
22

/* C program to avoid Dangling pointer*/


#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int *p,n=2,i;
clrscr();
p=(int*)malloc(n*sizeof(int));
for(i=0;i<n;i++)
scanf("%d",(p+i));
for(i=0;i<n;i++)
printf("%d\n",*(p+i));
free(p);
p=NULL; //avoiding dangling pointer p
NULL
printf("%d",p);
getch();

Memory Leakage:

When memory is reserved but not accessible such situation is called memory
leakage.

Example:

int *a;

a=(int*)malloc(2);

printf(“%d”,a);

a=(int*)malloc(2);

in the above example object a references to new memory location.


And it is accessible through new memory reference.
But old memory is reserved for object a, which is can’t be allocated to
other objects until that memory is get deallocated. such situation is
called memory leakage.
Dynamically Allocated Arrays:

Usually array at the time of its declaration gets it predefined size. Bounding to this size, programmers
will have to find out solution for several problems. For example, if SIZE value is 100, the program can
be used to sort a collection up to 100 numbers. If the user wishes to sort more than 100 numbers, we
have to change the definition of SIZE using some larger value and recompile the program. It becomes
little tedious for someone to rethink on this number. Hence the concept, Dynamic Arrays.

In c there three functions which can be used for dynamic allocation i.e malloc(),calloc() and realloc().
void main()
{
int n;
int *a;
printf(“enter the number of elements\n”);
scanf(“%d”,&n);
a=(int*)malloc(n*sizeof(int)); // allocate memory dynamically for n locations
if(a==NULL) // malloc returns NULL if no memory is allocated
printf(“No sufficient Memory”);
else
{
Printf(“enter %d elements \n”,n);
For(i=0;i<n;i++)
Scanf(“%d”,a+i);
}
}
2D – Dynamically declared Arrays
#include<stdio.h>
#include<stdlib.h>
int main()
{

int **p;
int m, n, i, j;
printf("Enter number of rows andcolumns:"); scanf("%d%d", &m, &n);

/* Allocate memory */

p = (int *) malloc(sizeof(int *) *m);/*Rowpointers*/

for(i = 0; i < m; i++)


{

p[i] = (int *) malloc(sizeof(int) * n); /* allocating memory each row*/

/* reading to array elements */


for(i = 0; i < m; i++)

{
for(j = 0; j < n; j++)
{
scanf("%d",(*(p+i)+j)); or scanf(“%d”,&p[i][j])

}
}

for(i = 0; i < m; i++)

{
for(j = 0; j < n; j++)

printf("%d", *(*(p+i)+j)); or printf(“%d”,p[i][j];

}
}

/* Deallocate memory */
for(i = 0; i < m; i++)
{

free (p[i]); /* Rows */


}
free (p); /* Row pointers */
p=NULL;

}
int **float;//double pointer
Polynomials:
Polynomial is a sum of terms,where each term is of the form axe where x is variable a is the co-
efficient and e is exponent.
Ex: A(x)=6x4+3x3+9, B(x)=9x3+6x2+6x.

The largest or leading exponent of the polynomial is called degree of the polynomial.

Ex: in the above ploynomials Degree of A is 4 and B is 3.

If the co-efficient is zero then the term is not displayed


If the the exponent is zero then the variable is not displayed .

ADT polynomial is:


Objects:p(x)=a0xe0+a1xe1+…….anxen a set of ordered pairs of<ei,ai> where ei is exponent and ai is an
coefficient
Functions: for all poly,poly1 € polynomial,coef€coefficients ,expon€Exponents
• Coefficient Coef(poly, expon) ::= it return its
coefficient else return Zero
• Exponent Lead_Exp(poly) ::= return the largest exponent
in poly

Polynomial Attach(poly,coef, expon) ::= if (expon € poly) return error
else return the polynomial poly
with the term <coef, expon>
inserted
• Polynomial Remove(poly, expon) ::= if (expon € poly) return the
polynomial poly with term whose exponent
is expon deleted else return error
• Polynomial Add(poly,poly1)::= Add two polynomials
• Polynomial mult(poly,poly1)::= returns product of polynomials

Polynomial Representation.

#define MAX_DEGREE 101


typedef struct {
int degree;
float coef[MAX_DEGREE];
} polynomial;
In the above represenation an array coef[] stores coefficients of polynomial. If n is the degree of
polynomial then the coefficents are stored in decreasing order .if n-i exponent is not exist then the
coefficent is intialized to zero i.e a.coefficient[i]=0. If the degree of polynomial is <<(very musch
lesser ) than the MAX_DEGREE then the no. of coefficients intialized with 0 will be more ,which
waste the space. to overcome this ,Alternatively a global array can be used to represent polynomial.

Alternate representation

Which is represented by using global arrays and can be used for storing any polynomial as follows.
C-representaion to store polynomial by using a global array

#define MAX_TERMS 50
typedef struct
int coeff;
int exponent;
} polynomial;
Polynomial terms[MAX_TERMS];
int avail=0;
Sparse Matrices:
if m is a row and n is a coloumn then the number of zero elements in the matrix if greater than the
(m*n)/2 then that matrix is called Sparse Marix.
/* C program to sparse matrix representation in triplet and finding its
transpose by using column indices method */
#include<stdio.h>
#include<conio.h>
struct sparse
{
int row,col,val;
};
void main()
{
struct sparse s[20],t[20];
int i,temp,j,m,n,k=0,l=1,p=1;
clrscr();
printf("enter the size of rows and columns\n");
scanf("%d%d",&m,&n);
printf("enter the elements of matrix\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&temp);
if(temp!=0)
{
k++;
s[k].row=i;
s[k].col=j;
s[k].val=temp;

}
}
}
s[0].row=m,s[0].col=n,s[0].val=k;
printf("\trow\t col \t val\t\n");
for(i=0;i<=k;i++)
printf("s[%d]\t%d\t%d\t%d\n",i,s[i].row,s[i].col,s[i].val);
for(i=0;i<n;i++) //to transpose by using coloumn indices method
{
while(l<=k)
{
if(s[l].col==i)
{
t[p].row=s[l].col;
t[p].col=s[l].row;
t[p].val=s[l].val;
p++;
}
l++;
}
l=1;
}
t[0].col=s[0].row,t[0].row=s[0].col,t[0].val=s[0].val;
printf("\ntranspose of sparse matrix\n");
printf("\t row\tcol\t val\n");
for(i=0;i<=k;i++)
printf("t[%d]\t%d\t%d\t%d\n",i,t[i].row,t[i].col,t[i].val);
getch();
}
Strings :
Strings are one-dimensional array of characters terminated by a null character '\0'. Thus a null-
terminated string contains the characters that comprise the string followed by a null. The following
declaration and initialization create a string consisting of the word "Hello". To hold the null character
at the end of the array, the size of the character array containing the string is one more than the number
of characters in the word "Hello."
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
If you follow the rule of array initialization then you can write the above statement as follows −
char greeting[] = "Hello";
Following is the memory presentation of the above defined string in C

Figure 1.6
Note: Actually, you do not place the null character at the end of a string constant. The C compiler
automatically places the '\0' at the end of the string when it initializes the array.

C supports a wide range of built in functions that manipulate null-terminated strings :−

strcpy(s1, s2):- Copies string s2 into string s1.

strcat(s1, s2):- Concatenates string s2 onto the end of string s1.

strlen(s1):- Returns the length of string s1.

strcmp(s1, s2):- Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.

strchr(s1, ch); Returns a pointer to the first occurrence of character ch in string s1

strstr(s1, s2); Returns a pointer to the first occurrence of string s2 in string s1.

Write a C program to all the above said operations without using any library function.
Different operations on strings.
1. insert
2. Replace
1.Insert: A string can be inserted inside another string in the specified position.
It is possible by using string builtin functions like,strcpy, strncpy and strcat.
Example:
Assume that we have two strings,say string1 and string2 and we want insert string2 into
string1 at the ith position string

String1=”amobile”
String2=”uto”
temp=”\0” // temp array for processing
i=1 // inserting in ith index of string1

strncpy(temp,string1,i); after this temp=”a\0”


strcat(temp,string2); after this temp=”auto\0”
strcat(temp,(string1+i));after this temp=”automobile\0”

strcpy(string1,temp); after this string=”automobile\0”

/* C function to insert a string inside another string*/


void instr(char *string1,char *string2,int i)
{
Char string[MAX_SIZE],*temp=string;

If(i<0 && i>strlen(string1))


{
fprintf(stderr,”position is out of bounds \n”);
exit(EXIT_FAILURE);
}
If(!strlen(t))
Strcpy(string1,string2);
else if(strlen(t))
{
strncpy(temp,string1,i); //after this temp=”a\0”
strcat(temp,string2); //after this temp=”auto\0”
strcat(temp,(string1+i));//after this temp=”automobile\0”
strcpy(string1,temp); //after this string=”automobile\0”
}

Replace:
It is the process of replacing a substring inside a main string or a text wherever it occurred in
the text.

Refer labprogram2.

Pattern Matching:
It is the process of finding the pattern in the given text. if it is exist the location of the that pattern in
the main string has to be return.
There is a built in function is available to search such pattern i.e strstr(str1,str2);
Where str1 is a text and str2 is a pattern to be searched. if pattern is found it returns a pointer to the
location of such pattern in the text otherwise returns null pointer .

Example: if(t==strstr(str1,str2))
Printf(“the string from str1 where pattern is found\”,t);
Else
Printf(“the string not found \n”);

This method consumes more time.to overcomes this rhere are some algorithms or methods can be
used
1.By comparing last indices
2.Knutt,Morris,Pratt (KMP algorithm).

1.By comparing last indices:

/* pattern matching by using end indices First */

int enind(char *string,char *pat)

int i, j, start=0;

int lasts=strlen(string)-1;

int lastp=strlen(string)-1;

int endmatch=lastp;

for(i=0;endmatch<=lasts;endmatch++,start++)

If(string[endmatch]==pat[lastp])

for(j=0,i<=start;j<lastp&&string[i]==pat[j];i++,j++);

If(j==lastp)

return start;

return -1;

Analysis of algorithm:
pattern=”aab\0”
string=”ababbaabaa\0”
astp=2
endmatch=2
Pattern: j=0 a a B ‘\0’

String: a b a b b a a b a a i=0

start endmatch [where endmatch!=lastp, start++,endmatch++]

Pattern: j=0 a a b ‘\0’

String: a b a b b a a b a a i=1

start endmatch [where endmatch=lastp, but b!=a,start++,endmatch++]]

Pattern: j=0 a A b ‘\0’

String: a b a b b a a b a a i=2

start endmatch [where endmatch=lastp,a=a, i++,j++]

Pattern: j=1 a A b ‘\0’

String: a b a b b a a b a a i=3

start endmatch

[wher endmatch=lastp,b!=a,endmatch++,start++]

Pattern: j=0 a a b ‘\0’

String: a b a b b a a b a a i=3

start endmatch
[where endmatch!=lastp,endmatch++,start++]

Pattern: j=0 a a b ‘\0’

String: i=4
a b a b b a a b a a
start endmatch
[where endmatch!=lastp,endmatch++,start++]
Pattern: j=0
a a b ‘\0’

String: i=5
a b a b b a a b a a
start endmatch
[where endmatch=lastp and a=a,i++,j++]
Pattern: j=1
a a b ‘\0’

String: i=6
a b a b b a a b a a
start endmatch
[where endmatch=lastp and a=a,i++,j++ finally j=lenp]
Now j=2,which is equal to lastp ,therefore pattern is foumd the value of
other indices are i=7,start=5,endmatch=7

Position of the pattern where that string is found is returned by using the
value of start.

KMP(Knutt,Morris and Pratt algorithm)

/* A c program to find the first occurence of pattern in main string by


using KMP algorithm*/
#include<stdio.h>
#include<string.h>
#include<conio.h>
char str[20],mstr[50];
int prfx[20],i,j,m,lenp;

/* function to compute prefixarray or failure function*/

void prefix()
{
i=1,j=0;
prfx[0]=0;
lenp=strlen(str);
while(i<lenp)
{
if(str[j]==str[i])
{
prfx[i]=j+1;
i++;
j++;
}
else if(j!=0)
{
j=prfx[j-1];
}
else
{
prfx[i++]=j;
}
}
i=0;
while(i<lenp)
printf("%d\n",prfx[i++]);
getch();
}

/*pattern matching by using prefix or failure function*/


int kmp()
{
j=0,m=0;
while(mstr[m]!='\0'|| str[j]!='\0')
{
if(mstr[m]==str[j])
{
m++;
j++;
}
else if(j==0)
{
m++;
}
else
{
j=prfx[j-1];
} }
return ((j==lenp)?(m-lenp):-1);
}

void main()
{
int pos;
clrscr();
printf("enter a string\n");
gets(mstr);
printf("enter a pattern string\n");
gets(str);
prefix();
pos=kmp();
if(pos==-1)
printf("pattern is not found\n");
else
printf("patern is found in the position %d of the main string\n",pos+1);
getch();
}

You might also like