Professional Documents
Culture Documents
OBJECTIVES:
1. To understand and implement basic data structures using C
2. Understand the principles of linear and nonlinear data structures.
3. To understand and implement basic data structures using C
4. Build an applications using sorting
5. Build an application using searching.
LIST OF EXERCISES:
TOTAL:60 PERIODS
OUTCOMES: Upon completion of the course, the students will be able to:
Write basic and advanced programs in C
Implement functions and recursive functions in C
Implement data structures using C
Choose appropriate sorting algorithm for an application and implement it in a modularized way
Implement C programs to illustrate linear data structures
Develop C programs to implement nonlinear data structures. 2
INDEX
SIGNATURE
PAGE
Sl.No. DATE NAME OF THE EXPERIMENT MARKS OF THE
No.
FACULTY
Basic C Programs – looping, data
1.
manipulations, arrays
Programs using strings – string function
2. implementation
3
Ex.No :1(a) Basic C Program – Looping, array - Finding the sum of elements in an
Date: array
Aim:
To write a c program to illustrate the usage of loop to find the sum of elements in an
array.
Algorithm:
Step 1 : Start
Step 2 : Take an array ‘a’ and define its values
Step 3 : Loop for each value of an array ‘a’
Step 4 : Add each element to 'sum' variable
Step 5: After the loop finishes, display 'sum'
Step 6 : Stop
Program:
#include<stdio.h>
#include <conio.h>
void main()
{
int array[10]={1,2,3,4,5,6,7,8,9,0};
int sum, loop;
sum =0;
for(loop =9; loop >=0; loop--)
{
sum = sum + array[loop];
}
printf("Sum of array is %d.", sum);
getch();
}
Output:
Sum of array is 45.
Result:
Thus the c program to illustrate the usage of loop to find the sum of elements in an array has
been executed successfully.
4
Ex.No :1(b)
Basic C Program – Array implementation
Date:
Aim:
To write a C program to illustrate the usage of an array to pass an array containing age of
person to a function and to find average age and display the average age in main function.
Algorithm:
Step 1 : Start
Step 2 : Take an array ‘age’ and define its values
Step 3 : Call function average() by passing an array ‘age’ as an argument
Step 4 : Loop for each value of an array ‘age’ to find the sum of it inside average()
Step 5: After the loop finishes, calculate ‘avg’
Step 6 : Return ‘avg’ and print it in main function
Step 7: Stop
Program:
#include<stdio.h>
#include<conio.h>
float average(float age[]);
void main()
{
Float avg,age[]={23.4,55,22.6,3,40.5,18};
avg= average(age);/* Only name of array is passed as argument. */
printf("Average age=%.2f",avg);
getch();
}
float average(float age[])
{
Int i;float avg, sum =0.0;
for(i=0;i<6;++i)
sum += age[i];
avg=(sum /6);
return avg;
}
Output:
Average age=27.08
Result:
Thus the C program to illustrate the usage of an array to pass an array containing
age of person to a function and to find average age and display the average age in main function
has been executed successfully.
5
Ex.No :1(c)
Basic C Program - Data manipulations
Date:
Aim:
To write a C program to illustrate data manipulation using file handling
Algorithm:
Step 1: Start
Step 2: Open file “input.txt” in read mode.
Step 3: Read the contents of file
Step 4: Reverse the contents of the file and print it on the standard output.
Step 5: Stop
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
int i,pos;
fp=fopen("input.txt","r");
if(fp==NULL)
{
printf("File does not exist..");
}
fseek(fp,0,SEEK_END);
pos=ftell(fp);
//printf("Current postion is %d\n",pos);
i=0;
while(i<pos) {
i++;
fseek(fp,-i,SEEK_END);
//printf("%c",fgetc(fp));
ch=fgetc(fp);
printf("%c",ch); }
getch();}
Input.txt
hai
Output:
iah
Result:
Thus the C Program to illustrate data manipulation using file handling has been
successfully executed.
6
Ex.No : 2(a)
Program using strings
Date:
Aim:
To write a C program to read a string and check if it's a palindrome, without using library
functions.
Algorithm:
Step 1: Start
Step 2 : Take a string as input and store it in the array string[].
Step 3 : Store the same string into the another array reverse_string[] in the reverse
fashion.
Step 4 : Using for loop compare the elements of both the arrays.
Step 5 : If all the elements of the array are same, then it is a palindrome. Otherwise it is
not a palindrome.
Step 6: Stop
Program:
#include <stdio.h>
#include <string.h>
void main()
{
char string[25], reverse_string[25] = {'\0'};
int i, length = 0, flag = 0;
fflush(stdin);
printf("Enter a string \n");
gets(string);
/* keepgoing through each character of the string till its end */
for (i = 0; string[i] != '\0'; i++)
{
length++;
}
for (i = length - 1; i>= 0; i--)
{
reverse_string[length - i - 1] = string[i];
}
for (i = 0; i< length; i++)
{
if (reverse_string[i] == string[i])
flag = 1;
7
else
flag = 0;
}
if (flag == 1)
printf("%s is a palindrome \n", string);
else
printf("%s is not a palindrome \n", string);
}
Output:
Enter a string
sanfoundry
sanfoundry is not a palindrome
Enter a string
malayalam
malayalam is a palindrome
Result:
Thus a C program to read a string and check if it's a palindrome, without using library
functions has been executed successfully.
8
Ex.No : 2(b)
Program using string functions
Date:
Aim:
To write a C program to illustrate the usage of string functions.
Algorithm:
Step 1 : Start
Step 2 : Declare a string as input and store it in the array string[].
Step 3 : Find the length of the string using strlen() function and print the length of the
string
Step 4 :Use Strstr() which returns the pointer to the first occurrence of the string in a
given string
Step 5: Stop
Program:
#include <stdio.h>
#include <string.h>
#include<conio.h>
#include<stdio.h>
void main( )
{
Int len;
char string[20]="fresh refresh com" ; char *p;
len = strlen(string) ;
printf ( "string length = %d \n" , len ) ;
p = strstr (string,"refresh");
if(p)
{
printf("string found\n" );
printf ("First occurrence of string \"refresh\" in \"%s\" is \"%s\"",string, p);
}
else printf("string not found\n" );
getch();}
Output:
string length = 17
string found
First occurrence of string "refresh" in "fresh refresh com" is "refresh com"
Result:
Thus the C program to illustrate the usage of string functions has been executed
successfully.
9
Ex.No : 3
Programs using structures and pointers
Date:
Aim:
To write a C program to illustrate the usage of structures and pointers
Algorithm:
Step 1:Start
Step 2: Create Structure using 'struct Structure_name{}'
Step 3: Create pointer variable for structure
Step 4: Use Arrow operator for accessing members of structure using pointer variable
Step 5: Stop
Program:
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
struct person {
int age;
float weight;
char name[30];
};
void main()
{
struct person *ptr;
inti,num;
for(i=0;i<num;++i)
{
printf("Enter name, age and weight of the person respectively:\n");
scanf("%s%d%f",&(ptr+i)->name,&(ptr+i)->age,&(ptr+i)->weight);
}
10
printf("Displaying Infromation:\n");
for(i=0;i<num;++i)
printf("%s\t%d\t%.2f\n",(ptr+i)->name,(ptr+i)->age,(ptr+i)->weight);
getch();
}
Output:
Enter number of persons: 2
Enter name, age and weight of the person respectively:
Adam
2
3.2
Enter name, age and weight of the person respectively:
Eve
6
2.3
Displaying Information:
Adam23.20
Eve62.30
Result:
Thus the C program to illustrate the usage of structures and pointers has been
successfully executed.
11
Ex.No : 4(a)
Program involving dynamic memory allocation(calloc() and free())
Date:
Aim:
To write a C program to find the sum of n elements by allocating memory dynamically
using calloc() function.
Algorithm:
Step 1: Start
Step 2: Read the no. of elements
Step 3: Allocate memory dynamically using Calloc() function
Step 4: Add the elements into sum variable
Step 5: Print ‘sum’
Step 6: Deallocate memory using free()
Step 7: Stop
Program:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &num);
Result:
Thus the C program to find sum of n elements by allocating memory dynamically using
calloc() function has been successfully executed.
12
Ex.No : 4(b) Program involving dynamic memory allocation (malloc() and
Date: realloc())
Aim:
To write a C program to illustrate the usage of dynamic memory allocation using
malloc () and realloc()
Algorithm:
Step 1: Start
Step 2: Read the size of an array
Step 3: Allocate memory using malloc() function
Step 4: Print the address of an array
Step 5: To reallocate the memory, read the new size of an array.
Step 6: Print the address of an array after reallocation
Step 7: Stop
Program:
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
void main()
{
int*ptr,i, n1, n2;
printf("Enter size of array: ");scanf("%d",&n1);
ptr=(int*) malloc(n1 *sizeof(int));
printf("Address of previously allocated memory: ");
for(i=0;i< n1;++i)
printf("%u\t",ptr+i);
printf("\nEnter new size of array: ");scanf("%d",&n2);
ptr=realloc(ptr, n2);
for(i=0;i< n2;++i)
printf("%u\t",ptr+i);
getch();
}
Output:
Enter size of array: 3
Address of previously allocated memory: 10760208 10760212 10760216
Result:
Thus the C program to illustrate the usage of dynamic memory allocation using malloc
() and realloc() has been executed successfully.
13
Ex.No:5a
Array implementation of stack
Date:
Aim:
To write a C program to implement a stack using array.
Algorithm:
Before implementing actual operations, first follow the below steps to create an empty stack.
Step 1: Include all the header files which are used in the program and define a
constant 'SIZE' with specific value.
Step 2: Declare all the functions used in stack implementation.
Step 3: Create a one dimensional array with fixed size (int stack[SIZE])
Step 4: Define a integer variable 'top' and initialize with '-1'. (int top = -1)
Step 5: In main method display menu with list of operations and make suitable function
calls to perform operation selected by the user on the stack.
push(value) - Inserting value into the stack
Step 1: Check whether stack is FULL. (top == SIZE-1)
Step 2: If it is FULL, then display "Stack is FULL!!! Insertion is not possible!!!" and
terminate the function.
Step 3: If it is NOT FULL, then increment top value by one (top++) and set stack[top] to
value (stack[top] = value).
pop() - Delete a value from the Stack
Step 1: Check whether stack is EMPTY. (top == -1)
Step 2: If it is EMPTY, then display "Stack is EMPTY!!! Deletion is not possible!!!" and
terminate the function.
Step 3: If it is NOT EMPTY, then delete stack[top] and decrement top value by one (top-
-).
display() - Displays the elements of a Stack
Step 1: Check whether stack is EMPTY. (top == -1)
Step 2: If it is EMPTY, then display "Stack is EMPTY!!!" and terminate the function.
Step 3: If it is NOT EMPTY, then define a variable 'i' and initialize with top.
Display stack[i] value and decrement i value by one (i--).
Step 4: Repeat above step until i value becomes '0'.
Program:
#include<stdio.h>
#include<conio.h>
#define SIZE 10
void push(int);
void pop();
void display();
int stack[SIZE], top = -1;
void main()
14
{
int value, choice;
clrscr();
while(1){
printf("\n\n***** MENU *****\n");
printf("1. Push\n2. Pop\n3. Display\n4. Exit");
printf("\nEnter your choice: ");
scanf("%d",&choice);
switch(choice){
case 1: printf("Enter the value to be insert: ");
scanf("%d",&value);
push(value);
break;
case 2: pop();
break;
case 3: display();
break;
case 4: exit(0);
default: printf("\nWrong selection!!! Try again!!!");
} }}
void push(int value){
if(top == SIZE-1)
printf("\nStack is Full!!! Insertion is not possible!!!");
else{
top++;
stack[top] = value;
printf("\nInsertion success!!!");
}}
void pop(){
if(top == -1)
printf("\nStack is Empty!!! Deletion is not possible!!!");
else{
printf("\nDeleted : %d", stack[top]);
top--;
}}
void display(){
if(top == -1)
printf("\nStack is Empty!!!");
else{
inti;
printf("\nStack elements are:\n");
for(i=top; i>=0; i--)
15
printf("%d\n",stack[i]);
}}
Output:
***** MENU *****
1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 1
Enter the value to be insert: 4
Insertion success!!!
***** MENU *****
1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 1
Enter the value to be insert: 5
Insertion success!!!
***** MENU *****
1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 2
Deleted : 5
***** MENU *****
1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 3
Stack elements are:
4
***** MENU *****
1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 4
Result:
Thus the C program to implement a stack using array has been successfully implemented.
16
Ex.No:5b
Array implementation of Queue
Date:
Aim:
To write a C program to implement Queue data structure using array
Algorithm:
Before we implement actual operations, first follow the below steps to create an empty
queue.
Step 1: Include all the header files which are used in the program and define a
constant 'SIZE' with specific value.
Step 2: Declare all the user defined functions which are used in queue implementation.
Step 3: Create a one dimensional array with above defined SIZE (int queue[SIZE])
Step 4: Define two integer variables 'front' and 'rear' and initialize both with '-1'. (int front
= -1, rear = -1)
Step 5: Then implement main method by displaying menu of operations list and make
suitable function calls to perform operation selected by the user on queue.
17
Program:
#include<stdio.h>
#include<conio.h>
#define SIZE 10
void enQueue(int);
void deQueue();
void display();
void main()
{
int value, choice;
clrscr();
while(1){
printf("\n\n***** MENU *****\n");
printf("1. Insertion\n2. Deletion\n3. Display\n4. Exit");
printf("\nEnter your choice: ");
scanf("%d",&choice);
switch(choice){
case 1: printf("Enter the value to be insert: ");
scanf("%d",&value);
enQueue(value);
break;
case 2: deQueue();
break;
case 3: display();
break;
case 4: exit(0);
default: printf("\nWrong selection!!! Try again!!!");
} }}
void enQueue(int value){
if(rear == SIZE-1)
printf("\nQueue is Full!!! Insertion is not possible!!!");
else{
if(front == -1)
front = 0;
rear++;
queue[rear] = value;
printf("\nInsertion success!!!"); }}
void deQueue(){
if(front == rear)
18
printf("\nQueue is Empty!!! Deletion is not possible!!!");
else{ printf("\nDeleted : %d", queue[front]);
front++;
if(front == rear)
front = rear = -1; }}
void display(){ if(rear == -1)
printf("\nQueue is Empty!!!");
else{
inti;
printf("\nQueue elements are:\n");
for(i=front; i<=rear; i++)
printf("%d\t",queue[i]);
}}
Output:
***** MENU *****
1. Insertion
2. Deletion
3. Display
4. Exit
Enter your choice: 1
Enter the value to be insert: 1
Insertion success!!!
***** MENU *****
1. Insertion
2. Deletion
3. Display
4. Exit
Enter your choice: 1
Enter the value to be insert: 2
Insertion success!!!
***** MENU *****
1. Insertion
2. Deletion
3. Display
4. Exit
Enter your choice: 3
Queue elements are:
1 2
***** MENU *****
1. Insertion
2. Deletion
3. Display
4. Exit
Enter your choice: 4
Result:
Thus the C program to implement Queue data structure using array has been successfully
executed.
19
Ex.No:7a
Linked list implementation of stack
Date:
Aim:
To write a C program to implement stack using linked list
Algorithm:
To implement stack using linked list, we need to set the following things before implementing
actual operations
Step 1: Include all the header files which are used in the program. And declare all
the user defined functions.
Step 2: Define a 'Node' structure with two members data and next.
Step 3: Define a Node pointer 'top' and set it to NULL.
Step 4: Implement the main method by displaying Menu with list of operations and make
suitable function calls in the main method.
20
Program:
#include<stdio.h>
#include<conio.h>
struct Node
{
int data;
struct Node *next;
}*top = NULL;
void push(int);
void pop();
void display();
void main()
{
int choice, value;
clrscr();
printf("\n:: Stack using Linked List ::\n");
while(1){
printf("\n****** MENU ******\n");
printf("1. Push\n2. Pop\n3. Display\n4. Exit\n");
printf("Enter your choice: ");
scanf("%d",&choice);
switch(choice){
case 1: printf("Enter the value to be insert: ");
scanf("%d", &value);
push(value);
break;
case 2: pop(); break;
case 3: display(); break;
case 4: exit(0);
default: printf("\nWrong selection!!! Please try again!!!\n");
}
}
}
void push(int value)
{
struct Node *newNode;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
if(top == NULL)
21
newNode->next = NULL;
else
newNode->next = top;
top = newNode;
printf("\nInsertion is Success!!!\n");
}
void pop()
{
if(top == NULL)
printf("\nStack is Empty!!!\n");
else{
struct Node *temp = top;
printf("\nDeleted element: %d", temp->data);
top = temp->next;
free(temp);
}
}
void display()
{
if(top == NULL)
printf("\nStack is Empty!!!\n");
else{
struct Node *temp = top;
while(temp->next != NULL){
printf("%d--->",temp->data);
temp = temp -> next;
}
printf("%d--->NULL",temp->data);
}
}
Output:
22
Insertion is Success!!!
****** MENU ******
1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 1
Enter the value to be insert: 5
Insertion is Success!!!
****** MENU ******
1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 3
5--->3--->NULL
****** MENU ******
1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 2
Deleted element: 5
****** MENU ******
1. Push
2. Pop
3. Display
4. Exit
Enter your choice:
3
3--->NULL
****** MENU ******
1. Push
2. Pop
3. Display
4. Exit
Enter your choice:4
Result:
Thus the C program to implement stack using linked list has been successfully executed.
23
Ex.No:7b
Linked list implementation of Queue
Date:
Aim:
To write a C program to implement queue using linked list.
Algorithms:
To implement queue using linked list , we need to set the following things before implementing
actual operations.
Step 1: Include all the header files which are used in the program. And declare all
the user defined functions.
Step 2: Define a 'Node' structure with two members data and next.
Step 3: Define two Node pointers 'front' and 'rear' and set both to NULL.
Step 4: Implement the main method by displaying Menu of list of operations and make
suitable function calls in the main method to perform user selected operation.
Program:
#include<stdio.h>
#include<conio.h>
24
struct Node
{
int data;
struct Node *next;
}*front = NULL,*rear = NULL;
void insert(int);
void delete();
void display();
void main()
{
int choice, value;
clrscr();
printf("\n:: Queue Implementation using Linked List ::\n");
while(1){
printf("\n****** MENU ******\n");
printf("1. Insert\n2. Delete\n3. Display\n4. Exit\n");
printf("Enter your choice: ");
scanf("%d",&choice);
switch(choice){
case 1: printf("Enter the value to be insert: ");
scanf("%d", &value);
insert(value);
break;
case 2: delete(); break;
case 3: display(); break;
case 4: exit(0);
default: printf("\nWrong selection!!! Please try again!!!\n");
}
}
}
void insert(int value)
{
struct Node *newNode;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode -> next = NULL;
if(front == NULL)
front = rear = newNode;
else{
25
rear -> next = newNode;
rear = newNode;
}
printf("\nInsertion is Success!!!\n");
}
void delete()
{
if(front == NULL)
printf("\nQueue is Empty!!!\n");
else{
struct Node *temp = front;
front = front -> next;
printf("\nDeleted element: %d\n", temp->data);
free(temp);
}
}
void display()
{
if(front == NULL)
printf("\nQueue is Empty!!!\n");
else{
struct Node *temp = front;
while(temp->next != NULL){
printf("%d--->",temp->data);
temp = temp -> next;
}
printf("%d--->NULL\n",temp->data);
}
}
Output:
:: Queue Implementation using Linked List ::
Insertion is Success!!!
26
****** MENU ******
1. Insert
2. Delete
3. Display
4. Exit
Enter your choice:
1
Enter the value to be insert: 5
Insertion is Success!!!
Deleted element: 3
Result:
Thus the c program to implement queue using linked list has been successfully executed.
27
Ex.No:8a
Implementation of Trees, Tree Traversals
Date:
Aim:
To write a C program to implement a tree and its traversals
Algorithm:
Pre-order display
Step1:Display value of root node.
Step2:Call print_preorder() function recursively while there is non-NULL left node
Step3:Call print_preorder() function recursively while there is non-NULL right node
In-order display
28
Step1:Call print_inorder() function recursively while there is non-NULL left node
Step2: Display value of root node.
Step3:Call print_inorder() function recursively while there is non-NULL right node
Post-order display
Step1:Call print_postorder() function recursively while there is non-NULL left node
Step2:Call print_postorder() function recursively while there is non-NULL right node
Step3:Display value of root node.
Program:
#include<stdlib.h>
#include<stdio.h>
struct bin_tree {
int data;
struct bin_tree * right, * left;
};
typedef struct bin_tree node;
if(val< (*tree)->data)
{
insert(&(*tree)->left, val);
}
else if(val> (*tree)->data)
{
insert(&(*tree)->right, val);
}
29
void print_preorder(node * tree)
{
if (tree)
{
printf("%d\n",tree->data);
print_preorder(tree->left);
print_preorder(tree->right);
}
}
if(val< (*tree)->data)
{
search(&((*tree)->left), val);
}
else if(val> (*tree)->data)
{
search(&((*tree)->right), val);
}
else if(val == (*tree)->data)
{
return *tree;
}
}
void main()
{
node *root;
node *tmp;
//inti;
root = NULL;
/* Inserting nodes into tree */
insert(&root, 9);
insert(&root, 4);
insert(&root, 15);
insert(&root, 6);
insert(&root, 12);
insert(&root, 17);
insert(&root, 2);
/* Printing nodes of tree */
printf("Pre Order Display\n");
print_preorder(root);
32
Ex.No:8b
Implementation of Binary Search trees
Date:
Aim:
To write a C program to demonstrate insert operation in binary search tree
Algorithm:
Program:
#include<stdio.h>
#include<stdlib.h>
struct node
{
int key;
struct node *left, *right;
};
33
/* A utility function to insert a new node with given key in BST */
struct node* insert(struct node* node, int key)
{
/* If the tree is empty, return a new node */
if (node == NULL) return newNode(key);
/* Otherwise, recur down the tree */
if (key < node->key)
node->left = insert(node->left, key);
else if (key > node->key)
node->right = insert(node->right, key);
Aim:
To write a C program to implement linear search in an array
Algorithm:
Step 1: Start from the leftmost element of arr[] and one by one compare x with each
element of arr[]
Step 2: If x matches with an element, return the index.
Step 3: If x doesn’t match with any of elements, return -1.
Program:
#include <stdio.h>
int search(int arr[], int n, int x)
{
int i;
for (i = 0; i < n; i++)
if (arr[i] == x)
return i;
return -1;
}
int main(void)
{
int arr[] = {2, 3, 10,4, 40};
int n = sizeof(arr)/ sizeof(arr[0]);
int x = 10;
int result = search(arr,n-1, x);
(result == -1)? printf("Element is not present in array")
: printf("Element is present at index %d",
result);
return 0;
}
Output:
Element is present at index 2
Result:
Thus the C program to implement linear search in an array has been successfully
executed
35
Ex.No:9b
Implementation of Binary Search
Date:
Aim:
To write a C program to implement binary search in an array
Algorithm:
Program:
// C program to implement recursive Binary Search
#include <stdio.h>
36
// We reach here when element is not
// present in array
return -1;
}
int main(void)
{
int arr[] = {2, 3, 4, 10, 40};
int n = sizeof(arr)/ sizeof(arr[0]);
int x = 10;
int result = binarySearch(arr, 0, n-1, x);
(result == -1)? printf("Element is not present in array")
: printf("Element is present at index %d",
result);
return 0;
}
Output:
Element is present at index 3
Result:
Thus the C program to implement binary search in an array has been successfully
executed.
37
Ex.No:10a
Implementation of Insertion Sort
Date:
Aim:
To write a C program to implement insertion sort
Algorithm:
Step 1: Assume that first element in the list is in sorted portion of the list and remaining
all elements are in unsorted portion.
Step 2: Consider first element from the unsorted list and insert that element into the
sorted list in order specified.
Step 3: Repeat the above process until all the elements from the unsorted list are moved
into the sorted list.
Program:
#include<stdio.h>
#include<conio.h>
void main(){
int size, i, j, temp, list[100];
printf("Enter the size of the list: ");
scanf("%d", &size);
printf("Enter %d integer values: ", size);
for (i = 0; i < size; i++)
scanf("%d", &list[i]);
for (i = 1; i < size; i++) {
temp = list[i];
j = i - 1;
while ((temp < list[j]) && (j >= 0)) {
list[j + 1] = list[j];
j = j - 1;
} list[j + 1] = temp; }
printf("List after Sorting is: ");
for (i = 0; i < size; i++)
printf(" %d", list[i]);
getch();}
Output:Enter the size of the list: 5
Enter 5 integer values: 6
3
9
1
2
List after Sorting is: 1 2 3 6 9
Result:
Thus the C program to implement insertion sort has been successfully executed
38
Ex.No:10b
Implementation of Bubble Sort
Date:
Aim:
To write a C program to implement Bubble sort
Algorithm:
Step 1: Starting with the first element(index = 0), compare the current element with the
next element of the array.
Step 2: If the current element is greater than the next element of the array, swap them.
Step 3: If the current element is less than the next element, move to the next
element. Repeat Step 1.
Program:
#include <stdio.h>
#include <conio.h>
void bubbleSort(int arr[], int n)
{ int i, j, temp;
for(i = 0; i < n; i++)
{ for(j = 0; j < n-i-1; j++)
{
if( arr[j] > arr[j+1])
{ // swap the elements
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
} } }
// print the sorted array
printf("Sorted Array: ");
for(i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}}
void main()
{
int arr[100], i, n, step, temp;
// ask user for number of elements to be sorted
printf("Enter the number of elements to be sorted: ");
scanf("%d", &n);
// input elements if the array
for(i = 0; i < n; i++)
{
39
printf("Enter element no. %d: ", i+1);
scanf("%d", &arr[i]);
}
// call the function bubbleSort
bubbleSort(arr, n);
getch();
// return 0;
}
Output:
Result:
Thus, the C program to implement Bubble sort has been successfully executed.
40
Ex.No:11a
Implementation of Quick Sort
Date:
Aim:
To write a C program to implement Quick sort
Algorithm:
Step 1: After selecting an element as pivot, which is the last index of the array
Step 2: Do partitioning where the array elements are so positioned that all the elements
smaller than the pivot will be on the left side of the pivot and all the elements greater than
the pivot will be on the right side of it and the pivot element will be at its
final sorted position.
Step 3: Then we pick subarrays, elements on the left of pivot and elements on the right
of pivot, and we perform partitioning on them by choosing a pivot in the subarrays to get
them sorted.
Program:
#include<stdio.h>
#include<conio.h>
// A utility function to swap two elements
void swap(int* a, int* b)
{
int t = *a;
*a = *b;
*b = t;
}
/* This function takes last element as pivot, places the pivot element at its correct position in
sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements
to right of pivot */
int partition (int arr[], int low, int high)
{
int pivot = arr[high]; // pivot
int i = (low - 1); // Index of smaller element
int j;
for (j = low; j <= high- 1; j++)
{
// If current element is smaller than or
// equal to pivot
if (arr[j] <= pivot)
{ i++; // increment index of smaller element
swap(&arr[i], &arr[j]);
41
} }
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}
/* The main function that implements QuickSort
arr[] --> Array to be sorted,
low --> Starting index,
high --> Ending index */
void quickSort(int arr[], int low, int high)
{ if (low < high) {
/* pi is partitioning index, arr[p] is now
at right place */
int pi = partition(arr, low, high);
Result:
Thus, the C program to implement Quick sort has been successfully executed.
42
Ex.No:11b
Implementation of Merge Sort
Date:
Aim:
To write a C program to implement Merge sort
Algorithm:
Step 1: Take a variable p and store the starting index of array in this.
Step 2:And take another variable r and store the last index of array in it.
Step 3:Thenfind the middle of the array using the formula (p + r)/2 and mark the middle
index as q, and break the array into two subarrays, from p to q and from q + 1 to r index.
Step 4: Then divide these 2 subarrays again, just like we divided main array and this
continues.
Step 5: Once we have divided the main array into subarrays with single elements, then we
start merging the subarrays.
Program:
/*
a[] is the array, p is starting index, that is 0,
and r is the last index of array.
*/
#include <stdio.h>
#include<conio.h>
// lets take a[5] = {32, 45, 67, 2, 7} as the array to be sorted.
43
// function to merge the subarrays
void merge(int a[], int p, int q, int r)
{
int b[5]; //same size of a[]
int i, j, k;
k = 0;
i = p;
j = q + 1;
while(i <= q && j <= r)
{
if(a[i] < a[j])
{
b[k++] = a[i++]; // same as b[k]=a[i]; k++; i++;
}
else
{
b[k++] = a[j++];
}
}
while(i <= q)
{
b[k++] = a[i++];
}
while(j <= r)
{
b[k++] = a[j++];
}
void main()
{
int arr[] = {32, 45, 67, 2, 7};
int len = sizeof(arr)/sizeof(arr[0]);
Output:
Given array:
32 45 67 2 7
Sorted array:
2 7 32 45 67
Result:
Thus the C program to implement Merge sort has been successfully executed and
verified.
45
Ex.No:12
Implementation of hash functions, collision resolution technique
Date:
Aim:
To write a C program to implement Hash Tables with linear Probing and Quadratic
Probing
Algorithm:
Step 1:Start
Step 2:Read the size 'tsize' of the hash table.
Step 3:Read the elements to be inserted in the hash table
Step 4:Use formula (key + 1) % tsize to implement hash table using Linear Probing
Step 5: Use formula (key + (j * j)) % tsize to implement hash table using Quadratic
Probing where j= 1, 2, 3, 4 and so on.
Step 6:Exit
Program:
#include <stdio.h>
#include <conio.h>
int tsize;
//-------LINEAR PROBING-------
int rehashl(int key)
{
int i ;
i = (key+1)%tsize ;
return i ;
}
//-------QUADRATIC PROBING-------
int rehashq(int key, int j)
{
int i ;
i = (key+(j*j))%tsize ;
46
return i ;
}
void main()
{
int key,arr[20],hash[20],i,n,s,op,j,k ;
clrscr() ;
printf ("Enter the size of the hash table: ");
scanf ("%d",&tsize);
for (i=0;i<tsize;i++)
hash[i]=-1 ;
do
{
printf("\n\n1.Linear Probing\n2.Quadratic Probing \n3.Exit \nEnter your option: ");
scanf("%d",&op);
switch(op)
{
case 1:
for (i=0;i<tsize;i++)
hash[i]=-1 ;
for(k=0;k<n;k++)
{
key=arr[k] ;
i = hasht(key);
while (hash[i]!=-1)
{
i = rehashl(i);
}
hash[i]=key ;
}
47
printf("\nThe elements in the array are: ");
for (i=0;i<tsize;i++)
{
printf("\n Element at position %d: %d",i,hash[i]);
}
break ;
case 2:
for (i=0;i<tsize;i++)
hash[i]=-1 ;
for(k=0;k<n;k++)
{
j=1;
key=arr[k] ;
i = hasht(key);
while (hash[i]!=-1)
{
i = rehashq(i,j);
j++ ;
}
hash[i]=key ;
}
printf("\nThe elements in the array are: ");
for (i=0;i<tsize;i++)
{
printf("\n Element at position %d: %d",i,hash[i]);
}
break ;
}
}while(op!=3);
getch() ;
}
Output:
Enter the size of the hash table: 10
48
1.Linear Probing
2.Quadratic Probing
3.Exit
Enter your option: 1
1.Linear Probing
2.Quadratic Probing
3.Exit
Enter your option: 2
1.Linear Probing
2.Quadratic Probing
3.Exit
Enter your option: 3
Result:
Thus the C program to implement Hash Tables with linear Probing and Quadratic
Probing have been successfully executed and verified.
49
Ex.No :13
Implementation of File concepts
Date:
Aim:
To write a C program to illustrate data manipulation using file handling
Algorithm:
Step 1: Start
Step 2: Open file “input.txt” in read mode.
Step 3: Read the contents of file
Step 4: Reverse the contents of the file and print it on the standard output.
Step 5: Stop
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
int i,pos;
fp=fopen("input.txt","r");
if(fp==NULL) {
printf("File does not exist.."); }
fseek(fp,0,SEEK_END);
pos=ftell(fp);
//printf("Current postion is %d\n",pos);
i=0;
while(i<pos) {
i++;
fseek(fp,-i,SEEK_END);
//printf("%c",fgetc(fp));
ch=fgetc(fp);
printf("%c",ch); }
getch();}
Input.txt
hai
Output:
iah
50