In: Computer Science
coding the following project:
Setting up structures to store and retrieve data. A major requirement of virtually all projects in the financial world involves the storage and retrieval of data. project must be properly modularized and allow for more than one way to store the data to satisfy the various needs of clients.The first manner is by storing data using hashtables (or hash maps) as the basis of storing and retrieving data.
The below code satisfies the given requirement to insert and retrieve the data using structure and hash arrays as follow:-
----------------------------------------------------------------------------------------------------------------------------------------
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#define SIZE 20
struct SRData { //creating the structure with the name SRdata having SRData_data and SRData_key as arguments.
int SRData_data;
int SRData_key;
};
struct SRData*hash_Array[SIZE];
struct SRData* SRData_item;
int hashCode(int SRData_key) { //declaring hashcode for specifing the key
return SRData_key % SIZE;
}
void insert(int SRData_key,int SRData_data) { //insert function which takes arguments as data and key pair
printf("Enter data ");
scanf("%d", &SRData_data);
printf("Enter key");
scanf("%d", &SRData_key);
struct SRData *SRData_item = (struct SRData*) malloc(sizeof(struct SRData));
SRData_item->SRData_data = SRData_data;
SRData_item->SRData_key = SRData_key;
int hash_Index = hashCode(key); //indexing hash with the key data to get hash
while(hashArray[hash_Index] != NULL &&hash_Array[hash_Index]->SRData_key != -1) { //insering the data into arrray untill the index become NULL or empty
++hash_Index; // to go for next index
hash_Index %= SIZE;
}
hash_Array[hash_Index] = SRData_item;
}
void retrieve_data() { //retrieve_data funciton is used to retrieve the data
int i = 0;
printf("inserted data : ");
for(i = 0; i<SIZE; i++) { //this loop is used to retrive the data untill the size of the hash array
if(hashArray[i] != NULL)
printf(" (%d,%d)",hashArray[i]->SRData_key,hashArray[i]->SRData_data); //priting data and key pair to the output
else
printf(" ~~ ");
}
printf("\n");
}
int main() { //main funciton whcih calls insert and retrieve_data functions
char choice;
int data,key;
printf("do you want to insert the data?(y/n)");
scanf("%c",&choice);
while(choice=="y")
{
insert(data,key);
printf("do you want to insert the data?(y/n)");
scanf("%c",&choice);
}
retrieve_data();
}
Output:-
--------
do you want to insert the data?(y/n)?
y
Enter data
27
Enter key
1
do you want to insert the data?(y/n)?
y
Enter data
26
Enter key
2
do you want to insert the data?(y/n)?
y
Enter data
92
Enter key
3
do you want to insert the data?(y/n)?
n
inserted data :
(27,1)
(26,2)
(92,3)