Вы находитесь на странице: 1из 154

1.

FILES

Large amount of data/ info has to be written to or from an


auxiliary storage device. Such information is stored on the
device in the form of a data file.
There are two different categories of data files.
- Stream oriented data files
- System oriented data files.

Stream oriented data files are of two types.


Text files – individual data items or component or
strings or numbers. (Formatted data files)
Binary files – Unformatted data files, organizes data into
blocks containing contiguous bytes of
information.

System oriented data files are more closely related to the


computer’s Operating System than the stream-oriented data
files.

To perform the Input/Output from and to files, an extensive


set of library functions are available in C.
Access to files generally requires four basic operations.
Open - This allows access to a file and establishes
the position, or offset, in the file.
Close- This ends access to the file, When access to
a file is complete, it should be closed. The
number of files that a running program can
have at any time is limited; by closing files
properly these limited facilities can be used
more intelligently.
Read- This gets information from the file, either in
the form of character strings, or in the form
of data (combined integers, characters,
floating point numbers, & structures.)
Write- This adds information to the file or replaces
information already on the file.

1.1 Opening & Closing of a data file


When working with a stream-oriented data file, the first
step is to establish a buffer area, where information is
temporarily stored while being transferred between the
computer’s memory and the data file. The buffer area is
established by writing
FILE *ptvar;

where FILE is a special structure type that establishes the


buffer area, & ptvar is a pointer variable that indicates the
beginning of the buffer area. The structure type FILE is
defined within a system include file stdio.h

Opening a file : fopen()


The standard I/O function used to open a file is named
fopen(). This associates the file name with the buffer
area. It returns a pointer to the structure FILE. The return
value must be saved because all ther functions for file
handling requires this as an argument.

Function name:
(FILE *) fopen(file_name, mode)
Description
This function opens a file and establishes a current offset
within the file. This must be done before attempts are
made to read from or write to the file.
Argument list
(char *) file_name – The starting address of a character
string describing the name of the file.
This can be either a character string, or
array name, or a character pointer.

(char *) mode-
This describes the actions to be
performed on the file and governs the
initial offset in the file. The modes for
opening a file are:
r - Opened for reading. Positioned at the
beginning of the file.
w - Opened for writing. The assumption is
that the file is to be created. If the file
does not exist, it is created, if it does
exist, it is truncated. Positioned at the
beginning of the file.
a - Opened for writing. Same rules apply
as for mode w except that initial
positioning is at the end of the file and
the file is not truncated.
r+ - Opened for update. File is available for
reading and writing but is not
truncated. The initial positioning is at
the start of the file.
w+ - Opened for update. File is available for
reading & writing and is truncated if
the file does not exist, it is created.
Initial positioning is at the start of the
file.
a+ - Opened for update. File is available for
reading and writing, is not truncated,
and initial positioning is at the end of
the file.

Return values:
FILE * Retained for successful open. Value is a
pointer to a structure that contains file
opening and buffering information. The
return value is to identify the file for
performing input and output.
(FILE *) NULL Returned if the file cannot be opened.
Occurs if the file does not exist
and is being opened other than for writing,
or if the user is opening a new file for
writing, but does not have permission to create a
file with the supplied file name.

Closing a file: fclose()


When a program has completed its use of a file, the file
should be closed using the fclose() function. This
function is defined formally as follows.
Function name:
(int) fclose(stream)
Description
This function closes the specified file and releases any
overhead used in maintaining the file, permitting the
memory that held this information to be used for opening
another file. If a program exits without closing a file, the
system will automatically close the file through proper
calls to fclose().

Argument list
(FILE *)stream This is the return value from fopen()
and is used to identify which file is to be
closed.

Return values
0 This means a successful file closing
EOF This means an error was encountered when closing
the file.

Processing a Data file


A data file must be created before it can be processed.
When creating a new data file, the
information that is entered through a keyboard is to write
out to the data file.

1.2 Writing to a File


Three functions for writing to files exist and are directly
analogous to functions used for terminal
output.These functions are fputc(), fputs() and fprintf().
These functions require an additional argument –an
output file identification i.e., the file to which the data has
to be written.

Individual characters can be written to the files using


fputc() function.
The entire strings can be written to the data files utilizing
special string-oriented library function,
fputs().Many data files contain more complicated data
structures, such as records that include
variouscombinations of numeric & character information.
For formatted writing of characters, strings,ntegers, &
floats, fprintf() can be used.

Function name:
int fputc(c,stream);

Description:
The fputc function writes the single character to the file at
the current position.

Argument list:
int c character to be written
FILE *stream pointer to FILE structure that is the return
value from fopen().

Return values
int The value of character return
EOF indicates an error.

This program uses fputc() to send a character to an


ASCII file.

#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fptr;
char strptr1[]=“This is the first FILE program !!\n";
char *p;
clrscr();
fptr=fopen("charfile.txt","w");
if(fptr==NULL)
{
printf("\nUnable to open the file");
exit(1);
}
for(p=strptr1;*p!='\0';p++)
fputc(*p,fptr);
getch();
}

Function Name:
int fputs(str,stream);

Description
The fputs function copies string to the output file at the
current position. The terminating character (‘\0’) is not
copied.

Argument list
char * str pointer to the string to be output.
FILE *stream pointer to FILE structure which
specifies the name of the file to which
output has to be written.
Return Values
int (>0) Non negative value if successful
EOF Error
This program receives strings from keyboard and
writes them to file using fputs() function.

#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fptr;
char s[80];
clrscr();
fptr=fopen("text.txt","w");
if(fptr==NULL)
{
puts("Cannot open file ");
exit();
}
printf("\nEnter a few lines of text : \n");
fflush(stdin);
while(strlen(gets(s))>0)
fputs(s,fptr);
fclose(fptr);
getch();
}
Function Name:
int fprintf(stream, format, argument)
Description:
fprintf() printf formatted data to the file. The fprintf()
function formats and prints a series of characters &
values to output file.
Argument list:
FILE *stream Pointer to FILE structure
char *format Format-control string
Arguments Each argument is converted and
output according to corresponding format
specification in format.

Return values
int (>0) The number of characters printed.
(<0) In case of an output error.

Write a C program to enter Employee details and copy


those to a file using fprintf() function.

#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ans='Y';
char name[40];
int age;
float bsal;
clrscr();
fp=fopen("EMPLOYEE.txt","w");
if(fp==NULL)
{
printf("\nCannot open file");
exit();
}
while(ans=='Y' || ans =='y')
{
printf("\nEnter name,age and basic salary\n");
scanf("%s %d %f",name,&age,&bsal);
fprintf(fp, "%s %d %f\n",name,age,bsal);
printf("\nAnother employee (Y/N) : ");
fflush(stdin);
scanf("%c",&ans);
}
fclose(fp);
getch();
}

1.3 Reading from a File


The functions getchar(), scanf(), gets() read information
from the terminal. Analogous functions
read information from open files. These functions are
fgetc(), fscanf(), and fgets().

Data files consisting of individual characters can be read


using fgetc() function. Data files
consisting entirely of strings can be read utilizing special
string-oriented library function, fgets().
Many data files contain more complicated data structures,
such as records that include various
combinations of numeric and character information. Such
data files can be read using fscanf()
function.
These function calls require one additional argument, the
identification of the file from where the
information is being read. This identification is the fopen
function call’s saved return value.
Note:
When reading a file beyond end of file, the manner in
which the end of file is indicated internally
depends on the device the file is on. fgetc() and fscanf()
function returns EOF which is already
defined in the header file stdio.h. EOF has the value -1.
The fgets() function indicates end of file
condition by returning NULL which has the value 0.

Function Name:
int fgetc(stream);

Description:
The fgetc() function reads a single character from the
current position of the file associated with the stream.
The character is converted and returned as an int. The
function then increments the associated file pointer(if
any) to point to the next character.

Argument List:
(FILE *) stream Pointer to FILE structure that is the
return value from fopen()

Return values:
int The value of the character read.
EOF Indicates an error or end-of-file.

This program uses fgetc() to read the first 100 input


characters (or until the end of input
from a file and place them into a string named buffer.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
FILE *fptr;
char buffer[100];
int i,ch;
fflush(stdin);
clrscr();
if((fptr=fopen("fgetc.c","r"))==NULL)
exit(0);
ch=fgetc(fptr);
for(i=0;i<100&&ch!=EOF;i++)
{
buffer[i]=ch;
ch=fgetc(fptr);
}
buffer[i]='\0';
printf("\n%s",buffer);
fclose(fptr);
getch();
}

Function Name:
char *fgets(str,n,stream)

Description:
The fgets() function reads a string from the input stream
argument and stores it in str. Characters are read from the
current stream position upto and including the first
newline character (‘\n’), upto the end of the stream, or
until the number of characters read is equal to n-1, which
ever comes first. The result is stored in str, and a null
character (‘\0’) is appended. The new line character if
read is included in the string. If n is equal to 1, the str is
empty(“”). The fgets function is similar to the gets
function; however gets replaces the newline character
with NULL.

Argument List:
char *str storage location for data
int n Number of characters stored
FILE *stream Pointer to FILE structure, which identifies
the file from where the data has to be
read.

Return Values:
char * The starting address of str.
NULL Error or end-of-file condition.

The program uses the fgets() function to read lines from


a file and then print them on the
standard output (the terminal) followed by a count of
the number of lines in the file.

#include<stdio.h>
#include<conio.h>
void main()
{
char inp_line[300],filename[30];
int counter;
FILE *fptr;
clrscr();
printf("\nEnter filename : ");
gets(filename);
fptr=fopen(filename,"r");
if(fptr==NULL)
{
printf("\nCannot open %s",filename);
exit(0);
}
counter=0;
printf("\nThe contents of the file :\n ");
while(fgets(inp_line,300,fptr)!=NULL)
{
printf("%s",inp_line);
counter++;
}
printf("\nTotal NUMBER OF LINES = %d",counter);
fclose(fptr);
getch();
}

Function Name:
int fscanf(stream, format, argument)

Description:
fscanf() function reads formatted data from a stream. It
reads data from the current position of stream into the
location given by the argument. Each argument must be a
pointer to a variable with a type that corresponds to a type
specifier in format.
Argument list:
FILE *stream Pointer to FILE structure
char *format Format-control string
argument Optional arguments

Return values:
int > 0 The number of strings that were
successfully converted and assigned.
The return values does not include fields that were
read but not assigned.
0 No values were assigned.
EOF error or end-of-file.

This program reads the data, Name, Age, and Basic


salary of different employees in a
formatted way from the file EMPLOYEE.txt
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char name[40];
int age;
float bsal;
clrscr();
fp=fopen("EMPLOYEE.txt","r");
if(fp==NULL)
{
printf("\nCannot open file");
exit(0);
}
while(fscanf(fp,"%s %d %f",name,&age,&bsal)!=EOF)
{
printf("\n%s %d %f",name,age,bsal);
}
fclose(fp);
getch();
}

1.4 Random Access of a Data file


It is possible to access any position randomly within a file
using the fseek() function. This function
expects three arguments and is defined formally as follows:

Function Name:
(int) fseek(stream,offset,where)

Description:
This function changes the current position within a file by
changing the offset associated with the opening of the
file. Positioning can be specified as a number of bytes
from the beginning of the file, from the end of the file, or
from the current position in the file. If a file is positioned
past the actual end of the file and a write is performed,
then the size of the file will be extended and a gap
will be placed in the file. If a read is attempted past the
end of the file, an error will occur.

Argument List:
(FILE *) stream This identifies the file in which the
current offset is to be changed.
Should be the saved return value from the file’s
fopen().
(long) offset The offset, in bytes, either from the start of
the file, the end of the file, or from the current position.

(int) where Defines the context for the second


argument. Legal values are
0 indicates from the beginning of the file.
1 indicates from the current position.
2 indicates from the end of the file.
Return Values
0 This means a successful seek.
!=0 This means the specified position could not be
seeked. Possibly out of range or an
argument was incorrectly specified.

The current offset in the file can be determined using the


function ftell().

Function Name:
long ftell(stream)

Description:
The ftell function gets the current position of the file
pointer(if any). The position is expressed as an offset
relative to the beginning of the file.

Argument List:
(FILE *) stream Pointer to a FILE structure, the return
value from the fopen of the file whose offset
is needed.

Return values:
long Current file position
-1 On error.

The file pointer can be positioned at the beginning of the


file.

Function Name:
void rewind(stream)

Description:
The rewind function repositions the file pointer to the
beginning of the file. A call to rewind is equivalent to
fseek(stream, 0L, seek_set);

