//Program for creating hash table and handling collision using linear probing without replacement
#include<stdio.h> //Header files
#include<stdlib.h>
int hash(int key) //Function to find the position of number
{
return(key%10);
}
int main() //Start of main function
{
int ht[10],i,k,pos,num,flag; //Declaration of variables
char ch;
for(i=0;i<10;i++)
ht[i]=-1; //Initially the value in table is -1
do
{
printf("\nEnter the number : ");
scanf("%d",&num);
flag=1;
pos=hash(num);
k=pos;
do
{
if(ht[k]==-1) //Check whether the position is empty or not
{
printf("\nThe position %d is empty",k);
printf("\nValue is stored at position %d",k);
ht[k]=num;
flag=0;
}
else //If required position is not empty
{
printf("\nCollision occurs");
printf("\nNext position is %d",(k+1)%10);
}
k=(k+1)%10;
}while(flag && k!=pos);
if(flag)
{
printf("\nTable full");
ch='n';
}
else
{
printf("\nAdd another(y/n):");
scanf("%s",&ch);
}
}while(ch=='y'|| ch=='Y');
printf("\nHash table is ");
printf("\n===============================");
printf("\nPosition \t\t key");
printf("\n===============================");
for(i=0;i<10;i++)
{
printf("\n%d\t\t\t%d",i,ht[i]);
}
printf("\n===============================");
printf("\n\n");
} //End of main function
/*
****OUTPUT****
Enter the number 10
The position 0 is empty
Value is stored at position 0
Add another(y/n):
Enter the number 20
Collision occurs
Next position is 1
The position 1 is empty
Value is stored at position 1
Add another(y/n):
Enter the number21
Collision occurs
Next position is 2
The position 2 is empty
Value is stored at position 2
Add another(y/n):
Enter the number45
The position 5 is empty
Value is stored at position 5
Add another(y/n):
Enter the number 56
The position 6 is empty
Value is stored at position 6
Add another(y/n):
Enter the number76
Collision occurs
Next position is 7
The position 7 is empty
Value is stored at position 7
Add another(y/n):
Hash table is
Position key
0 10
1 20
2 21
3 -1
4 -1
5 45
6 56
7 76
8 -1
9 -1
*/