c rec
c rec
DEPARTMENT :
REGISTER NO :
1
2
INDEX
3
Ex.No: 1 I/O STATEMENTS, EXPRESSIONS,DECISION MAKING AND IT
Date:
AIM:
To write a program for I/O statements, operators, expressions using C.
ALGORITHM:
STEP1:Start the program.
STEP2:Declare the variables
totamt,amount,subtot,distant,taxamt,quantity,value,discount,tax.
STEP3:Read the values for the variables.
STEP4:Perform addition, subtraction and multiplication.
STEP5:Stop the program.
PROGRAM:
#include<stdio.h>
#include<conio.h>
Void main()
{
float totamt,amount,subtot,distant,taxamt,quantity,value,discount,tax;
printf("\nenter the quantity of item sold:");
scanf("%f",&quantity);
printf("\n enter the value of item:");
scanf("%f",&value);
printf("\n enter the discount
percentage:"); scanf("%f",&discount);
printf("\n enter the tax:");
scanf("%f",&tax);
amount=quantity*value;
distant=(amount*discount)/100.0;
subtot=amount-distant;
taxamt=(subtot*tax)/100.0;
totamt=subtot+taxamt; printf("\n\n\
n******bill******"); printf("\n
quantity sold:%f",quantity); printf("\n
priceperitem:%f",value); printf("\n
amount %f",amount); printf("\n
discount:%f",distant); printf("\n
discounted total: %f",subtot); printf("\
n tax:+ %f",taxamt);
printf("\n total amount %f",totamt); getch();
}
4
OUTPUT:
Enter the quantity of item sold:10
Enter the value of item:50
Enter the discount percentage:10
Enter the tax:10
Quantity sold:10.00
Price per item:50.00
Amount:500.00
Discount:50.00
Discounted total:450.00
Tax:+45
Total amount:495.00
RESULT:
Thus the program for I/O statements, operators and expressions are
executed successfully.
5
Ex.No: 2 FUNCTIONS AND ARRAY
Date:
AIM:
Write a program in C using one dimensional array.
ALGORITHM:
PROGRAM:
#include<stdio.h>
#include<conio.h>
void main()
void fun(int a[5] ):/^ * function
declaration"/ int all (10,20,30,40,50):
clrscr();
fun(a):/"call to the function"/
getch()
void fun(int a[6])
int i;
for(i=0;i<5;1++)
printf("%d", "(a+1)); /or printf("%d",alil);"/ }
OUTPUT:
10, 20,30,40,50
RESULT:
Thus the program to arrange numbers in ascending order using one dimensional array is
executed successfully.
6
Ex.No: 3
Date: POINTERS AND STRUCTURES
AIM:
Write a program in C for pointers to structures.
ALGORITHM:
STEP1:Start the program
STEP2:Declare the variables and pointer variable.
STEP3:Read the value of variables.
STEP4:Using the structure do process.
STEP5:Print the output.
STEP6:Stop the program.
PROGRAM:
#include<stdio.h>
struct person{
int age;
float weight;
};
int main(){
struct person *personPtr,
person1; personPtr = &person1;
printf("Enter age: ");
scanf("%d", &personPtr->age);
printf("Enter weight: ");
scanf("%f", &personPtr->weight);
printf("Displaying:\n");
printf("Age: %d\n", personPtr->age);
printf("weight: %f", personPtr-
>weight); return 0;
}
RESULT:
Thus the program for pointers and structure is executed successfully.
7
Ex.No: 4
Date: FILES: READING AND WRITING, FILE POINTERS, FILE OPERATIONS, R
AIM:
Write a program in C for files reading and writing, file pointers, file operations,
random access, processor directives.
Reading a file
fgetc(file_pointer): It returns the next character from the file pointed to by the file
pointer. When the end of the file has been reached, the EOF is sent back.
fgets(buffer, n, file_pointer): It reads n-1 characters from the file and stores the string
in a buffer in which the NULL character ‘\0’ is appended as the last character.
PROGRAM:
#include <stdio.h>
int main()
{
FILE * file_pointer;
char buffer[30], c;
file_pointer = fopen("fprintf_test.txt",
"r"); printf("----read a line \n");
fgets(buffer, 50,
file_pointer); printf("%s\n",
buffer);
printf("----read and parse data- - -\n");
file_pointer = fopen("fprintf_test.txt", "r"); //reset the pointer
char str1[10], str2[2], str3[20], str4[2];
fscanf(file_pointer, "%s %s %s %s", str1, str2, str3, str4);
printf("Read String1 |%s|\n", str1);
printf("Read String2 |%s|\n", str2);
printf("Read String3 |%s|\n", str3);
printf("Read String4 |%s|\n", str4);
printf("----read the entire file- - -\n");
file_pointer = fopen("fprintf_test.txt", "r"); //reset the pointer
while ((c = getc(file_pointer)) != EOF) printf("%c", c);
fclose(file_pointer);
return 0;
}
8
Writing to file
The above program writes a single character into the fputc_test.txt file until it reaches the
next line symbol “\n” which indicates that the sentence was successfully written. The
process is to take each character of the array and write it into the file.
#include <stdio.h>
int main() {
int i;
FILE * fptr;
char fn[50];
char str[] = "Guru99 Rocks\n";
fptr = fopen("fputc_test.txt", "w"); // "w" defines "writing mode"
for (i = 0; str[i] != '\n'; i++) {
/* write to file using fputc() function */
fputc(str[i], fptr);
}
fclose(fptr);
return 0;
}
Random Access in File
fseek() function is used to take file pointer to a particular position data file.
Syntax: fseek(Fpointer, Position, Initial);
Fpointer is name of file pointer variable.
Initial specifies the position from where file pointer should be jumped. It can three
values :
0: From the beginning of file.
1: Current position.
2: End of file
#include<stdio.h>
int main()
{
FILE *f1;
char line[80] , s;
int n;
f1=fopen(“data.txt”,”r”);
fgets(line,80,f1);
printf(“%s”,line);
fseek(f1,2,0);
/*File pointer jumped to 3rd character from beginning*/
s=getc(f); /*5th Character read from file*/ printf(“\n
%c”,s);
fseek(f1,2,1);
/*File pointer jumped to 3rd character from current
position*/
9
s=getc(f); printf(“\n
%c”,s);
fseek(f1,0,2);
/*File pointer jumped end of file* /
s=getc(f);
printf(“\n%c”,s);
fclose(f);
return(0);
}
Preprocessor Directive
The #error preprocessor directive indicates error. The compiler gives fatal
error if #error directive is found and skips further compilation process.
#include<stdio.h>
#ifndef MATH_H
#error First include then compile
#else
void main(){
float a;
a=sqrt(7);
printf("%f",a);
}
#endif
RESULT:
Thus the program in C for files reading and writing, file pointers, file operations, random
access, processor directives is executed successfully.
1
Ex.No: 5
Date: DEVELOPMENT OF REALTIME C APPLICATION
Each of the above mentioned operations is provided to the program user in the form of
a "menu" with the options:
1- file creation
2- display the contents of the file
3- add information to the file
4- age average calculation
5- sort file contents
6- person removal
7- correctness information analysis
8- end program
Source Code
#include <stdio.h>
#include <stdlib.h>
char fileName[20];
int createFile(){
/* file is created in current working directory */
FILE * fptr = NULL;
int mode = 2;
printf("\n Enter name of file :
"); scanf(" %s", fileName);
fptr = fopen(fileName, "w");
if(fptr!=NULL)
fclose(fptr);
return 0;
1
}
void displayFileContents(){
FILE *fptr = fopen(fileName,
"r"); char c;
long int count = 0;
printf("\n---- File Content----------\n\n");
while ((c = getc(fptr)) != EOF)
{ putchar(c); count++;
}
if(count==0)
printf("\n Warning: File is empty!!");
else
fclose(fptr);
void addInfo(){
char name[50];
unsigned char age;
getchar();
printf("\n\n Enter Name :
"); gets(name);
char alreadyExist = 0;
while (fgets(line, sizeof(line), fptr)) {
if(strstr(line, name))
alreadyExist = 1;
}
fclose(fptr);
if(alreadyExist==1)
{
printf("\n Record already exist !!");
printf(" %s ", line);
}
else{
fptr = fopen(fileName, "a");
fputs(name, fptr);
char buffage[5];
char temp[5];
strcpy(temp, " | ");
strcat(temp, buffage);
strcat(temp, "\n");
fputs(temp, fptr);
void calcualteAvgAge(){
FILE* fptr = fopen(fileName, "r");
char line[500];
char *ptr = NULL;
float avg = 0;
char alreadyExist = 0;
int count =0;
while (fgets(line, sizeof(line), fptr)) {
ptr = strtok(line, "|");
ptr = strtok(NULL, "|");
avg += atoi(ptr); count+
+;
}
if(count>0){
avg = avg/count;
printf("\nAverage Age is : %.2f",avg) ;
}
else{
printf("\n No data to calcualte avg age.");
}
void sortFileContents(){
FILE* fptr = fopen(fileName, "r");
char line[500];
float tempArr[500];
char *ptr = NULL;
int i=0, count=0;
while (fgets(line, sizeof(line), fptr)) {
count++;
ptr = strtok(line, "|");
ptr = strtok(NULL, "|");
tempArr[i++] = atoi(ptr);
}
int order=0;
printf("\n\n Press 1 for Assending order ");
printf("\n Press 2 for Desending order : ");
scanf("%d",&order);
if(order==2){
if(tempArr[j] > tempArr[i])
{ temp=tempArr[j];
tempArr[j] =
tempArr[i]; tempArr[i]
= temp;
}
}
1
else{
1
if(tempArr[i] > tempArr[j])
{
temp=tempArr[j];
tempArr[j] = tempArr[i];
tempArr[i] = temp;
}
}
}
}
if(temp == tempArr[i]){
printf("\n %s", tempLine);
break;
}
}
}
if(nameptr==NULL){ printf("\
n\n Enter Name : ");
getchar(); gets(name);
}
else
strcpy(name, nameptr);
if(fptr==NULL){
printf("\n Error: No record
exist"); return;
}
char temp[]="temp";
//file mode should be same as bas file
FILE* fptrTmp = fopen(temp, "w");
if(fptrTmp==NULL){
printf("\n Error: Unable to perform this operation");
return;
}
1
char line[500];
int count =0;
while (fgets(line, sizeof(line), fptr)) {
if(strstr(line, name)){
//don't copy it
count++;
fclose(fptrTmp);
fclose(fptr);
if(count>0){
printf("fileName : %s removed ", fileName);
if(remove(fileName) == 0)
printf("\n File %s is deleted successfully", fileName);
else
printf("\n Error while deleting file %s ", fileName);
getchar(); getchar();
rename(temp, fileName);
printf("\n Success ! Reocrd found & deleted");
}
else{
printf("\n Error: Record not found");
}
remove(temp);
}
void correctInfo(){
/* create a temporary file */
FILE* fptr = fopen(fileName, "r");
if(fptr==NULL){
printf("\n Error: No record
exist"); return;
}
char temp[]="temp1";
char line[500];
//file mode should be same as bas file
FILE* fptrTmp = fopen(temp, "w");
while (fgets(line, sizeof(line), fptr)) {
fputs(line, fptrTmp);
//printf("\n putting : %s in new file", line);
memset(line, NULL, sizeof(line));
}
fclose(fptrTmp);
fclose(fptr);
1
fptrTmp = fopen(temp, "r");
float tempArr[500];
char *ptr = NULL;
char name[50];
memset(name, NULL, sizeof(name));
if(choice=='y'){
ptr = strtok(line, "|");
strcpy(name, ptr);
removePerson(name);
printf("\n\n Please enter new values ");
addInfo();
break;
}
}
close(fptr);
}
void menu(){
char choice = -1;
while(choice!=8){
printf("\n\n\n #### Main Menu ####\n\n");
printf("\n 1. File creation");
printf("\n 2. Display the contents of the file");
printf("\n 3. Add Info to file");
printf("\n 4. Age average calcualtion");
printf("\n 5. Sort file contents");
printf("\n 6. Person removal");
printf("\n 7. Correctness information analysis");
printf("\n 8. End program");
switch(choice){
case 1:
if(createFile() == 0)
printf("\n Success : File created
successfully!");
else
printf("\n Error: Can't create file'");
break;
case 2:
displayFileContents();
break;
1
case 3:
addInfo();
break;
case
4: calcualteAvgAge();
break;
case sortFileContents();
5:
break; removePerson(NULL);
case
6:
correctInfo();
break;
case
7:
break;
case 8: printf("\n thanks for using the
application \n ");
default: printf("\n Error: Invalid Choice! Enter
again");
getchar();
}
}
1
RESULT:
Thus the program is executed
and the output is verified.
1
Ex.No:6
Date: LIST USING ARRAY
AIM:
To perform various operations on List ADT using array implementation.
ALGORITHM:
1. Start
2. Create a list of n elements
3. Display list operations as a menu
4. Accept user choice
5. If choice = 1 then
Get position of element to be
deleted Move elements one position
upwards thereon.Decrement length
of the list
Else if choice = 2
Get position of element to be
inserted.Increment length of the list
Move elements one position downwards thereon
Store the new element in corresponding position
Else if choice = 3
Traverse the list and inspect each element
Report position if it exists.
6. Stop
PROGRAM
#include
<stdio.h>
#include
<conio.h>
void
create();
void insert();
void
search();
void
deletion();
void
display(); int
i, e, n, pos;
static int
1
b[50];
main()
{
int ch;
char g =
'y';
create();
do
1
{
printf("\n List Operations");
printf("\n 1.Deletion\n 2.Insert\n 3.Search\n4.Exit\n");
printf("Enter your
choice: "); scanf("%d",
&ch); switch(ch)
{
case 1:
deletion();
break;
case 2:
insert(); break;
case 3:
search();
break;
case 4:
exit(0);d efault:
printf("\n Enter the correct choice:");
}
printf("Do you want to continue:
"); fflush(stdin);
scanf("\n %c",&g);
} while(g=='y' || g=='Y');g etch();
}
void create()
{
printf("\n Enter the number of
elements:"); scanf("%d",&n);
printf("\n Enter list elements:
");for(i=0; i<n; i++)
scanf("%d", &b[i]);
}
void deletion()
{
printf("\n enter the position you want to delete: ");s
canf("%d", &pos);
if(pos >= n)
printf("\n Invalid location"); else
{
for(i=pos+1; i<n; i++)b[i-1]
= b[i];
n--;
printf("List elements after deletion"); display();
}
}
1
void search()
{
int flag = 0;
printf("\n Enter the element to be searched:
");scanf("%d", &e);
for(i=0; i<n; i++)
{
if(b[i] == e)
{
flag = 1;
printf("Element is in the %d position", i);b reak;
}
}
if(flag == 0)
printf("Value %d is not in the list", e);
}
void insert()
{
printf("\n Enter the position you need to insert: ");s
canf("%d", &pos);
if(pos >= n)
printf("\n Invalid location"); else
{
++n;
for(i=n; i>pos;
i--) b[i] = b[i-
1];
printf("\n Enter the element to insert: ");s
canf("%d", &e);
b[pos] = e;
}
printf("\n List after insertion:"); display();
}
void display()
{
for(i=0; i<n; i++) printf("\n
%d", b[i]);
}
OUTPUT
2
Enter the number of elements:5 Enter
list elements: 12 23 34 45 56
2
List Operations
1.Deletion 2.Insert
3.Search
4.Exit
Enter your choice:2
Enter the position you need to insert: 1 Enter the
element to insert: 99
List after insertion:
12
99
23
34
45
56
Do you want to continue: y
List Operations
1.Deletion 2.Insert
3.Search
4. Exit
Enter your choice:1
Enter the position you want to delete: 3
Elements after
deletion1 2 99
23
45
56
Do you want to continue: n
RESULT:
Thus various operations was successfully executed on list using array implementation.
2
Ex.No:7a Date:
STACK ARRAY
AIM:
To implement stack operations using array.
ALGORITHM:
1. Start
2. Define a array stack of size max= 5
3. Initialize top = -1
4. Display a menu listing stack operations
5. Accept choice
6. If choice = 1 then
If top < max -1
Increment top
Store element at current position of top
Else
Print Stack overflow
Else If choice = 2 then
If top < 0 then
Print Stack underflow
Else
Display current top
elementDecrement top
Else If choice = 3 then
Display stack elements starting from top
7. Stop
PROGRAM:
#include <stdio.h>
#include
<conio.h>#define static
int stack[max];
void push(int
x)
stack[++top] = x;
}
2
int pop()
{
return (stack[top--]);
}
2
void view()
{
int i;
if (top < 0)
printf("\n Stack Empty \n");else
{
printf("\n Top-->");
for(i=top; i>=0; i--)
{
printf("%4d", stack[i]);
}
printf("\n");
}
}
main()
{
int ch=0,
val; clrscr();
while(ch !=
4)
{
printf("\n STACK OPERATION \n");
printf("1.PUSH ");
printf("2.POP ");
printf("3.VIEW ");
printf("4.QUIT \n");
printf("Enter Choice : ");
scanf("%d", &ch);
switch(ch)
{
case 1:
if(top < max-1)
{
printf("\nEnter Stack element : ");
scanf("%d", &val);
push(val);
}
else
printf("\n Stack Overflow \
n");break; case 2:
if(top < 0)
printf("\n Stack Underflow \n");e lse
{
val = pop();
printf("\n Popped element is %d\n", val);
}
break;
2
case 3:
view();b reak;
2
case 4:
exit(0);d efault:
printf("\n Invalid Choice \n");
}
}
}
OUTPUT:
STACK OPERATION
1.PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice : 1
STACK OPERATION
1.PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice : 1
STACK OPERATION
1.PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice : 1
STACK OPERATION
1.PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice : 1
STACK OPERATION
1.PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice : 3
Top--> 45 34 23 12
STACK OPERATION
1.PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice : 2
Popped element is
45
RESULT:
2
Thus push and pop operations of a stack was demonstrated using arrays
2
Ex.No:7b Date: Queue Array
AIM:
To implement queue operations using array.
ALGORITHM:
1. Start
2. Define a array queue of size max = 5
3. Initialize front = rear = –1
4. Display a menu listing queue operations
5. Accept choice
6. If choice = 1 then If rear < max -
1 Increment rear
Store element at current position of
rear Else
Print Queue Full
Else If choice = 2 then If front = –1 then
Print Queue empty
Else
Increment front
PROGRAM:
include <stdio.h>
#include <conio.h>
#define max 5
static int
queue[max]; int
front = -1;
2
int rear = -1;
2
void insert(int x)
{
queue[++rear] =
x;i f (front == -1)
front = 0;
}
int remove()
{
int val;
val = queue[front];
if (front==rear && rear==max-1)f
ront = rear = -1;
else
front ++;
return (val);
}void view()
{
int i;
if (front == -1)
printf("\n Queue Empty \n");e lse
{
printf("\n Front-->");
for(i=front; i<=rear; i++)
printf("%4d", queue[i]);
printf(" <--Rear\n");
}
}main()
{
int ch=
0,val;
clrscr();
while(ch !=
4)
{
printf("\n QUEUE OPERATION \
n"); printf("1.INSERT ");
printf("2.DELETE ");
printf("3.VIEW ");
printf("4.QUIT\n");
printf("Enter Choice : ");s
canf("%d", &ch); switch(ch)
{
case 1:
if(rear < max-1)
{
2
printf("\n Enter element to be inserted : ");s
canf("%d", &val);
insert(val);
}
2
else
printf("\n Queue Full \n");
break; case 2:
if(front == -1)
printf("\n Queue Empty \n");e lse
{
val = remove();
printf("\n Element deleted : %d \n", val);
}
break;
case 3:
view();b
reak; case 4:
exit(0);d efault:
printf("\n Invalid Choice \n");
}
}
}
OUTPUT:
QUEUE OPERATION
1.INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice : 1
OPERATION
1.INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice : 1
OPERATION
1.INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice : 1
OPERATION
1.INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice : 1
Enter element to be
inserted : 45Q OPERATION
2
UEUE
1.INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice : 1
2
Enter element to be UEUE
inserted : 56Q
OPERATION
1.INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice : 1
Queue Full
QUEUE OPERATION
2. INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice : 3
Front--> 12 23 34 45 56 <--Rear
RESULT:
Thus insert and delete operations of a queue was demonstrated using arrays
2
Ex. No. 8a Singly Linked List
Date:
AIM:
To define a singly linked list node and perform operations such as insertions
and
deletions dynamically.
ALGORITHM:
1. Start
2. Define single linked list nodes self referential structure
3. Create head node with label = -1 and next = NULL using
4. Display menu on list operation
5. Accept user choice
6. If choice = 1 then
Locate node after which insertion is to
be doneCreate a new node and get data
part
Insert new node at appropriate position by manipulating address
Else if choice = 2
Get node's data to be deleted.
Locate the node and delink the
nodeRearrange the links
Else
Traverse the list from Head node to node which points to null
7. Stop
PROGRAM:
#include <stdio.h>
#include <conio.h>
#include <process.h>
#include <alloc.h>
#include <string.h>
struct node
{
int label;
struct node *next;
};
main()
{
int ch, fou=0;i
nt k;
struct node *h, *temp, *head, *h1;
2
head = (struct node*) malloc(sizeof(struct node));h ead->label
= -1;
2
head->next = NULL;
while(-1)
{
clrscr();
printf("\n\n SINGLY LINKED LIST OPERATIONS \
n"); printf("1->Add "); printf("2-
>Delete "); printf("3-
>View "); printf("4-
>Exit \n"); printf("Enter
your choice : ");
scanf("%d", &ch);
switch(ch)
{
/* Add a node at any intermediate location */c ase 1:
printf("\n Enter label after which to add : ");scanf("%d", &k);
h = head;
fou = 0;
if (h->label ==
k)fou = 1;
while(h->next != NULL)
{
if (h->label == k)
{
fou=1;
break;
}
h = h->next;
}
if (h->label ==
k)fou = 1;
if (fou != 1)
printf("Node not found\n"); else
{
temp=(struct node *)(malloc(sizeof(struct node)));
printf("Enter label for new node : "); scanf("%d",
&temp->label);
temp->next = h->next;h -
>next = temp;
}
break
3
;
3
&k);
fou =
0;
h = h1 = head;
while (h->next != NULL)
{
h = h->next;
if (h->label == k)
{
fou = 1;
break;
}
}
if (fou == 0)
printf("Sorry Node not found\n"); else
{
while (h1->next !=
h)h 1 = h1-
>next;
h1->next = h->next;
free(h);
printf("Node deleted successfully \n");
}
break
;
case 3:
printf("\n\n HEAD -
> "); h=head;
while (h->next != NULL)
{
h = h->next;
printf("%d -> ",h->label);
}
printf("NULL"); break;
case 4:
exit(0);
}
}
}
OUTPUT:
3
1->Add 2->Delete 3->View nter
4->ExitE your choice : 1
Enter label after which new node is to be added :
23Enter label for new node : 67
RESULT:
Thus operation on single linked list is performed.
3
Ex. No. 8b Stack Using Linked List
Date:
AIM:
To implement stack operations using linked list.
ALGORITHM:
1. Start
2. Define a singly linked list node for stack
3. Create Head node
4. Display a menu listing stack operations
5. Accept choice
6. If choice = 1 then
Create a new node with data
Make new node point to
first node
Make head node point to
new nodeElse If choice = 2 then
Make temp node point to first node
Make head node point to next of
temp nodeRelease memory
Else If choice = 3 then
Display stack elements starting from head node till null
7. Stop
PROGRAM:
#include <stdio.h>
#include <conio.h>
#include
<process.h>
#include <alloc.h>
struct node
{
int label;
struct node *next;
};
main()
{
int ch =
0;int k;
struct node *h, *temp, *head;
3
while(1)
{
3
printf("\n Stack using Linked List \n");p rintf("1-
>Push ");
printf("2->Pop
"); printf("3-
>View ");
printf("4->Exit \
n");
printf("Enter your choice : ");
scanf("%d", &ch);
switch(ch)
{
case 1:
/* Create a new node */
temp=(struct node *)(malloc(sizeof(struct node)));
printf("Enter label for new node : "); scanf("%d",
&temp->label);
h = head;
temp->next = h->next;h -
>next = temp; break;
case 2:
/* Delink the first node */h = head-
>next;
head->next = h->next;
case 3:
printf("\n HEAD -> "); h
= head;
/* Loop till last hile(h-
node */w
>next != NULL)
{
h = h->next;
printf("%d -> ",h->label);
}
printf("NULL \n"); break;
case 4:
exit(0);
}
}
}
3
OUTPUT:
3
Enter your choice : 1
Enter label for new node ew
: 23N node added
RESULT:
Thus push and pop operations of a stack was demonstrated using linked list.
3
Ex. No. 8c Queue Using Linked
List Date:
AIM:
To implement queue operations using linked list.
ALGORITHM:
1. Start
2. Define a singly linked list node for stack
3. Create Head node
4. Display a menu listing stack operations
5. Accept choice
6. If choice = 1 then
Create a new node with data
Make new node point to
first node
Make head node point to
new nodeElse If choice = 2 then
Make temp node point to first node
Make head node point to next of
temp nodeRelease memory
Else If choice = 3 then
Display stack elements starting from head node till null
7. Stop
PROGRAM:
#include <stdio.h>
#include <conio.h>
#include
<process.h>
#include <alloc.h>
struct node
{
int label;
struct node *next;
};
main()
{
int ch=0;
int k;
struct node *h, *temp, *head;
3
ead->next = NULL;
3
while(1)
{
printf("\n Queue using Linked List \n"); printf("1-
>Insert ");
printf("2->Delete ");
printf("3->View ");
printf("4-
>Exit \n");
printf("Enter your choice : ");
scanf("%d", &ch);
switch(ch)
{
case 1:
/* Create a new node */
temp=(struct node *)(malloc(sizeof(struct node)));
printf("Enter label for new node : "); scanf("%d",
&temp->label);
case 2:
/* Delink the first node */h = head-
>next;
head->next = h->next;
printf("Node deleted \n");
free(h); break;
case 3:
printf("\n\nHEAD -> ");
h=head; while (h->next!
=NULL)
{
h = h->next;
printf("%d -> ",h->label);
}
printf("NULL \n"); break;
case 4:
exit(0);
3
}
}
}
3
OUTPUT:
RESULT:
Thus insert and delete operations of a queue was demonstrated using linked list.
3
Ex. No. 9a Infix To Postfix Conversion
Date:
AIM:
To convert infix expression to its postfix form using stack operations.
ALGORITHM:
1. Start
2. Define a array stack of size max= 20
3. Initialize top = -1
4. Read the infix expression character-by-
character If character is an operand
print it
If character is an operator
Compare the operator’s priority with the stack[top] operator.
If the stack [top] has higher/equal priority than the input operator,
Pop it from the stack and print it.
Else
Push the input operator onto the stack
If character is a left parenthesis, then push it onto the stack.
If character is a right parenthesis, pop all operators from stack and
print it until a left parenthesis is encountered. Do not print the
parenthesis.
If character = $ then Pop out all operators, Print them and Stop
3
PROGRAM:
<stdio.h>
#include <conio.h># include
<string.h> #define MAX 20
}
}
4
break;d efault:
return 0;
}
}
while(stack[top] != '#')
{
4
postfix[j] = pop();
4
j++;
}
postfix[j] = '\0';
}
main()
{
char infix[20],postfix[20]; clrscr();
printf("Enter the valid infix string: ");gets(infix);
convertip(infix, postfix);
printf("The corresponding postfix string is: ");p
uts(postfix); getch();
}
char pop()
{
char a;
a = stack[top];t op--
;
return a;
}
OUTPUT
RESULT:
4
Thus the given infix expression was converted into postfix form using stack.
4
Ex. No. 9b Postfix Expression Evaluation
Date:
AIM:
To evaluate the given postfix expression using stack operations.
ALGORITHM:
1. Start
2. Define a array stack of size max=20
3. Initialize top=-1
4. Read the postfix expression character-by-
character If character is an operand push it
onto the stackIf character is an operator
Pop topmost two elements from stack.
Apply operator on the elements and push the result onto the stack,
5. Eventually only result will be in the stack at end of the expression.
6. Pop the result and print it.
7. Stop
4
PROGRAM:
<stdio.h>
#include <conio.h>
struct stack
{
int top; float
a[50];
}s;
main()
{
char pf[50]; float
d1,d2,d3; int i;
clrscr();
s.top = -1;
printf("\n\n Enter the postfix expression:
");gets(pf); for(i=0; pf[i]!='\0'; i++)
{
switch(pf[i])
{
case
'0':
case
'1':
case
'2':
case
'3':
case
'4':
case
'5':
case
'6':
case
'7':
case
'8':
case
'9':
s.a[++s.top] = pf[i]-'0';break;
case '+':
4
d1 = s.a[s.top--];
d2 = s.a[s.top--];
s.a[++s.top] = d1 +
d2; break;
case '-':
d2 = s.a[s.top--];
d1 = s.a[s.top--]; s.a[+
+s.top] = d1 - d2;break;
4
case '*':
d2 = s.a[s.top--];
d1 = s.a[s.top--];
s.a[++s.top] =
d1*d2; break;
case '/':
d2 = s.a[s.top--];
d1 = s.a[s.top--]; s.a[+
+s.top] = d1 / d2; break;
}
}
printf("\n Expression value is %5.2f", s.a[s.top]);g etch();
}
OUTPUT:
4
RESULT:
Thus the given postfix expression was evaluated using stack.
4
Ex. No. 1 0 Binary Tree
Date:
AIM:
To implement program for the given binary tree.
ALGORITHM:
1. Start the program
2. Create a tree
3. Perform the Insertion, Deletion and Search operation
4. Stop the program
PROGRAM:
#include<stdio.
h>
#include<stdlib.
h> struct node
{int value;
struct node *left_child, *right_child;
};
struct node *new_node(int value)
{struct node *tmp = (struct node
*)malloc(sizeof(struct node)); tmp->value = value;
tmp->left_child = tmp->right_child =
NULL; return tmp;
}
void print(struct node *root_node) // displaying the nodes!
{if (root_node != NULL)
{
print(root_node->left_child);
printf("%d \n", root_node-
>value); print(root_node-
>right_child);
}
}
struct node* insert_node(struct node* node, int value) // inserting nodes!
{
if (node == NULL) return
new_node(value); if (value < node-
>value)
{
4
node->left_child = insert_node(node->left_child, value);
}
else if (value > node->value)
{
node->right_child = insert_node(node->right_child, value);
}
return node;
}
int main()
{
printf("TechVidvan Tutorial: Implementation of a Binary Tree in
C!\n\n"); struct node *root_node = NULL;
root_node = insert_node(root_node,
10); insert_node(root_node, 10);
insert_node(root_node, 30);
insert_node(root_node, 25);
insert_node(root_node, 36);
insert_node(root_node, 56);
insert_node(root_node, 78);
print(root_node);
return 0;
}
OUTPUT:
Implementation of a Binary Tree
in C! 10
25
30
36
56
78
RESULT:
Thus the program for binary tree has been successfully and output is verified
4
Ex. No. 11 Binary Search Tree
Date:
AIM
To insert and delete nodes in a binary search tree.
ALGORITHM:
1. Create a structure with key and 2 pointer variable left and right.
2. Read the node to be inserted.
If (root==NULL)
root=node
else if (root->key<node-
>key)root-
>right=NULL
else
Root->left=node
3. For
Deletion
4. Stop
PROGRAM:
#include <stdio.h>
# include <stdlib.h>
struct node
{
int key;
struct node *left;s
truct node *right;
}
;
struct node *newNode(int item)
{
struct node *temp = (struct node
*)malloc(sizeof(structnode)); temp->key = item;
temp->left = temp->right = NULL;r
eturn temp;
}
void inorder(struct node *root)
{
if (root != NULL)
{
inorder(root->left);
printf("%d ", root->key);
4
inorder(root->right);
}
}
4
Program
#include <stdio.h>
# include <stdlib.h>
struct node
{
int key;
struct node *left;s
truct node *right;
}
;
struct node *newNode(int item)
{
struct node *temp = (struct node
*)malloc(sizeof(structnode)); temp->key = item;
temp->left = temp->right = NULL;r
eturn temp;
}
void inorder(struct node *root)
{
if (root != NULL)
{
inorder(root->left);
printf("%d ", root->key);
inorder(root->right);
}
}
5
struct node* deleteNode(struct node* root, int key)
{
struct node
*temp;if (root ==
NULL)
return root;
if (key < root-
>key)
root->left = deleteNode(root->left, key); else if (key
> root->key)
root->right = deleteNode(root->right, key);
else
{
if (root->left == NULL)
{
temp = root-
>right;
free(root);
return temp;
}
else if (root->right == NULL)
{
temp = root-
>left; free(root);
return temp;
}
temp = minValueNode(root->right); root-
>key = temp->key;
root->right = deleteNode(root->right, temp->key);
}
return root;
}
main()
{
struct node *root = NULL;r oot
= insert(root, 50);root
= insert(root, 30);r
oot = insert(root,
20);r oot =
insert(root, 40);r oot
= insert(root, 70);r
oot = insert(root, 60);r
oot = insert(root, 80);
printf("Inorder traversal of the given tree \n");i norder(root);
printf("\nDelete 20\n"); root =
5
deleteNode(root, 20);
printf("Inorder traversal of the modified tree \n");i
norder(root); printf("\nDelete 30\n"); root =
deleteNode(root, 30);
printf("Inorder traversal of the modified tree \n");i
norder(root); printf("\nDelete 50\n");
5
root = deleteNode(root, 50);
printf("Inorder traversal of the modified tree \n");i norder(root);
}
OUTPUT:
RESULT:
5
Thus nodes were inserted and deleted from a binary search tree.
5
Ex. No. 12a Linear Search
Date:
AIM:
To perform linear search of an element on the given array.
ALGORITHM:
1. Start
2. Read number of array elements n
3. Read array elements Ai,I=0,1,2,-n-1
4. Read searchvalue
5. Assign 0 to found
6. Check each array element against search
If Ai = search then
found = 1
5
PROGRAM:
# include
<stdio.h>
#include
<conio.h>
main()
{
int a[50],i, n, val, found; clrscr();
Output
RESULT:
Enter number of
elements : 7E Array
Elements :
23 6 12 5 0 32 10
Enter element to locate :
5 Element found at
position 3
5
nter
Thus an array was linearly searched for an element's existence.
5
Ex. No. 12b Binary Search
Date:
AIM:
To locate an element in a sorted array using Binary search method
ALGORITHM:
1. Start
2. Read number of array elements, say n
3. Create an array arrconsisting n sorted elements
4. Get element, say key to be located
5. Assign 0 to lower and n to upper
6. While (lower<upper)
Determine middle element mid =
(upper+lower)/2If key = arr[mid] then
Print mid
Stop
Else if key > arr[mid]
thenlower = mid
+1
else
upper = mid – 1
5
PROGRAM:
<stdio.h>
#include <conio.h>
main()
{
int a[50],i, n, upper, lower, mid, val, found;c lrscr();
if (found == -1)
printf("Element not
found");
getch();
5
}
5
OUTPUT:
RESULT:
5
Thus an element is located quickly using binary search method.
5
Ex. No. 13a Quick Sort
Date:
AIM:
To sort an array of N numbers using Quick sort.
ALGORITHM:
1. Start
2. Read number of array elements n
3. Read array elements A
4. Select an pivot element X from Ai
5. Divide the array into 3 sequences: elements < x, x, elements > x
6. Recursively quick sort both sets (Ai<x and Ai>x)
7. Stop
5
PROGRAM:
/* Quick Sort */
OUTPUT:
RESULT:
6
Thus an array was sorted using quick sort's divide and conquer method.
6
Ex. No. 13b Merge
SortDate:
AIM:
To sort an array of N numbers using Merge sort.
ALGORITHM:
1. Start
2. Read number of array elements n
3. Read array elements Ai
4. Divide the array into sub-arrays with a set of elements
5. Recursively sort the sub-arrays
6. Merge the sorted sub-arrays onto a single sorted array.
7. Stop
6
PROGRAM:
#include <stdio.h>
#include <conio.h>
main()
{
int i, arr[30];
printf("Enter total no. of elements : ");s
canf("%d", &size);
printf("Enter array elements :
");for(i=0; i<size; i++)
scanf("%d", &arr[i]);
part(arr, 0, size-1);
printf("\n Merge sorted list : ");f
or(i=0; i<size; i++)
printf("%d ",arr[i]); getch();
}
OUTPUT:
6
RESULT:
Thus array elements was sorted using merge sort's divide and conquer method.
6
Ex. No. 13c Insertion Sort
Date:
AIM:
To sort an array of N numbers using Insertion sort.
ALGORITHM:
1. Start
2. Read number of array elements n
3. Read array elements Ai
4. Sort the elements using insertion sort
In pass p, move the element in position p left until its correct place is
found among the first p + 1 elements.
Element at position p is saved in temp, and all larger elements
(prior toposition p) are moved one spot to the right. Then temp is
placed in thecorrect spot.
5. Stop
PROGRAM:
/* Insertion
Sort */m ain()
{
int i, j, k, n, temp, a[20], p=0;
p++;
printf("\n After Pass %d: ", p);f
6
or(k=0; k<n; k++)
printf(" %d", a[k]);
}
printf("\n Sorted List : "); for(i=0; i<n; i++)
printf(" %d", a[i]);
}
OUTPUT:
RESULT:
Thus array elements was sorted using insertion sort.
6
Ex. No. 14 Open Addressing Hashing Technique
Date:
AIM:
To implement hash table using a C program.
ALGORITHM:
1. Create a structure, data (hash table item) with key and value as data.
2. Now create an array of structure, data of some certain size (10, in this case).
But, the size of array must be immediately updated to a prime number just
greater than initial array capacity (i.e 10, in this case).
3. A menu is displayed on the screen.
4. User must choose one option from four choices given in the menu
5. Perform all the operations
6. Stop
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
#define MAX ain()
10m
{
int a[MAX], num, key, i;
char ans;
int create(int);
void linearprobing(int[], int, int);
v oid display(int[]);
printf("\nCollision handling by linear probing\n\n"); for(i=0; i<MAX; i++)
a[i] = -1;
do
{
printf("\n Enter number:");
scanf("%d", &num);
key = create(num);
linearprobing(a, key, num);
printf("\nwish to continue?(y/n):"); ans =
getch();
6
} while( ans == 'y');
display(a);
}
{
int flag, i, count =
0;v oid display(int
a[]);flag = 0;
if(a[key] == -1)
a[key] = num;
else
{
i=0;
while(i < MAX)
{
if(a[i] != -
1) count+
+; i++;
}
if(count == MAX)
{
printf("hash table is full");
display(a); getch();
exit(1);
}
for(i=key+1; i<MAX; i++)
if(a[i] == - 1)
{
a[i] = num;
flag = 1;
break;
}
for(i=0; i<key && flag==0; i++ )i f(a[i] ==
-1)
{
a[i] = num;
flag = 1;
break;
6
}
}
wish to continue?(y/n):
Enter number:26
wish to continue?(y/n):
Enter number:62
wish to continue?(y/n):
Enter number:93
wish to continue?(y/n):
Enter number:84 wish to continue?(y/n):
Enter number:15
wish to continue?
(y/n):
Enter number:76
wish to continue?
(y/n):
Enter number:98
wish to continue?
(y/n):
Enter number:26
wish to continue?
(y/n):
Enter number:199
wish to continue?
(y/n):
Enter number:1234
wish to continue?(y/n):
Enter number:5678
hash table is
full Hash
table is:
0 1234
1 1
2 62
6
3 93
4 84
5 15
6 26
7 76
8 98
9 199
RESULT:
Thus hashing has been performed successfully.