Argument List:
(FILE *) stream Pointer to FILE structure

Return Values:
No return value

Write a C program to perform the following:


Assume there are N records, each having the structure
consisting of USN : +ve integer, Name : 25 chararacters,
Marks1: +ve integer, Marks2: +ve integer, Marks3: +ve
integer. Where USN stands for University Seat Number,
Marks1, Marks2 and Marks3 are the marks scored by a
student in subject1, subject2 and subject3 respectively.
Let us write a program to create a sequential file with at
least 5 records, each record having the structure as
defined. Write necessary functions to
4. Display all the records in the file.
5. To search for a specific record based on USN.
Display suitable message.

#include<stdio.h>
#include<conio.h>
#include<process.h>
#include<string.h>
struct student
{
int usn;
char name[30];
int marks1;
int marks2;
int marks3;
};
typedef struct student STUD;

int search_record(int key, FILE *fp)


{
STUD st;
for(;;)
{
fscanf(fp,"%d %s %d %d
%d",&st.usn,st.name,&st.marks1,&st.marks2,&st.marks3
);
if(feof(fp))
break;
if(key==st.usn)
{
printf("\nUSN Name Marks1 Marks2 Marks3");
printf("\n%d\t %s\t %d\t %d\t
%d",st.usn,st.name,st.marks1,st.marks2,st.marks3);
return 1;
}
}
return 0;
}

void append_record(FILE *fp)


{
STUD st;
printf("\nUSN : ");
scanf("%d",&st.usn);
printf("\nName : ");
fflush(stdin);
gets(st.name);
printf("\nMarks 1 : ");
scanf("%d",&st.marks1);
printf("\nMarks 2 : ");
scanf("%d",&st.marks2);
printf("\nMarks 3 : ");
scanf("%d",&st.marks3);
fprintf(fp,"%d %s %d %d
%d\n",st.usn,st.name,st.marks1,st.marks2,st.marks3);
}
void display(FILE *fp)
{
STUD st;
printf("\nUSN Name Marks1 Marks2 Marks3");
for(;;)
{
fscanf(fp,"\n%d %s %d %d
%d",&st.usn,st.name,&st.marks1,&st.marks2,&st.marks3
);
if(feof(fp))
break;
printf("\n%-5d %-10s %-5d\t%-5d\t %-
5d",st.usn,st.name,st.marks1,st.marks2,st.marks3);
}
}
void main()
{
STUD st;
char filename[15];
FILE *fp;
int usn,flag,choice;
clrscr();
printf("\nEnter the file name : ");
scanf("%s",filename);
for(;;)
{
clrscr();
printf("\n\n\n\n\n\n\t\t\t*****MAIN
MENU*****\n\n\n");
printf("\nPRESS 1--> TO INSERT RECORD\nPRESS
2--> TO SEARCH RECORD");
printf("\nPRESS 3--> TO DISPLAY RECORD\nPRESS
4--> TO QUIT");
printf("\nEnter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
fp=fopen(filename,"a+");
if(fp==NULL)
{
printf("\nFile open failed");
break;
}
append_record(fp);
fclose(fp);
getch();
break;
case 2:
fp=fopen(filename,"r");
if(fp==NULL)
{
printf("\nFile open failed");
break;
}
printf("\nEnter USN : ");
scanf("%d",&usn);
flag=search_record(usn,fp);
if(flag==0)
printf("\nSearch Unsucessful");
else
printf("\nSearch Successful");
fclose(fp);
getch();
break;
case 3:
fp=fopen(filename,"r");
if(fp==NULL)
{
printf("\nFile open failed ");
break;
getch();
}
display(fp);
fclose(fp);
getch();
break;
default:
printf("\nTHANK YOU!!! HAVE A NICE DAY");
getch();
exit(0);
}
}
getch();
}

2. STACKS

2.1 Data Structures


The logical or mathematical model of a particular
organization of data is called data structures.
Data structures is the study of logical relationship existing
between individual data elements, the way the data is
organized in the memory and the efficient way of storing,
accessing and manipulating the data elements.

Choice of a particular data model depends on two


considerations: it must be rich enough in structure to mirror
the actual relationships of the data in the real world. On the
other hand, the structure should be simple enough that one
can effectively process the data when necessary.

Data Structures can be classified as:


Primitive data structures
Non-Primitive data structures.
Primitive data structures are the basic data structures that
can be directly manipulated/operated by machine
instructions.
Some of these are character, integer, real, pointers etc.
Non-primitive data structures are derived from primitive
data structures, they cannot be directly
manipulated/operated by machine instructions, and these
are group of homogeneous or heterogeneous data items.
Some of these are Arrays, stacks, queues, trees, graphs etc.

Data structures are also classified as


Linear data structures
Non-Linear data structures.
In the Linear data structures processing of data items is
possible in linear fashion, i.e., data can be
processed one by one sequentially.
Example of such data structures are:
Array
Linked list
Stacks
Queues
A data structure in which insertion and deletion is not
possible in a linear fashion is called as non
linear data structure. i.e., which does not show the
relationship of logical adjacency between the
elements is called as non-linear data structure.
Such as trees, graphs and files.

Data structure operations:


The particular data structures that one chooses for a given
situation depends largely on the
frequency with which specific operations are performed.
The following operations play major role in the processing
of data.
i) Traversing.
ii) Searching.
iii) Inserting.
iv) Deleting.
v) Sorting.
vi) Merging

2.2 Stack definition


A stack is an ordered collection of items into which
new items may be inserted and from which items may be
deleted at the same end, called the TOP of the stack.
A stack is a non-primitive linear data structure.
As all the insertion and deletion are done from the same
end, the first element inserted into the stack is the last
element deleted from the stack and the last element inserted
into the stack is the first element to be deleted. Therefore,
the stack is called Last-In First-Out (LIFO) data structure.

Inserting elements into the stack is called as PUSH


operation. The items are inserted into the stack by using a
pointer called as TOP. The TOP indicates the current status
of the stack. Initially, TOP is initialized to -1. During
insertion, We first increment the TOP and then, items are
inserted into the stack of TOP position. If stack is full, then
the TOP will be SIZE-1. (SIZE indicates the maximum
elements that the stack can hold.) and an error message is
generated, telling that STACK OVERFLOW condition has
occurred and insertion is not possible.

Deletion of elements from the stack is called as POP


operation. The items deleted from the stack are the TOP
specified content. If TOP is equal to -1. It indicates stack is
empty, then an error message is raised, indicating STACK
UNDERFLOW and deltion not possible.

A ‘C’ program to implement STACK to perform the


PUSH, POP and DISPLAY operations, Display the
appropriate messages for STACK OVERFLOW,
STACK UNDERFLOW and STACK EMPTY.

#include<stdio.h>
#include<conio.h>
#define SIZE 5
int top=-1;
int stack[SIZE];
void display()
{
int i;
if(top==-1)
{
printf("\nSTACK IS EMPTY....");
getch();
return;
}
for(i=top;i>=0;i--)
printf("\nstack[%d]=%d",i,stack[i]);
getch();
}

void push(int d)
{
if(top==(SIZE-1))
{
printf("\nSTACK IS FULL ..!! STACK
OVERFLOW...");
getch();
}
else
{
stack[++top]=d;
printf("\nThe content of the stack after insertion is :\n");
display();
}
}
void pop(void)
{
int pop_ele;
if(top==-1)
{
printf("\nThe stack is empty..!!STACK
UNDERFLOW...");
getch();
}
else
{
pop_ele=stack[top--];
printf("\nThe popped out element of the stack is :
%d",pop_ele);
printf("\n\nThe content of the stack after deletion is ");
display();
}
}
void main()
{
int data,choice,q=0;
while(q!=1)
{
clrscr();
printf("\n\n\n\t\t\t\t*****MAIN MENU*****");
printf("\n\n\n\n\n\n\t ENTER 1 --> TO PUSH THE
ELEMENT INTO THE STACK");
printf("\n\t ENTER 2 --> TO POP THE ELEMENT
FROM THE STACK");
printf("\n\t ENTER 3 --> TO DISPLAY THE CONTENT
OF THE STACK ");
printf("\n\t ENTER 4 --> TO QUIT");
printf("\n\n\nEnter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nENTER THE ELEMENT TO BE
INSERTED : ");
scanf("%d",&data);
push(data);
break;
case 2:
pop();
break;
case 3:
printf("\nTHE CONTENT OF THE STACK IS : ");
display();
break;
case 4:
q=1;
printf("\nTHANK YOU....HAVE A NICE DAY");
break;
}
}
getch();
}

2.3 Expressions

Infix Expression :
Any expression in the standard form like "2*3-4/5" is an
Infix expression. (Operator in between the two operands).
(In-order) expression.

Postfix Expression :
The Postfix expression has the Operator after the two
operands. (Post order) form of the above expression is
"23*45/-".

Infix to Postfix Conversion :


In normal algebra we use the infix notation like a+b*c. The
corresponding postfix notation is abc*+. The algorithm for
the conversion is as follows :
 Scan the Infix string from left to right.
 Initialize an empty stack.
 If the scanned character is an operand, add it to the
Postfix string.
 If the scanned character is an operator and if the stack
is empty Push the character to stack.
 If the scanned character is an Operand and the
stack is not empty, compare the precedence of the
character with the element on top of the stack
(top of Stack). If top of Stack has higher
precedence over the scanned character Pop the
stack else Push the scanned character to stack.
Repeat this step as long as stack is not empty and
top of Stack has precedence over the character.
Repeat this step till all the characters are scanned.
 (After all characters are scanned, we have to add any
character that the stack may have to the Postfix string.)
If stack is not empty add top of Stack to Postfix string
and Pop the stack. Repeat this step as long as stack is
not empty.
 Return the Postfix string.
Example :
Let us see how the above algorithm will be implemented
using an example.
Infix String : a+b*c-d
Initially the Stack is empty and our Postfix string has no
characters. Now, the first character scanned is 'a'. 'a' is
added to the Postfix string. The next character scanned is
'+'. It being an operator, it is pushed to the stack.
Next character scanned is 'b' which will be placed in the
Postfix string. Next character is '*' which is an operator.
Now, the top element of the stack is '+' which has lower
precedence than '*', so '*' will be pushed to the stack.
The next character is 'c' which is placed in the Postfix
string. Next character scanned is '-'. The topmost character
in the stack is '*' which has a higher precedence than '-'.
Thus '*' will be popped out from the stack and added to the
Postfix string. Even now the stack is not empty. Now the
topmost element of the stack is '+' which has equal priority
to '-'. So pop the '+' from the stack and add it to the Postfix
string. The '-' will be pushed to the stack.
Next character is 'd' which is added to Postfix string. Now
all characters have been scanned so we must pop the
remaining elements from the stack and add it to the Postfix
string. At this stage we have only a '-' in the stack. It is
popped out and added to the Postfix string.
End result :
 Infix String : a+b*c-d
• Postfix String : abc*+d-
Conversion of Postfix to infix expression:

Let us take an example. Postfix expression: ab+c-


6. Scan the postfix expression. Whenever operands are
encountered. Push it to stack.
7. Whenever, Operator is encountered. Pop out two
operands from the stack. Infix the operator, in between
the operands and Push the expression back to stack.
8. After scanning, the whole postfix expression, Pop out
the content of the stack.
Here in this example, Initially, The character scanned is a.
So push it to the stack., next the character scanned is b,
again push it to stack. Next, we come across +. So pop out
‘a’ and ‘b’, stack is empty, and after infixing the operator
+, We get (a+b). Call this as T1. and push this to stack.
Scan the next character, In this case it is ‘c’, its an operand
so push it to stack. Next we come across -. So pop out ‘c’
and ‘T1’. Infix – in between T1 and c. We get (T1-c). Call
this as T2. Push T2 to stack. It’s the end of the expression.
Now substitute the value of T2. we get (T1-c). Now
substitute T1. We get ((a+b)-c).

End result:
Postfix expression: ab+c-
Infix expression: ((a+b)-c)

Conversion of Infix to Prefix expression:

First, reverse the given prefix expression and follow the


same steps as to convert the Postfix expression to infix
expression.

A ‘C’ program to EVALUATE A VALID POSTFIX


EXPRESSION using stack. Assume that the postfix
expression is read as a single line consisting of non-
negative single digit operands and binary arithmetic
operators + (add), - (subtract), *(multiply) and /
(divide).

#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<string.h>
#define size 20
int top=-1;
int stack[size];
int operate(char symb, int oprd1, int oprd2)
{
switch(symb)
{
case '+': return oprd1+oprd2;
case '-': return oprd1-oprd2;
case '*': return oprd1*oprd2;
case '/': return oprd1/oprd2;
case '$':
case '^': return pow(oprd1,oprd2);
}
}
void push(int s[], int d)
{
s[++top]=d;
}
int pop(int s[])
{
int data;
data=s[top--];
return data;
}

void main()
{
int i,ans,oprd1,oprd2,choice,q=0;
char symb, expr[20];
clrscr();
do
{
printf("\n\n\n\t\t\t\t*******MAIN
MENU**********");
printf("\n\tPRESS 1 --> TO EVALUATE
EXPRESSION");
printf("\n\tPRESS 2 --> TO QUIT");
printf("\n\nEnter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nEnter the postfix expression : ");
fflush(stdin);
gets(expr);
for(i=0;i<strlen(expr);i++)
{
symb=expr[i];
if(symb>='0' && symb<='9')
push(stack,symb-'0');
else
{
oprd2=pop(stack);
oprd1=pop(stack);
ans=operate(symb,oprd1,oprd2);
push(stack,ans);
}
}
ans=pop(stack);
printf("\nThe result of the postfix expression is :
%d",ans);
getch();
clrscr();
break;
case 2:
q=1;
}
}while(!q);
}

A ‘C’ program to CONVERT and print a valid


parenthesized INFIX arithmetic expression to
POSTFIX expression. The expression consists of single
character operands and the binary operators + (plus), -
(minus), *(multiply) and / (divide).

#include<stdio.h>
#include<conio.h>
#include<string.h>
#define SIZE 20
#define Operator (-10)
#define Operand (-20)
#define Leftparen (-30)
#define Rightparen (-40)
int top=-1;
char stack[SIZE],infix[SIZE],postfix[SIZE];
void push(char symbol)
{
if(top==(SIZE-1))
printf("\nSTACK OVERFLOW...!!");
else
stack[++top]=symbol;
}
char pop(void)
{
char pop_ele;
if(top==-1)
printf("\nSTACK UNDERFLOW...!!");
else
{
pop_ele=stack[top--];
return pop_ele;
}
}
void infix_to_postfix(void)
{
int i,p,len,type,precedence;
char next;
i=p=0;
len=strlen(infix);
while(i<len)
{
if(!white_space(infix[i]))
{
type=get_type(infix[i]);
switch(type)
{
case Leftparen:
push(infix[i]);
break;
case Rightparen:
while((next=pop())!='(')
postfix[p++]=next;
break;
case Operand:
postfix[p++]=infix[i];
break;
case Operator:
precedence=get_prec(infix[i]);
while(top>-1 &&
precedence<=get_prec(stack[top]))
postfix[p++]=pop();
push(infix[i]);
break;
}
}
i++;
}while(top>-1)
postfix[p++]=pop();
postfix[p]='\0';
}

int get_type(char symbol)


{
switch(symbol)
{
case '(':
return(Leftparen);
case ')':
return(Rightparen);
case '+':
case '-':
case '*':
case '%':
case '/':
return(Operator);
default:
return(Operand);
}
}

int get_prec(char symbol)


{
switch(symbol)
{
case '+':
case '-':
return 1;
case '*':
case '/':
case '%':
return 2;
case '(':
return 0;
default:
return 999;
}
}

int white_space(char symbol)


{
return(symbol=='\0' || symbol==' ' || symbol=='\t');
}
void main()
{
int q=0,choice;
do
{
top=-1;
clrscr();
printf("\n\n\n\n\t\t\t******MAIN MENU******");
printf("\n\n\n\n\tENTER 1 --> TO CONVERT INFIX
TO POSTFIX");
printf("\n\tENTER 2 --> TO QUIT");
printf("\n\nEnter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nEnter an infix expression : ");
fflush(stdin);
gets(infix);
infix_to_postfix();
printf("\nInfix expression : %s",infix);
printf("\nPostfix expression : %s",postfix);
getch();
clrscr();
break;
case 2:
q=1;
printf("\nTHANK YOU.... HAVE A NICE
DAY..!!!");
getch();
}
}while(!q);
}

2.4 RECURSION

Recursion can be defined as a programming technique in


which a program or routine calls itself to perform
successive steps in an operation, with each step using the
output of the preceding step.

A RECURSIVE C program for searching an element on


a given list of integers using the BINARY SEARCH
METHOD.
#include<stdio.h>
#include<conio.h>
int a[20],beg,end,mid,key;
int binsearch(beg,end)
{
if(beg>end)
return (-1);
mid=(beg+end)/2;
return(key==a[mid]? mid : key<a[mid]?
binsearch(beg,mid-1):binsearch(mid+1,end));
}
void main()
{
int i,n,flag;
clrscr();
printf("\n\n\n\t\tPROGRAM TO SEARCH AN
ELEMENT USING RECURSIVE BINARY SEARCH");
printf("\n\n\nEnter the number of elements in the array :
");
scanf("%d",&n);
printf("\nEnter %d elements in ASCENDING ORDER
",n);
for(i=0;i<n;i++)
{
printf("\nEnter %d element : ",i+1);
scanf("%d",&a[i]);
}
printf("\nEnter the number to be searched : ");
scanf("%d",&key);
beg=0;
end=n-1;
flag=binsearch(beg,end);
if(flag>=0)
printf("\nSEARCH SUCCESSFUL...!!! %d FOUND IN
POSITION %d",key,mid+1);
else
printf("\nSEARCH UNSUCESSFUL");
getch();
}

A RECURSIVE C Program to find the nth


FIBONACCI NUMBER .
#include<stdio.h>
#include<conio.h>
long fibo(int n)
{
if(n<=1)
return (n);
return (fibo(n-1)+fibo(n-2));
}
void main()
{
int n;
long fib;
clrscr();
printf("\nEnter which numbers Fibonacci series to be
found ? ");
scanf("%d",&n);
fib=fibo(n);
printf("\nThe %dth Fibonacci number is = %ld",n,fib);
getch();
}

A RECURSIVE C Program to MULTIPLY TWO


NUMBERS.

#include<stdio.h>
#include<conio.h>
int mul(int a,int b)
{
return(b==1 ? a: mul(a,b-1)+a);
}

void main()
{
int a,b,res;
clrscr();
printf("\nEnter the two numbers : ");
scanf("%d %d",&a,&b);
res=mul(a,b);
printf("\nThe result is = %d",res);
getch();
}

A RECURSIVE C program to implement TOWER OF


HANOI .

#include<stdio.h>
#include<conio.h>
int count=0;
void twrofhanoi(int m, char srcpeg, char tempeg, char
destpeg)
{
if(m==1)
{
printf("\nMove disk 1 from %c to %c",srcpeg,destpeg);
count++;
return;
}
twrofhanoi(m-1,srcpeg,destpeg,tempeg);
printf("\nMove disk %d from %c to
%c",m,srcpeg,destpeg);
count++;
twrofhanoi(m-1,tempeg,srcpeg,destpeg);
}
void main()
{
int n;
clrscr();
printf("\n\n\n\n\n\t\tPROGRAM TO IMPLEMENT THE
TOWER OF HANOI");
printf("\n\n\n\n\nPLEASE ENTER THE NUMBER OF
DISCS : ");
scanf("%d",&n);
twrofhanoi(n,'X','Y','Z');
printf("\nTotal number of disc moves = %d",count);
getch();
}
3. QUEUES

A queue is a non-primitive linear data structure.


Where the operation on the queue is based on First-In-First-
Out FIFO process — the first element in the queue will be
the first one out. This is equivalent to the requirement that
whenever an element is added, all elements that were added
before have to be removed before the new element can be
removed.

For inserting elements into the queue are done from the rear
end and deletion is done from the front end, we use external
pointers called as rear and front to keep track of the status
of the queue.
During insertion, Queue Overflow condition has to be
checked. Likewise during deletion, Queue Underflow
condition is checked.

3.1 Queue operations


A ‘C’ program to implement the QUEUE of integers to
perform operations like INSERTION, DELETION and
DISPLAY using arrays.

#include<stdio.h>
#include<conio.h>
#define SIZE 5
int front=-1,rear=-1,flag,queue[SIZE];
int qinsert(int data)
{
flag=0;
if(rear<SIZE-1)
{
queue[++rear]=data;
if(front==-1)
front++;
flag=1;
}
else
printf("\nThe queue is full, Can't insert");
return(flag);
}
int qdelete()
{
int data;
flag=0;
if(front<=rear)
{
flag=1;
data=queue[front++];
printf("\nThe Element deleted from the queue is :
%d",data);
if(front>rear)
{
front=-1;
rear=-1;
}
}
else
printf("\nThe queue is empty, No elements to
delete....!!");
return(flag);
}
void qdisplay()
{
int i;
if(front==-1)
printf("\nQueue is empty...!!!");
else
for(i=front;i<=rear;i++)
printf("\nqueue[%d] = %d",i,queue[i]);
}
void main()
{
int choice,data,q=0;
while(q!=1)
{
clrscr();
printf("\n\n\n\t\t\t*****MAIN MENU*****");
printf("\n\n\n\tENTER 1 --> TO ENTER THE
ELEMENTS INTO THE QUEUE");
printf("\n\tENTER 2 --> TO DELETE THE
ELEMENTS FROM THE QUEUE");
printf("\n\tENTER 3 --> TO DISPLAY THE
CONTENTS OF THE QUEUE");
printf("\n\tENTER 4 --> TO QUIT");
printf("\n\n\nEnter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nEnter the element to be inserted : ");
scanf("%d",&data);
qinsert(data);
if(flag)
{
printf("\nThe content of the queue after
insertion is : ");
qdisplay();
}
break;
case 2:
qdelete();
if(flag)
{
printf("\nThe content of the queue after deletion
is : ");
qdisplay();
}
break;
case 3:
printf("\nThe contents of the queue is : ");
qdisplay();
break;
case 4:
q=1;
printf("\nTHANK YOU..!! HAVE A NICE
DAY");
break;
}
getch();
}
}
3.2Circular Queue

In the above mentioned linear queues, Insertion into the


queues, cannot be done, If rear pointer is equal to the
queue size, and even though, the queue has space to hold
other items. This disadvantage is overcome by using
Circular queues.

A ‘C’ program to implement a CIRCULAR QUEUE of


integers to perform Insert, delete and
display operations using arrays. Appropriate messages
for queueoverflow, queue underflow and queue empty
should be displayed.

#include<stdio.h>
#include<conio.h>
#define SIZE 5
int cq[SIZE],data,count=0,flag=0;
int rear=-1,front=0;
void Insert_cqueue()
{
flag=0;
if(count<SIZE)
{
printf("\nEnter the element : ");
scanf("%d",&data);
rear=(rear+1)%SIZE;
cq[rear]=data;
count++;
flag=1;
}
else
printf("\nCircular queue is full.!!OVERFLOW
CONDITION..!!\a");
}

void Delete_cqueue()
{

if(count==0)
{
printf("\n\aCIRCULAR QUEUE UNDERFLOW....!!");
flag=0;
return;
}
data=cq[front];
printf("\nElement deleted is : %d",data);
front=(front+1)%SIZE;
count--;
flag=1;
}

void Display_cqueue()
{
int i=front,j;
if(count==0)
{
printf("\nCircular queue is Empty");
return;
}
for(j=0;j<count;j++)
{
printf("\ncq[%d]=%d",i,cq[i]);
i=(i+1)%SIZE;
}
}

void main()
{
int choice,k=0;
do
{
clrscr();
printf("\n\n\n\n\t\t\t*****MAIN MENU*****");
printf("\n\n\n\tENTER 1 --> TO INSERT AN
ELEMENT INTO THE CIRCULAR QUEUE");
printf("\n\tENTER 2 --> TO DELETE AN ELEMENT
FROM THE CIRCULAR QUEUE");
printf("\n\tENTER 3 --> TO DISPLAY THE
CONTENTS OF THE CIRCULAR QUEUE");
printf("\n\tENTER 4 --> TO QUIT");
printf("\n\n\nEnter your choice : ");
scanf("%d",&choice);
printf("\nYour choice is --> %d",choice);
switch(choice)
{
case 1:
Insert_cqueue();
if(flag)
{
printf("\nCircular queue contents after inserting is :
\n");
Display_cqueue();
}
break;
case 2:
Delete_cqueue();
if(flag)
{
printf("\nCircular queue contents after deletion is :
\n");
Display_cqueue();
}
break;
case 3:
Display_cqueue();
break;
case 4:
k=1;
break;
}
getch();
}while(k!=1);
}

3.3 Double ended queue

A ‘C’ program to implement DOUBLE ENDED


QUEUE of integers to perform operations
9. Insert front
10.Insert rear
11.Delete front
12.Delete rear
13.Display

#include<stdio.h>
#include<conio.h>
#define SIZE 5
int front=-1,rear=-1,flag,queue[SIZE];
int qinsert_rear(int data)
{
flag=0;
if(rear<SIZE-1)
{
queue[++rear]=data;
if(front==-1)
front++;
flag=1;
}
else
printf("\nCan't insert from rear end\a");
return(flag);
}
int qdelete_front()
{
int data;
flag=0;
if(front>=0&&front<=rear)
{
flag=1;
data=queue[front++];
printf("\nThe Element deleted from the queue is :
%d",data);
if(front>rear)
{
front=-1;
rear=-1;
}
}
else
printf("\nThe queue is empty, No elements to
delete....!!");
return(flag);
}
int qinsert_front(int data)
{
flag=0;
if(front==-1&&rear==-1)
{
queue[++front]=data;
rear++;
flag=1;
return;
}
if(front!=0)
{
queue[--front]=data;
flag=1;
}
else
printf("\nCan't insert from front end\a");
return(flag);
}
int qdelete_rear()
{
int data;
flag=0;
if(rear>=0&&front<=rear)
{
flag=1;
data=queue[rear--];
printf("\nThe Element deleted from the queue is :
%d",data);
if(front>rear)
{
front=-1;
rear=-1;
}
}
else
printf("\nThe queue is empty, No elements to
delete....!!");
return(flag);
}

void qdisplay()
{
int i;
if(front==-1)
printf("\nQueue is empty...!!!");
else
for(i=front;i<=rear;i++)
printf("\nqueue[%d] = %d",i,queue[i]);
}
void main()
{
int choice,data,q=0;
while(q!=1)
{
clrscr();
printf("\n\n\n\t\t\t*****MAIN MENU*****");
printf("\n\n\n\tENTER 1 --> TO ENTER THE
ELEMENTS INTO THE QUEUE FROM THE REAR
END");
printf("\n\tENTER 2 --> TO DELETE THE
ELEMENTS FROM THE QUEUE FROM THE FRONT
END");
printf("\n\tENTER 3 --> TO ENTER THE
ELEMENTS INTO THE QUEUE FROM THE FRONT
END");
printf("\n\tENTER 4 --> TO DELETE THE
ELEMENTS FROM THE QUEUE FROM THE REAR
END");
printf("\n\tENTER 5 --> TO DISPLAY THE
CONTENTS OF THE QUEUE");

printf("\n\tENTER 6 --> TO QUIT");


printf("\n\n\nEnter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\n\n\nYOUR CHOICE IS TO ENTER
THE ELEMENT INTO THE QUEUE FROM THE REAR
END");
printf("\nEnter the element to be inserted : ");
scanf("%d",&data);
qinsert_rear(data);
if(flag)
{
printf("\nThe content of the queue after
insertion is : ");
qdisplay();
}
break;
case 2:
printf("\n\n\nYOUR CHOICE IS TO DELETE
THE ELEMENT FROM THE QUEUE FROM THE
FRONT END");
qdelete_front();
if(flag)
{
printf("\nThe content of the queue after deletion
is : ");
qdisplay();
}
break;
case 3:
printf("\n\n\nYOUR CHOICE IS TO ENTER
THE ELEMENT INTO THE QUEUE FROM THE
FRONT END");
printf("\nEnter the element to be inserted : ");
scanf("%d",&data);
qinsert_front(data);
if(flag)
{
printf("\nThe content of the queue after
insertion is : ");
qdisplay();
}
break;
case 4:
printf("\n\n\nYOUR CHOICE IS TO DELETE
THE ELEMENT FROM THE QUEUE FROM THE
FRONT END");
qdelete_rear();
if(flag)
{
printf("\nThe content of the queue after deletion
is : ");
qdisplay();
}
break;
case 5:
printf("\n\n\nYOUR CHOICE IS TO DISPLAY
THE CONTENTS OF THE QUEUE");
printf("\nThe contents of the queue is : ");
qdisplay();
break;
case 6:
q=1;
printf("\nTHANK YOU..!! HAVE A NICE
DAY");
break;
}
getch();
}
}
3.4 Priority queue

A ‘C’ program to implement PRIORITY QUEUES of


integers.

#include<stdio.h>
#include<conio.h>
#define SIZE 5
int q1[SIZE],q2[SIZE],q3[SIZE],ch;
int r1=-1,r2=-1,r3=-1;
int f1=0,f2=0,f3=0;
void Insert_queue(int n)
{
if(n==1)
if(r1<SIZE-1) q1[++r1]=ch;
if(n==2)
if(r2<SIZE-1) q2[++r2]=ch;
if(n==3)
if(r3<SIZE-1) q3[++r3]=ch;
else
printf("\nQueue %d is full!!",n);
}
void Delete_queue()
{
if(f1>r1) printf("\nQueue1 is empty!!");
else
{ printf("\nElement deleted is : %d",q1[f1++]);
return;
}
if(f2>r2) printf("\nQueue2 is empty!!");
else
{ printf("\nElement deleted is : %d",q2[f2++]);
return;
}
if(f3>r3) printf("\nQueue3 is empty!!");
else printf("\nElement deleted is : %d",q3[f3++]);
}

void Display_queue()
{
int i;

if(f1>r1)
printf("\n\n\nQueue1 is empty!!");
else
{
printf("\n\n\n");
for(i=f1;i<=r1;i++)
printf("\nq1[%d]=%d",i,q1[i]);
}

if(f2>r2)
printf("\n\n\nQueue2 is empty!!");
else
{
printf("\n\n\n");
for(i=f2;i<=r2;i++)
printf("\nq2[%d]=%d",i,q2[i]);
}

if(f3>r3)
printf("\n\n\nQueue3 is empty!!");
else
{
printf("\n\n\n");
for(i=f3;i<=r3;i++)
printf("\nq3[%d]=%d",i,q3[i]);
}
}

void main()
{
int choice,q=0,n,i;
do
{
clrscr();
printf("\n\n\n\t\t\t*****MAIN MENU******");
printf("\n\tEnter 1 --> TO INSERT");
printf("\n\tEnter 2 --> TO DELETE");
printf("\n\tEnter 3 --> TO DISPLAY");
printf("\n\tEnter 4 --> TO QUIT");
printf("\n\n\nEnter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nEnter the priority of the queue : ");
scanf("%d",&n);
if(n>=1 &&n<=3)
{
printf("\nEnter the data : ");
scanf("%d",&ch);
}
else
{
printf("\nInvalid...! priority queue number..Cannot
Insert");
getch();
break;

}
Insert_queue(n);
Display_queue();
getch();
break;
case 2:
Delete_queue();
Display_queue();
getch();
break;
case 3:
Display_queue();
getch();
break;
case 4:
q=1;
printf("\nTHANK YOU..... HAVE A NICE DAY");

break;
}
}while(!q);
getch();
}
4. LINKED LISTS
4.1 Overview
Disadvantages of static/sequential allocation technique:

14.If an item has to be deleted then all the following


items will have to be moved by one allocation.
Wastage of time.
15.Inefficient memory utilization.
16.If no consecutive memory(free) is available,
execution is not possible.

Linear Linked Lists


Types of Linked lists
17.Single Linked lists
18.Circular Single Linked Lists
19.Double Linked Lists
20.Circular Double Linked Lists.

NODE:

Each node consists of two fields. Information(info)


field and next address(next) field. The info field consists of
actual information/data/item that has to be stored in a list.

The second field next/link contains the address of the


next node. Since next field contains the address, It is of
type pointer.
Here the nodes in the list are logically adjacent to each
other.
Nodes that are physically adjacent need not be logically
adjacent in the list.
The entire linked list is accessed from an external pointer
FIRST that points to (contains the address of) the first node
in the list. (By an “external” pointer, we mean, one that is
not included within a node. Rather its value can be
accessed directly by referencing a variable).

The list containing 4 items/data 10, 20, 30 and 40 is shown


below.

The nodes in the list can be accessed using a pointer


variable. In the above fig. FIRST is the pointer having the
address of the first node of the list, Initially before creating
the list, as list is empty. The FIRST will always be
initialized to NULL in the beginning. Once the list is
created, FIRST contains the address of the first node of the
list.
As each node is having only one link/next, the list is called
single linked list and all the nodes are linked in one
direction.
Each node can be accessed by the pointer pointing (holding
the address) to that node, Say P is pointer to a particular
node, then the information field of that node can be
accessed using info(P) and the next field can be accessed
using next(P).
The arrows coming out of the next field in the fig. indicates
that the address of the succeeding node is stored in that
field.
The link field of last node contains a special value known
as NULL which is shown using a diagonal line pictorially.
This NULL pointer is used to signal the end of a list.

The basic operations of linked lists are Insertion, Deletion


and Display.
A list is a dynamic data structure. The number of nodes on
a list may vary dramatically as elements are inserted and
deleted(removed).
The dynamic nature of list may be contrasted with the static
nature of an array, whose size remains constant.
When an item has to inserted, we will have to create a
node, which has to be got from the available free memory
of the computer system, So we shall use a mechanism to
find an unused node which makes it available to us. For this
purpose we shall use the getnode operation (getnode()
function).
The C language provides the built-in functions like
malloc(), calloc(), realloc() and free(), which are stored in
alloc.h or stdlib.h header files. To dynamically allocate and
release the memory locations from/to the computer system.

4.2 Implementations
A ‘C’ program to construct a SINGLE LINKED LIST
using dynamic variables and pointers.

#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#include<process.h>
struct node
{
int info;
struct node *next;
};
typedef struct node *NODE;

NODE getnode(void)
{
NODE x;
x=(NODE) malloc(sizeof(struct node));
if(x==NULL)
{
printf("\nNO MEMORY!...!");
getch();
exit(1);
}
return (x);
}

NODE insert_front(int item, NODE first)


{
NODE temp;
temp=getnode();
temp->info=item;
temp->next=first;
return temp;
}

NODE delete_front(NODE first)


{
NODE temp;
if(first==NULL)
{
printf("\nList is empty cannot delete");
return first;
}
temp=first;
first=first->next;
printf("\nThe item deleted is %d",temp->info);
free(temp);
return first;
}

void display(NODE first)


{
NODE temp;
if(first==NULL)
{
printf("\nList is empty");
return;
}
temp=first;
while(temp!=NULL)
{
printf("\n %d ",temp->info);
temp=temp->next;
}
}

void main()
{
NODE first=NULL;
int k=0,choice,item;
while(k!=1)
{
clrscr();
printf("\nPRESS 1 --> TO INSERT FROM FRONT");
printf("\nPRESS 2 --> TO DELETE FROM FRONT");
printf("\nPRESS 3 --> TO DISPLAY THE CONTENT
OF THE LIST");
printf("\nPRESS 4 --> TO QUIT");
printf("\nEnter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nEnter the element to be inserted : ");
scanf("%d",&item);
first=insert_front(item,first);
printf("\nThe contents of the list after insertion is :
\n");
display(first);
break;
case 2:
first=delete_front(first);
printf("\nThe contents of the list is : \n");
display(first);
break;
case 3:
printf("\nThe contents of the list is : \n");
display(first);
break;
case 4:
k=1;
printf("\nTHANK YOU...!! HAVE A NICE DAY");
break;
}
getch();
}
}

A ‘C’ program performing Insert front, Insert rear,


Delete front, Delete rear functions using SINGLE
LINKED LIST

#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#include<process.h>
struct node
{
int info;
struct node *next;
};
typedef struct node *NODE;
NODE getnode(void)
{
NODE x;
x=(NODE) malloc(sizeof(struct node));
if(x==NULL)
{
printf("\nNO MEMORY!...!");
getch();
exit(1);
}
return (x);
}

NODE insert_front(int item, NODE first)


{
NODE temp;
temp=getnode();
temp->info=item;
temp->next=first;
return temp;
}
NODE insert_rear(int item, NODE first)
{
NODE temp,cur;
temp=getnode();
temp->info=item;
temp->next=NULL;
if(first==NULL)
return temp;
cur=first;
while(cur->next!=NULL)
cur=cur->next;
cur->next=temp;
return first;
}

NODE delete_front(NODE first)


{
NODE temp;
if(first==NULL)
{
printf("\nList is empty cannot delete");
return first;
}
temp=first;
first=first->next;
printf("\nThe item deleted is %d",temp->info);
free(temp);
return first;
}
NODE delete_rear(NODE first)
{
NODE cur,prev;
if(first==NULL)
{
printf("\nList is empty cannot delete");
return first;
}
if(first->next==NULL)
{
printf("\nThe item to be deleted is %d",first->info);
free(first);
first=NULL;
return first;
}
prev=NULL;
cur=first;
while(cur->next!=NULL)
{
prev=cur;
cur=cur->next;
}
printf("\nThe item deleted is %d",cur->info);
free(cur);
prev->next=NULL;
return first;
}
void display(NODE first)
{
NODE temp;
if(first==NULL)
{
printf("\nList is empty");
return;
}
temp=first;
while(temp!=NULL)
{
printf("\n %d",temp->info);
temp=temp->next;
}
}
void main()
{
NODE first=NULL;
int k=0,choice,item;
while(k!=1)
{
clrscr();
printf("\n\n\n\n\t\t\t*****MAIN MENU*****");
printf("\n\n\n\tPRESS 1 --> TO INSERT FROM
FRONT");
printf("\n\tPRESS 2 --> TO INSERT FROM REAR");
printf("\n\tPRESS 3 --> TO DELETE FROM FRONT");
printf("\n\tPRESS 4 --> TO DELETE FROM REAR");
printf("\n\tPRESS 5 --> TO DISPLAY THE CONTENT
OF THE LIST");
printf("\n\tPRESS 6 --> TO QUIT");
printf("\n\n\nEnter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nEnter the element to be inserted : ");
scanf("%d",&item);
first=insert_front(item,first);
printf("\nThe contents of the list after insertion is :
\n");
display(first);
break;
case 2:
printf("\nEnter the element to be inserted : ");
scanf("%d",&item);
first=insert_rear(item,first);
printf("\nThe contents of the list after insertion is :
\n");
display(first);
break;
case 3:
first=delete_front(first);
printf("\nThe contents of the list after deletion is :
\n");
display(first);
break;
case 4:
first=delete_rear(first);
printf("\nThe contents of the list after deletion is :
\n");
display(first);
break;
case 5:
printf("\nThe contents of the list is : \n");
display(first);
break;
case 6:
k=1;
break;
}
getch();
}
}
A ‘C’ program to create an ORDERED LIST using
dynamic variables and pointers.

#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#include<process.h>
struct node
{
int info;
struct node *next;
};
typedef struct node *NODE;

NODE getnode(void)
{
NODE x;
x=(NODE) malloc(sizeof(struct node));
if(x==NULL)
{
printf("\nNO MEMORY!...!");
getch();
exit(1);
}
return (x);
}
NODE insert(int item, NODE first)
{
NODE temp,prev,cur;
temp=getnode();
temp->info=item;
temp->next=NULL;
if(first==NULL)
return temp;
if(item<first->info)
{
temp->next=first;
return temp;
}
prev=NULL;
cur=first;
while(cur!=NULL && item > cur->info)
{
prev=cur;
cur=cur->next;
}
prev->next=temp;
temp->next=cur;
return first;
}

void display(NODE first)


{
NODE temp;
if(first==NULL)
{
printf("\nList is empty");
return;
}
temp=first;
while(temp!=NULL)
{
printf("\n %d",temp->info);
temp=temp->next;
}
}

void main()
{
NODE first=NULL;
int k=0,choice,item;
while(k!=1)
{
clrscr();
printf("\nPRESS 1 --> TO INSERT INTO AN
ORDERED LINKED LIST");
printf("\nPRESS 2 --> TO DISPLAY THE CONTENT
OF THE LIST");
printf("\nPRESS 3 --> TO QUIT");
printf("\nEnter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nEnter the element to be inserted : ");
scanf("%d",&item);
first=insert(item,first);
printf("\nThe contents of the list after insertion is :
\n");
display(first);
break;
case 2:
display(first);
break;
case 3:
k=1;
printf("\nHAVE A NICE DAY.. THANK YOU");
break;
}
getch();
}
}
A ‘C’ program to CREATE and MERGE two SORTED
LISTS into a single list (Merging two ordered link list)

#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#include<process.h>
struct node
{
int info;
struct node *next;
};
typedef struct node *NODE;

NODE getnode(void)
{
NODE x;
x=(NODE) malloc(sizeof(struct node));
if(x==NULL)
{
printf("\nNO MEMORY!...!");
getch();
exit(1);
}
return (x);
}
NODE insert(int item, NODE first)
{
NODE temp,prev,cur;

temp=getnode();
temp->info=item;
temp->next=NULL;
if(first==NULL)
return temp;
if(item<first->info)
{
temp->next=first;
return temp;
}
prev=NULL;
cur=first;
while(cur!=NULL && item > cur->info)
{
prev=cur;
cur=cur->next;
}
prev->next=temp;
temp->next=cur;
return first;
}

void display(NODE first)


{
NODE temp;
if(first==NULL)
{
printf("\nList is empty");
return;
}
temp=first;
while(temp!=NULL)
{
printf("\n %d",temp->info);
temp=temp->next;
}
}

NODE merge(NODE first1, NODE first2)


{
NODE cur,first3;
cur=first3=getnode();
while(first1!=NULL && first2!=NULL)
{
if(first1->info < first2->info)
{
cur->next=first1;
first1=first1->next;
}
else
{
cur->next=first2;
first2=first2->next;
}
cur=cur->next;
}
if(first1!=NULL)
cur->next=first1;
else
cur->next=first2;
return first3->next;
}
void main()
{
NODE first1=NULL, first2=NULL, first3=NULL;
int k=0,choice,item;
while(k!=1)
{
clrscr();
printf("\nPRESS 1 --> TO INSERT INTO THE FIRST
ORDERED LINKED LIST");
printf("\nPRESS 2 --> TO INSERT INTO THE
SECOND ORDERED LINKED LIST");
printf("\nPRESS 3 --> TO DISPLAY THE CONTENTS
OF THE LISTS");
printf("\nPRESS 4 --> TO MERGE BOTH THE
LISTS");
printf("\nPRESS 5 --> TO QUIT");
printf("\nEnter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nEnter the element to be inserted into list1 :
");
scanf("%d",&item);
first1=insert(item,first1);
printf("\nThe contents of the list1 after insertion
is : \n");
display(first1);
break;
case 2:
printf("\nEnter the element to be inserted into list1 :
");
scanf("%d",&item);
first2=insert(item,first2);
printf("\nThe contents of the list2 after insertion
is : \n");
display(first2);
break;
case 3:
printf("\nThe content of list1 is : \n\n");
display(first1);
printf("\nThe content of list2 is : \n\n");
display(first2);
break;
case 4:
first3=merge(first1,first2);
printf("\nThe content of the list3 after merging is :
\n\n");
display(first3);
//break;
case 5:
k=1;
printf("\nHAVE A NICE DAY.. THANK YOU");
break;
}
getch();
}
}

Write a C program to create an ordered linked


list(ascending order) based on the rank of the student.
Where each node consists of the following information:
student id (integer), student name (string) and rank
(integer).

#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#include<process.h>
struct stud
{
int regno;
char name[20];
int rank;
struct stud *next;
};
typedef struct stud *NODE;

NODE getnode(void)
{
NODE x;
x=(NODE) malloc(sizeof(struct stud));
if(x==NULL)
{
printf("\nNO MEMORY!...!");
getch();
exit(1);
}
return (x);
}
NODE insert(NODE first)
{
NODE temp,prev,cur;

temp=getnode();
printf("\nEnter the student's regno : ");
scanf("%d",&temp->regno);
printf("\nEnter the student's name : ");
fflush(stdin);
gets(temp->name);
printf("\nEnter the rank of the student : ");
scanf("%d",&temp->rank);
temp->next=NULL;
if(first==NULL)
return temp;
if(temp->rank<first->rank)
{
temp->next=first;
return temp;
}
prev=NULL;
cur=first;
while(cur!=NULL && temp->rank > cur->rank)
{
prev=cur;
cur=cur->next;
}
prev->next=temp;
temp->next=cur;
return first;
}

void display(NODE first)


{
NODE temp;
if(first==NULL)
{
printf("\nList is empty");
return;
}
temp=first;
while(temp!=NULL)
{
printf("\n\n\n Student's Regno : %d",temp->regno);
printf("\n Student's Name : %s",temp->name);
printf("\n Student's Rank : %d",temp->rank);
temp=temp->next;
}
}

void main()
{
NODE first=NULL;
int k=0,choice;
while(k!=1)
{
clrscr();
printf("\n\n\n\t\t\t*****MAIN MENU*****");
printf("\n\n\n\tPRESS 1 --> TO INSERT STUDENT'S
INFORMATION INTO AN ORDERED LINKED LIST");
printf("\n\tPRESS 2 --> TO DISPLAY THE CONTENT
OF THE LIST");
printf("\n\tPRESS 3 --> TO QUIT");
printf("\n\n\nEnter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
first=insert(first);
printf("\nThe contents of the list after insertion is :
\n");
display(first);
break;
case 2:
printf("\nTHE CONTENT OF THE STUDENT'S
ORDERED LIST BASED ON THE RANK IS AS
FOLLOWS");
display(first);
break;
case 3:
k=1;
printf("\nHAVE A NICE DAY.. THANK YOU");
break;
}
getch();
}
}

A ‘C’ program to DELETE a node whose INFO FIELD


IS SPECIFIED.

#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#include<process.h>
struct node
{
int info;
struct node *next;
};
typedef struct node *NODE;

NODE getnode(void)
{
NODE x;
x=(NODE) malloc(sizeof(struct node));
if(x==NULL)
{
printf("\nNO MEMORY!...!");
getch();
exit(1);
}
return (x);
}

NODE insert_front(int item, NODE first)


{
NODE temp;
temp=getnode();
temp->info=item;
temp->next=first;
return temp;
}
NODE insert_rear(int item, NODE first)
{
NODE temp,cur;
temp=getnode();
temp->info=item;
temp->next=NULL;
if(first==NULL)
return temp;
cur=first;
while(cur->next!=NULL)
cur=cur->next;
cur->next=temp;
return first;
}
NODE delete_info(int item, NODE first)
{
NODE cur,prev;
if(item==first->info)
{
cur=first;
first=first->next;
printf("\nThe item deleted is : %d",cur->info);
free(cur);
return first;
}
prev=NULL;
cur=first;
while(cur!=NULL && item != cur->info)
{
prev=cur;
cur=cur->next;
}
if(item==cur->info)
{
prev->next=cur->next;
printf("\nThe item deleted is : %d",cur->info);
free(cur);
}
return first;
}
void display(NODE first)
{
NODE temp;
if(first==NULL)
{
printf("\nList is empty");
return;
}
temp=first;
while(temp!=NULL)
{
printf("\n %d",temp->info);
temp=temp->next;
}
}
void main()
{
NODE first=NULL;
int k=0,choice,item;
while(k!=1)
{
clrscr();
printf("\nPRESS 1 --> TO INSERT FROM FRONT");
printf("\nPRESS 2 --> TO INSERT FROM REAR");
printf("\nPRESS 3 --> TO DELETE AN ELEMENT
WHOSE INFORMATION IS SPECIFIED");
printf("\nPRESS 4 --> TO DISPLAY THE CONTENT
OF THE LIST");
printf("\nPRESS 5 --> TO QUIT");
printf("\nEnter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nEnter the element to be inserted : ");
scanf("%d",&item);
first=insert_front(item,first);
printf("\nThe contents of the list after insertion is :
\n");
display(first);
break;
case 2:
printf("\nEnter the element to be inserted : ");
scanf("%d",&item);
first=insert_rear(item,first);
printf("\nThe contents of the list after insertion is :
\n");
display(first);
break;
case 3:
printf("\nEnter the item to be deleted : ");
scanf("%d",&item);
first=delete_info(item,first);
break;
case 4:
printf("\nThe contents of the list is : \n");
display(first);
break;
case 5:
k=1;
printf("\nTHANK YOU... HAVE A NICE DAY");
break;
}
getch();
}
}

A ‘C’ program to SEARCH FOR A SPECIFIC NODE


in list

#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#include<process.h>
struct node
{
int info;
struct node *next;
};
typedef struct node *NODE;

NODE getnode(void)
{
NODE x;
x=(NODE) malloc(sizeof(struct node));
if(x==NULL)
{
printf("\nNO MEMORY!...!");
getch();
exit(1);
}
return (x);
}
NODE insert(int item, NODE first)
{
NODE temp,prev,cur;

temp=getnode();
temp->info=item;
temp->next=NULL;
if(first==NULL)
return temp;
if(item<first->info)
{
temp->next=first;
return temp;
}
prev=NULL;
cur=first;
while(cur!=NULL && item > cur->info)
{
prev=cur;
cur=cur->next;
}
prev->next=temp;
temp->next=cur;
return first;
}

void display(NODE first)


{
NODE temp;
if(first==NULL)
{
printf("\nList is empty");
return;
}
temp=first;
while(temp!=NULL)
{
printf("\n %d",temp->info);
temp=temp->next;
}
}
NODE search(int item,NODE first)
{
NODE cur;
int pos;
cur=first;
pos=1;
while(cur!=NULL && item != cur->info)
{
cur=cur->next;
pos++;
}
if(cur==NULL)
{
printf("\nSEARCH UNSUCESSFUL!!");
return first;
}
printf("\nSearch Sucessful... %d is found in position
%d",item,pos);
return first;
}

void main()
{
NODE first=NULL;
int k=0,choice,item;
while(k!=1)
{
clrscr();
printf("\nPRESS 1 --> TO INSERT INTO AN
ORDERED LINKED LIST");
printf("\nPRESS 2 --> TO SEARCH FOR AN ITEM");
printf("\nPRESS 3 --> TO DISPLAY THE CONTENT
OF THE LIST");
printf("\nPRESS 4 --> TO QUIT");
printf("\nEnter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nEnter the element to be inserted : ");
scanf("%d",&item);
first=insert(item,first);
printf("\nThe contents of the list after insertion is :
\n");
display(first);
break;
case 2:
printf("\nEnter the element to be searched : ");
scanf("%d",&item);
first=search(item,first);
break;
case 3:
display(first);
break;
case 4:
k=1;
printf("\nHAVE A NICE DAY.. THANK YOU");
break;
}
getch();
}
}
Function to reverse the linked list without using extra
nodes.
NODE reverse(NODE first)
{
NODE cur,prev;
prev=NULL;
while(first!=NULL)
{
cur=first;
first=first->next;
cur->next=prev;
prev=cur;
}
return cur;
}

Write a C program using dynamic variables and


pointers to construct a single linked list consisting of the
following STUDENT INFORMATION in each node:
student id (integer), student name (character string)
and semester (integer). The operations to be supported
are:
21.The insertion operation
At the front of a list
At the back of the list
At any position in the list
22.Deleting a node based on student id. If the
specified node is not present in the list an error
message should be displayed. Both the options
should be demonstrated.
23.Searching a node based on student id and update
the information content. If the specified node is not
present in the list an error message should be
displayed. Both the situations should be
demonstrated.
24.Displaying all the nodes in the list.

#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#include<process.h>
struct stud
{
int id;
char st_name[25];
int sem;
struct stud *next;
};
typedef struct stud *NODE;

NODE getnode(void)
{
NODE x;
x=(NODE) malloc(sizeof(struct stud));
if(x==NULL)
{
printf("\nNO MEMORY!...!");
getch();
exit(1);
}
return (x);
}

NODE insert_front(NODE first)


{
NODE temp;
temp=getnode();
printf("\nEnter the student's ID : ");
scanf("%d",&temp->id);
printf("\nEnter student's name : ");
fflush(stdin);
gets(temp->st_name);
printf("\nEnter the student's semester : ");
scanf("%d",&temp->sem);
temp->next=first;
return temp;
}
NODE insert_rear(NODE first)
{
NODE temp,cur;
temp=getnode();
printf("\nEnter the student's ID : ");
scanf("%d",&temp->id);
printf("\nEnter student's name : ");
fflush(stdin);
gets(temp->st_name);
printf("\nEnter the student's semester : ");
scanf("%d",&temp->sem);
temp->next=NULL;
if(first==NULL)
return temp;
cur=first;
while(cur->next!=NULL)
cur=cur->next;
cur->next=temp;
return first;
}

NODE insert_position(NODE first,int pos)


{
NODE temp,cur;
int count=1;
temp=getnode();
printf("\nEnter the student's ID : ");
scanf("%d",&temp->id);
printf("\nEnter student's name : ");
fflush(stdin);
gets(temp->st_name);
printf("\nEnter the student's semester : ");
scanf("%d",&temp->sem);
temp->next=NULL;
if(first==NULL)
return temp;
cur=first;
while(cur->next!=NULL&&count!=pos-1)
{
cur=cur->next;
count++;
}
if(count!=pos-1)
{
printf("\nInvalid position..!! Cannot Insert");
free(temp);
return first;
}
temp->next=cur->next;
cur->next=temp;
return first;
}

NODE delete_id(NODE first,int id)


{
NODE cur,prev;
if(first==NULL)
{
printf("\nList is empty cannot delete");
return first;
}
if(first->next==NULL&&id==first->id)
{
printf("\n\nThe following information is being deleted");
printf("\nStudent ID : %d",first->id);
printf("\nStudent Name : %s",first->st_name);
printf("\nStudent Semester : %d",first->sem);
free(first);
first=NULL;
return first;
}

prev=NULL;
cur=first;
while(cur->next!=NULL&&id!=cur->id)
{
prev=cur;
cur=cur->next;
}
if(id==cur->id)
{
printf("\n\nSearch Succesful... The following information
is being deleted");
printf("\nStudent ID : %d",cur->id);
printf("\nStudent Name : %s",cur->st_name);
printf("\nStudent Semester : %d",cur->sem);
prev->next=cur->next;
if(first==cur)
first=first->next;
free(cur);
return first;
}
printf("\nSearch Unsucessful, %d student's id not found in
the list",id);
return first;
}
NODE search_update(NODE first,int id)
{
NODE cur,prev;
if(first==NULL)
{
printf("\nList is empty Search Unsucessful");
return first;
}

prev=NULL;
cur=first;
while(cur->next!=NULL&&id!=cur->id)
cur=cur->next;
if(id==cur->id)
{
printf("\n\nSearch Succesful...\nEnter the new student's
semester ");
scanf("%d",&cur->sem);
printf("\nThe student's updated record is as follows:\n\n");
printf("\nStudent ID : %d",cur->id);
printf("\nStudent Name : %s",cur->st_name);
printf("\nStudent Semester : %d",cur->sem);
return first;
}
printf("\nSearch Unsucessful, %d student's id not found in
the list",id);
return first;
}

void display(NODE first)


{
NODE temp;
if(first==NULL)
{
printf("\nList is empty");
return;
}
temp=first;
while(temp!=NULL)
{
printf("\n\n\n\nStudent ID : %d",temp->id);
printf("\nStudent Name : %s",temp->st_name);
printf("\nStudent Semester : %d",temp->sem);
temp=temp->next;
}
}
void main()
{
NODE first=NULL;
int k=0,choice,pos,id;
while(k!=1)
{
clrscr();
printf("\nPRESS 1 --> TO INSERT FROM FRONT");
printf("\nPRESS 2 --> TO INSERT FROM REAR");
printf("\nPRESS 3 --> TO INSERT IN THE SPECIFIED
POSITION");
printf("\nPRESS 4 --> TO DELETE WHOSE ID IS
SPECIFIED");
printf("\nPRESS 5 --> TO SEARCH AN ID AND
UPDATE");
printf("\nPRESS 6 --> TO DISPLAY THE CONTENT
OF THE LIST");
printf("\nPRESS 7 --> TO QUIT");
printf("\nEnter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
first=insert_front(first);
printf("\nThe contents of the list after insertion is :
\n");
display(first);
break;
case 2:
first=insert_rear(first);
printf("\nThe contents of the list after insertion is :
\n");
display(first);
break;
case 3:
printf("\nEnter the position of insertion into the
linked list : ");
scanf("%d",&pos);
first=insert_position(first,pos);
printf("\nThe contents of the list after insertion is :
\n");
display(first);
break;
case 4:
printf("\nEnter the student's id to delete : ");
scanf("%d",&id);
first=delete_id(first,id);
printf("\nThe contents of the list after deletion is :
\n");
display(first);
break;
case 5:
printf("\nEnter the Student's ID whose info has to be
updated : ");
scanf("%d",&id);
first=search_update(first,id);
printf("\nThe contents of the list after search is : \n");
display(first);
break;
case 6:
printf("\nThe contents of the list is : \n");
display(first);
break;
case 7:
k=1;
printf("\nTHANK YOU... HAVE A NICE
DAY..!!");
break;
}
getch();
}
}

A ‘C’ program to construct a DOUBLY LINKED LIST


of integers.

#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#include<process.h>
struct node
{
int info;
struct node *prev;
struct node *next;
};
typedef struct node *NODE;

NODE getnode()
{
NODE x;
x=(NODE) malloc(sizeof(struct node));
if(x==NULL)
{
printf("\nNO MEMORY!...!");
getch();
exit(1);
}
return x;
}
NODE insert_front(int item,NODE head)
{
NODE temp,cur;
temp=getnode();
temp->info=item;
cur=head->next;

head->next=temp;
temp->prev=head;
temp->next=cur;
cur->prev=temp;

return head;
}
NODE insert_rear(int item,NODE head)
{
NODE temp,cur;
temp=getnode();
temp->info=item;
cur=head->prev;
head->prev=temp;
temp->next=head;
temp->prev=cur;
cur->next=temp;

return head;
}
NODE delete_front(NODE head)
{
NODE cur,next;
if(head->next==head)
{
printf("\nList is empty");
return head;
}

cur=head->next;
next=cur->next;
head->next=next;
next->prev=head;
printf("\nThe item deleted is %d",cur->info);
free(cur);
return head;
}
NODE delete_rear(NODE head)
{
NODE cur,prev;
if(head->prev==head)
{
printf("\nList is empty");
return head;
}
cur=head->prev;
prev=cur->prev;
head->prev=prev;
prev->next=head;
printf("\nThe item deleted is %d",cur->info);
free(cur);
return head;
}
void display(NODE head)
{
NODE temp;
if(head->next==head)
{
printf("\nDoubly linked List is empty");
return;
}
printf("\nThe contents of the Doubly Linked list is :\n");
for(temp=head->next;temp!=head;temp=temp->next)
printf("\n%d",temp->info);
}

void main()
{
NODE head;
int choice,item,k=0;
head=getnode();
head->next=head;
head->prev=head;
while(k!=1)
{
clrscr();
printf("\n\n\n\t\t\t******MAIN MENU*******");
printf("\n\tENTER 1 --> TO INSERT ITEMS FROM
FRONT INTO THE LIST");
printf("\n\tENTER 2 --> TO INSERT ITEMS FROM
REAR INTO THE LIST");
printf("\n\tENTER 3 --> TO DELETE ITEMS FROM
FRONT OF THE LIST");
printf("\n\tENTER 4 --> TO DELETE ITEMS FROM
REAR OF THE LIST");
printf("\n\tENTER 5 --> TO DISPLAY THE
CONTENTS OF THE LIST");
printf("\n\tENTER 6 --> TO QUIT");
printf("\nEnter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nEnter the item to be inserted : ");
scanf("%d",&item);
head=insert_front(item,head);
printf("\nThe list contents after insertion is :\n");
display(head);
break;
case 2:
printf("\nEnter the item to be inserted : ");
scanf("%d",&item);
head=insert_rear(item,head);
printf("\nThe list contents after insertion is :\n");
display(head);
break;
case 3:
head=delete_front(head);
printf("\nThe list contents after deletion is :\n");
display(head);
break;
case 4:
head=delete_rear(head);
printf("\nThe list contents after deletion is :\n");
display(head);
break;
case 5:
display(head);
break;
case 6:
k=1;
printf("\nQUITTING FROM THE
PROGRAM!!!");
break;
}
getch();
}
}

Write a C program to perform the following operations


using doubly linked lists:
Lab program
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#include<process.h>
struct node
{
int info;
struct node *prev;
struct node *next;
};
typedef struct node *NODE;
int flag=0;
NODE getnode()
{
NODE x;
x=(NODE) malloc(sizeof(struct node));
if(x==NULL)
{
printf("\nNO MEMORY!...!");
getch();
exit(1);
}
return x;
}
NODE insert_front(int item,NODE head)
{
NODE temp,cur;
temp=getnode();
temp->info=item;
cur=head->next;

head->next=temp;
temp->prev=head;
temp->next=cur;
cur->prev=temp;
return head;
}

NODE insert_left(int key,NODE head)


{
NODE temp,cur,prev;
int item;
if(head->next==head)
{
printf("\nList is empty... cannot find the %d key",key);
return head;
}
cur=head->next;
while(cur->next!=head && cur->info!=key)
cur=cur->next;
if(cur->info==key)
{
printf("\nThe key %d node is found. Enter the element to
insert to its left : ",key);
scanf("%d",&item);
temp=getnode();
temp->info=item;
temp->prev=cur->prev;
temp->next=cur;
prev=cur->prev;
prev->next=temp;
cur->prev=temp;
flag=1;
return head;
}
printf("\nThe key %d node is not found in the list. ",key);
return head;
}
NODE delete_info(int item,NODE head)
{
NODE cur,prev,next;
if(head->next==head)
{
printf("\nList is empty");
return head;
}
cur=head->next;
while(cur->next!=head&&item!=cur->info)
cur=cur->next;
if(cur->info==item)
{
printf("\nThe item deleted is %d",cur->info);
prev=cur->prev;
prev->next=cur->next;
next=cur->next;
next->prev=prev;
free(cur);
flag=1;
return head;
}
printf("\nThe %d item not found int the list, Cannot
delete",item);
return head;
}
void display(NODE head)
{
NODE temp;
if(head->next==head)
{
printf("\nDoubly linked List is empty");
return;
}
for(temp=head->next;temp!=head;temp=temp->next)
printf("%d\t",temp->info);
}

void main()
{
NODE head;
int choice,item,k=0;
head=getnode();
head->next=head;
head->prev=head;
while(k!=1)
{
clrscr();
printf("\n\n\n\t\t\t******MAIN MENU*******\n\n\n");
printf("\n\tENTER 1 --> TO INSERT ITEMS FROM
FRONT INTO THE LIST");
printf("\n\tENTER 2 --> TO INSERT ITEMS TO THE
LEFT OF THE KEY");
printf("\n\tENTER 3 --> TO DELETE SPECIFIED
ITEM FROM THE LIST");
printf("\n\tENTER 4 --> TO DISPLAY THE
CONTENTS OF THE LIST");
printf("\n\tENTER 5 --> TO QUIT");
printf("\n\n\n\nEnter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nEnter the item to be inserted : ");
scanf("%d",&item);
head=insert_front(item,head);
printf("\nThe Content of the Double linked list
after insertion is : \n");
display(head);
break;
case 2:
printf("\nEnter the key element to whose left
insertion has to be done : ");
scanf("%d",&item);
flag=0;
head=insert_left(item,head);
if(flag)
{
printf("\nThe Content of the Double linked list
after insertion is : \n");
display(head);
}
break;
case 3:
printf("\nEnter the item to be deleted : ");
scanf("%d",&item);
flag=0;
head=delete_info(item,head);
if(flag)
{
printf("\nThe Content of the Double linked list
after deletion is : \n");
display(head);
}

break;
case 4:
printf("\nThe contents of the Doubly Linked list
is :\n");
display(head);
break;
case 5:
k=1;
printf("\nQUITTING FROM THE
PROGRAM!!!\n\n\nHAVE A NICE DAY");
break;
}
getch();
}
}
5. TREES

5.1 Definition: A data structure which is accessed


beginning at the root node. Each node is either a leaf or an
internal node. An internal node has one or more child nodes
and is called the parent of its child nodes. All children of
the same node aresiblings. Contrary to a physical tree, the
root is usually depicted at the top of the structure, and the
leaves are depicted at the bottom.
A tree can also be defined as a connected, acyclic di-graph.

Binary tree: A tree with utmost two children for each node.
Complete binary tree: A binary tree in which every level,
except possibly the deepest, is completely filled. At depth
n, the height of the tree, all nodes must be as far left as
possible.
Binary search tree: A binary tree where every node’s left
subtree has keys less than the node's key, and every right
subtree has keys greater than the node's key.
Tree traversal is a technique for processing the nodesof a
tree in some order.
The different tree traversal techniques are Pre-order, In-
order and Post-order traversal.
In Pre-order traversal, the tree node is visited first and the
left subtree is traversed recursively and later right sub-tree
is traversed recursively.

A C Program to create a tree, traverse and search for


an item.
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<alloc.h>
#include<process.h>
struct tree
{
int info;
struct tree *lchild;
struct tree *rchild;
};
typedef struct tree *TREE;

TREE getnode()
{
TREE x;
x=(TREE) malloc(sizeof(struct tree));
if(x==NULL)
{
printf("\nNO MEMORY!...!");
getch();
exit(1);
}
return x;
}
TREE insert(int item,TREE root)
{
TREE temp,cur,prev;
char path[20];
int i,len;
temp=getnode();
temp->info=item;
temp->lchild=temp->rchild=NULL;
if(root==NULL)
return temp;
printf("\nEnter the path of insertion : ");
fflush(stdin);
gets(path);
len=strlen(path);
prev=NULL;
cur=root;
for(i=0;i<len&&cur!=NULL;i++)
{
prev=cur;
if(path[i]=='l'||path[i]=='L')
cur=cur->lchild;
else if(path[i]=='r'||path[i]=='R')
cur=cur->rchild;
else
{
printf("\nInvalid path...!!");
free(temp);
return root;
}
}
if(cur!=NULL||i!=len)
{
printf("\nInsertion not possible !...!");
free (temp);
return root;
}
if(path[--i]=='l')
prev->lchild=temp;
else
prev->rchild=temp;
return root;
}

void preorder(TREE root)


{
if(root!=NULL)
{
printf("\t%d",root->info);
preorder(root->lchild);
preorder(root->rchild);
}
}

void inorder(TREE root)


{
if(root!=NULL)
{
inorder(root->lchild);
printf("\t%d",root->info);
inorder(root->rchild);
}
}

void postorder(TREE root)


{
if(root!=NULL)
{
postorder(root->lchild);
postorder(root->rchild);
printf("\t%d",root->info);
}
}

void search(int item,TREE root, int *flag)


{
if(root!=NULL)
{
search(item,root->lchild,flag);
if(item==root->info)
{
*flag=1;
return;
}
search(item,root->rchild,flag);
}
}

void main()
{
TREE root=NULL;
int choice,item,flag,k=0;

while(k!=1)
{
clrscr();
printf("\n\n\n\t\t\t******MAIN MENU*******");
printf("\n\n\n\tENTER 1 --> TO INSERT INTO THE
TREE");
printf("\n\tENTER 2 --> TO TRAVERSE THE TREE
IN PREORDER");
printf("\n\tENTER 3 --> TO TRAVERSE THE TREE
IN INORDER");
printf("\n\tENTER 4 --> TO TRAVERSE THE TREE
IN POSTORDER");
printf("\n\tENTER 5 --> TO SEARCH FOR AN ITEM
IN THE TREE");
printf("\n\tENTER 6 --> TO QUIT");
printf("\n\n\nEnter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nEnter the item to be inserted : ");
scanf("%d",&item);
root=insert(item,root);
break;
case 2:
if(root==NULL)
printf("\nTree is empty");
else
{
printf("\nPreorder traversal is : \n");
preorder(root);
}
break;
case 3:
if(root==NULL)
printf("\nTree is empty");
else
{
printf("\nInorder traversal is : \n");
inorder(root);
}

break;
case 4:
if(root==NULL)
printf("\nTree is empty");
else
{
printf("\nPostorder traversal is : \n");
postorder(root);
}

break;
case 5:
if(root==NULL)
printf("\nTree is empty");
else
{
printf("\nEnter item to be searched : ");
scanf("%d",&item);
flag=0;
search(item,root,&flag);
if(flag==1)
printf("\nSearch successful");
else
printf("\nSearch Unsucessful");
}
break;
case 6:
k=1;
printf("\nTHANK YOU.. HAVE A NICE DAY
QUITTING FROM THE PROGRAM!!!");
break;
}
getch();
}
}

5.2 Implementations

Write a C program to perform the following operations:


i)Construct a Binary search tree of integers.
ii)Traverse the tree in inorder, preorder and postorder.
iii) Search an item in BST.

#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<alloc.h>
#include<process.h>
struct tree
{
int info;
struct tree *lchild;
struct tree *rchild;
};
typedef struct tree *TREE;
TREE getnode()
{
TREE x;
x=(TREE) malloc(sizeof(struct tree));
if(x==NULL)
{
printf("\nNO MEMORY!...!");
getch();
exit(1);
}
return x;
}
TREE insert_bst(int item,TREE root)
{
TREE temp,cur,prev;
temp=getnode();
temp->info=item;
temp->lchild=temp->rchild=NULL;
if(root==NULL)
return temp;
prev=NULL;
cur=root;
while(cur!=NULL)
{
prev=cur;
if(item<cur->info)
cur=cur->lchild;
else
cur=cur->rchild;
}
if(item<prev->info)
prev->lchild=temp;
else
prev->rchild=temp;
return root;
}

void preorder(TREE root)


{
if(root!=NULL)
{
printf("\t%d",root->info);
preorder(root->lchild);
preorder(root->rchild);
}
}

void inorder(TREE root)


{
if(root!=NULL)
{
inorder(root->lchild);
printf("\t%d",root->info);
inorder(root->rchild);
}
}

void postorder(TREE root)


{
if(root!=NULL)
{
postorder(root->lchild);
postorder(root->rchild);
printf("\t%d",root->info);
}
}

void search_bst(int item,TREE root, int *flag)


{
TREE cur;
cur=root;
while(cur!=NULL && item !=cur->info)
{
if(item<cur->info)
cur=cur->lchild;
else
cur=cur->rchild;
}
if(cur->info==item)
*flag=1;
}

void main()
{
TREE root=NULL;
int choice,item,flag,k=0;

while(k!=1)
{
clrscr();
printf("\n\n\n\t\t\t******MAIN MENU*******");
printf("\n\n\n\tENTER 1 --> TO INSERT INTO THE
TREE");
printf("\n\tENTER 2 --> TO TRAVERSE THE TREE
IN PREORDER");
printf("\n\tENTER 3 --> TO TRAVERSE THE TREE
IN INORDER");
printf("\n\tENTER 4 --> TO TRAVERSE THE TREE
IN POSTORDER");
printf("\n\tENTER 5 --> TO SEARCH FOR AN ITEM
IN THE TREE");
printf("\n\tENTER 6 --> TO QUIT");
printf("\n\n\nEnter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nEnter the item to be inserted : ");
scanf("%d",&item);
root=insert_bst(item,root);
break;
case 2:
if(root==NULL)
printf("\nTree is empty");
else
{
printf("\nPreorder traversal is : \n");
preorder(root);
}
break;
case 3:
if(root==NULL)
printf("\nTree is empty");
else
{
printf("\nInorder traversal is : \n");
inorder(root);
}

break;
case 4:
if(root==NULL)
printf("\nTree is empty");
else
{
printf("\nPostorder traversal is : \n");
postorder(root);
}

break;
case 5:
if(root==NULL)
printf("\nTree is empty");
else
{
printf("\nEnter item to be searched : ");
scanf("%d",&item);
flag=0;
search_bst(item,root,&flag);
if(flag==1)
printf("\nSearch successful");
else
printf("\nSearch Unsucessful");
}
break;
case 6:
k=1;
printf("\nTHANK YOU.. HAVE A NICE DAY
QUITTING FROM THE PROGRAM!!!");
break;
}
getch();
}
}

Write a C program to perform i)insert elements into the


BST, ii)Find the maximum element, iii) Find the
minimum element, iv) to search for a specified element,
v)to traverse in preorder, inorder, postorder, vi)to
delete a specified item and vii)display operations.
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<alloc.h>
#include<process.h>
struct tree
{
int info;
struct tree *lchild;
struct tree *rchild;
};
typedef struct tree *TREE;

TREE getnode()
{
TREE x;
x=(TREE) malloc(sizeof(struct tree));
if(x==NULL)
{
printf("\nNO MEMORY!...!");
getch();
exit(1);
}
return x;
}
TREE insert_bst(int item,TREE root)
{
TREE temp,cur,prev;
temp=getnode();
temp->info=item;
temp->lchild=temp->rchild=NULL;
if(root==NULL)
return temp;
prev=NULL;
cur=root;
while(cur!=NULL)
{
prev=cur;
if(item<cur->info)
cur=cur->lchild;
else
cur=cur->rchild;
}
if(item<prev->info)
prev->lchild=temp;
else
prev->rchild=temp;
return root;
}

void preorder(TREE root)


{
if(root!=NULL)
{
printf("\t%d",root->info);
preorder(root->lchild);
preorder(root->rchild);
}
}

void inorder(TREE root)


{
if(root!=NULL)
{
inorder(root->lchild);
printf("\t%d",root->info);
inorder(root->rchild);
}
}

void postorder(TREE root)


{
if(root!=NULL)
{
postorder(root->lchild);
postorder(root->rchild);
printf("\t%d",root->info);
}
}

void search_bst(int item,TREE root, int *flag)


{
TREE cur;
cur=root;
while(cur!=NULL && item !=cur->info)
{
if(item<cur->info)
cur=cur->lchild;
else
cur=cur->rchild;
}
if(cur->info==item)
*flag=1;
}
void search_max(TREE root)
{
TREE cur;
if(root==NULL)
{
printf("\nThe Tree is empty...");
getch();
return;
}
cur=root;
while(cur->rchild!=NULL)
cur=cur->rchild;
printf("\nThe maximum element in the tree is : %d",cur-
>info);
}
void search_min(TREE root)
{
TREE cur;
if(root==NULL)
{
printf("\nThe Tree is empty...");
getch();
return;
}
cur=root;
while(cur->lchild!=NULL)
cur=cur->lchild;
printf("\nThe minimum element in the tree is : %d",cur-
>info);
}

TREE delete_bst(int item, TREE root)


{
TREE temp,cur,prev,next;
if(root==NULL)
{
printf("\nTree is empty... Cannot delete");
getch();
return root;
}
prev=NULL;
cur=root;
while(cur!=NULL && item!=cur->info)
{
prev=cur;
if(item<cur->info)
cur=cur->lchild;
else
cur=cur->rchild;
}
if(cur==NULL)
{
printf("\n%d not found in the tree..Cannot delete",item);
getch();
return root;
}
if(cur->lchild==NULL)
temp=cur->rchild;
else if(cur->rchild==NULL)
temp=cur->lchild;
else
{
next=cur->rchild;
while(next->lchild!=NULL)
next=next->lchild;
next->lchild=cur->lchild;
temp=cur->rchild;
}
if(prev==NULL)
{
printf("\nThe item deleted is : %d",cur->info);
free(cur);
return temp;
}
if(prev->lchild==cur)
prev->lchild=temp;
else
prev->rchild=temp;
return root;
}

void main()
{
TREE root=NULL;
int choice,item,flag,k=0;

while(k!=1)
{
clrscr();
printf("\n\n\n\t\t\t******MAIN MENU*******");
printf("\n\n\n\tENTER 1 --> TO INSERT INTO THE
BINARY SEARCH TREE");
printf("\n\tENTER 2 --> TO FIND THE MAXIMUM
ELEMENT IN THE BINARY SEARCH TREE");
printf("\n\tENTER 3 --> TO FIND THE MINIMUM
ELEMENT IN THE BINARY SEARCH TREE");
printf("\n\tENTER 4 --> TO SEARCH FOR AN ITEM
IN THE BINARY SEARCH TREE");
printf("\n\tENTER 5 --> TO DELETE A SPECIFIED
ITEM FROM BINARY SEARCH THE TREE");
printf("\n\tENTER 6 --> TO TRAVERSE THE
BINARY SEARCH TREE IN PREORDER");
printf("\n\tENTER 7 --> TO TRAVERSE THE
BINARY SEARCH TREE IN INORDER");
printf("\n\tENTER 8 --> TO TRAVERSE THE
BINARY SEARCH TREE IN POSTORDER");
printf("\n\tENTER 9 --> TO QUIT");
printf("\n\n\nEnter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nEnter the item to be inserted : ");
scanf("%d",&item);
root=insert_bst(item,root);
break;
case 2:
search_max(root);
break;
case 3:
search_min(root);
break;
case 4:
if(root==NULL)
printf("\nTree is empty");
else
{
printf("\nEnter item to be searched : ");
scanf("%d",&item);
flag=0;
search_bst(item,root,&flag);
if(flag==1)
printf("\nSearch successful");
else
printf("\nSearch Unsucessful");
}

break;
case 5:
printf("\nEnter the item to be deleted : ");
scanf("%d",&item);
delete_bst(item,root);
break;
case 6:
if(root==NULL)
printf("\nTree is empty");
else
{
printf("\nPreorder traversal is : \n");
preorder(root);
}
break;
case 7:
if(root==NULL)
printf("\nTree is empty");
else
{
printf("\nInorder traversal is : \n");
inorder(root);
}

break;
case 8:
if(root==NULL)
printf("\nTree is empty");
else
{
printf("\nPostorder traversal is : \n");
postorder(root);
}

break;
case 9:
k=1;
printf("\nTHANK YOU.. HAVE A NICE DAY
QUITTING FROM THE PROGRAM!!!");
break;
}
getch();
}
}

Function for iterative pre-order traversal.

In this function, we use datatype TREE, which is a pointer


to a struct tree, which consists of members *lchild, info,
and *rchild. We also use global variables int top=-1, and
TREE stack[20].
root is a pointer variable which points to the root of the
tree.
We call the push() function and pop() function, which
inserts elements into the stack and deletes out elements
respectively. The functional code required is given below.
void push(TREE data)
{
stack[++top ]=data;
}
TREE pop( )
{
return stack[top--];
}

void iterative_preorder(TREE root)


{
TREE cur;
if(root==NULL)
{
printf(“\nTree is empty..!!”);
return;
}
cur=root;
for(; ;)
{
while(cur!=NULL)
{
printf(“\n%d”,cur->info);
push(cur);
cur=cur->lchild;
}
if(top>-1)
{
cur=pop();
cur=cur->rchild;
}
else
return;
}
}
7. SORTING
7.1 Definition and techniques
Sorting is the technique of arranging the elements in
ascending or descending order.

Selection Sort:

Write a C program to sort the elements in the array


using selection Sort technique.

#include<stdio.h>
#include<conio.h>
void selection(int a[],int n)
{
int i,j,temp,sum,pass;
sum=0,pass=0;
for(i=0;i<n-1;i++)
{
pass++;
for(j=i+1;j<n;j++)
{
if(a[j]<a[i])
{
temp=a[j];
a[j]=a[i];
a[i]=temp;
sum++;
}
}
}
printf("\nTotal number of passses = %d",pass);
printf("\nTotal number of exchanges = %d",sum);
}

void main()
{
int a[100],n,i;
clrscr();
printf("\nEnter the number of elements in the array : ");
scanf("%d",&n);
printf("\nEnter %d elements of the array : \n",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
selection(a,n);
printf("\nArray in the sorted order is : \n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
getch();
}

Bubble Sort:

Write a C program to sort the elements in the array


using Bubble Sort technique.

#include<stdio.h>
#include<conio.h>
void bubble(int a[],int n)
{
int i,j,temp,sum,exch,pass,flag;
sum=0,exch=0,pass=0;
for(i=1;i<n;i++)
{
flag=0;
exch=0;
pass++;
for(j=0;j<n-i;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
exch++;
sum++;
flag=1;
}
}
printf("\nNumber of exchanges in pass %d =
%d",pass,exch);
if(flag==0)
break;
getch();
}
printf("\nTotal number of passses = %d",pass);
printf("\nTotal number of exchanges = %d",sum);
}

void main()
{
int a[100],n,i;
clrscr();
printf("\nEnter the number of elements in the array : ");
scanf("%d",&n);
printf("\nEnter %d elements of the array : \n",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
bubble(a,n);
printf("\nArray in the sorted order is : \n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
getch();
}

Merge Sort:

Write a C program to sort the elements in the array


using Merge Sort technique.

#include<stdio.h>
#include<conio.h>
void simple_merge(int a[],int low,int mid,int high)
{
int i,j,k,c[30];
k=i=low;
j=mid+1;
while((i<=mid) && (j<=high))
{
if(a[i]<a[j])
c[k++]=a[i++];
else
c[k++]=a[j++];
}
while(i<=mid)
c[k++]=a[i++];
while(j<=high)
c[k++]=a[j++];
for(i=low;i<=k-1;i++)
a[i]=c[i];
}

void mergesort(int a[],int low,int high)


{
int mid;
if(low<high)
{
mid=(low+high)/2;
mergesort(a,low,mid);
mergesort(a,mid+1,high);
simple_merge(a,low,mid,high);
}
}
void main()
{
int a[30],i,n;
clrscr();
printf("\nEnter the number of elements : ");
scanf("%d",&n);
printf("\nEnter %d elements ",n);
for(i=0;i<n;i++)
{
printf("\nEnter %d element : ",i+1);
scanf("%d",&a[i]);
}
printf("\nBefore Sorting : ");
for(i=0;i<n;i++)
printf("%d ",a[i]);
mergesort(a,0,n-1);
printf("\nAfter Sorting : ");
for(i=0;i<n;i++)
printf("%d ",a[i]);
getch();
}

Insertion Sort:

Write a C program to sort the elements in the array


using Insertion Sort technique.

#include <stdio.h>
#include<conio.h>
void ins_sort(int a[],int n)
{
int i,j,item;
for(i=0;i<n;i++)
{
item=a[i];
j=i-1;
while(j>=0&&item<a[j])
{
a[j+1]=a[j];
j--;
}
a[j+1]=item;
}
}

void main()
{
int i,n,arr[100];
clrscr();
printf("\nEnter the number of elements in the array : ");
scanf("%d",&n);
printf("\nEnter %d elements ",n);
for(i=0;i<n;i++)
{
printf("\nEnter %d element : ",i+1);
scanf("%d",&arr[i]);
}
printf("\nBefore Sorting : ");
for(i=0;i<n;i++)
printf("%d ",arr[i]);
ins_sort(arr,n);
printf("\nAfter Sorting : ");
for(i=0;i<n;i++)
printf("%d ",arr[i]);
getch();
}

Heap Sort:

Write a C program to sort the elements in the array


using Heap Sort technique.

#include<stdio.h>
#include<conio.h>
create(int a[],int n)
{
int i,k,item,j;
for(k=2;k<=n;k++)
{
item=a[k];
i=k;
j=i/2;
while(j!=0&&item>a[j])
{
a[i]=a[j];
i=j;
j=i/2;
}
a[i]=item;
}
}
void main()
{
int n,i,j,a[20],temp;
clrscr();
printf("Enter number of elements\n");
scanf("%d",&n);
printf("Enter array elements : \n");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
for(i=n;i>0;i--)
{
create(a,i);
temp=a[1];
a[1]=a[i];
a[i]=temp;
}
printf("sorted array:\n");
for(i=1;i<=n;i++)
printf("%d\t",a[i]);
getch();
}

Quick Sort:

Write a C program to sort the elements in the array


using Quick Sort technique.

#include<stdio.h>
#include<conio.h>
#define SIZE 10
/* sort everything inbetween `low' <-> `high' */
void quicksort(int arr[], int low, int high)
{
int i=low;
int j=high;
int y=0;
/* compare value */
int z=arr[(low+high)/2];
/* partition */
do
{
/* find element above ... */
while(arr[i]<z)
i++;
/* find element below ... */
while(arr[j]>z)
j--;
if(i<=j)
{
/* swap two elements */
y=arr[i];
arr[i]=arr[j];
arr[j]=y;
i++;
j--;
}
}while(i<=j);
/* recursive call */
if(low < j)
quicksort(arr, low, j);
if(i < high)
quicksort(arr, i, high);
}

void main()
{
int array[SIZE];
int i;
clrscr();
printf("\n\n\n\t******PROGRAM TO SORT THE
ELEMENT OF THE ARRAY USING QUICK
SORT*****");
printf("\n\n\nEnter %d elements into the array ",SIZE);
for(i=0;i<SIZE;i++)
{
printf("\nEnter %d element : ",i+1);
scanf("%d",&array[i]);
}
/* print the original array */
printf("Before quicksort: ");
for(i=0;i<SIZE;i++)
{
printf(" %d ",array[i]);
}
printf("\n");
quicksort(array,0,(SIZE - 1));
/* print the `quicksorted' array */
printf("After quicksort: ");
for(i=0;i<SIZE;i++)
{
printf(" %d ",array[i]);
}
printf("\n");
getch();
}

SHELL SORT

Write a C program to sort the elements in the array


using Shell Sort technique.

#include<stdio.h>
#include<conio.h>
void shell_sort(int n,int a[])
{
int i,j,depth,item;
for(depth=(n-1)/2;depth>0;depth/=2)
{
for(i=0;i<n;i+=depth)
{
item=a[i];
j=i-depth;
while(j>=0 &&item<a[j])
{
a[j+depth]=a[j];
j=j-depth;
}
a[j+depth]=item;
}
}
}
void main()
{
int i,n,arr[100];
clrscr();
printf("\nEnter the number of elements in the array : ");
scanf("%d",&n);
printf("\nEnter %d elements ",n);
for(i=0;i<n;i++)
{
printf("\nEnter %d element : ",i+1);
scanf("%d",&arr[i]);
}
printf("\nBefore Sorting : ");
for(i=0;i<n;i++)
printf("%d ",arr[i]);
shell_sort(n,arr);
printf("\nAfter Sorting : ");
for(i=0;i<n;i++)
printf("%d ",arr[i]);
getch();
}

Вам также может понравиться