In: Computer Science
Write a program in C as per following requirements:
a) It takes two fields from the user 1) NAME and 2) age. Hint: (Take the name of employee
in an array of 50 characters).
b) It saves the data given by the user in a doubly link list.
c) As soon a record is entered by the user it should be given a record number or serial
number.
d) Program should have a menu for
a. Entering new data.
b. Printing a particular record by serial number.
c. Printing the whole data with serial numbers.
d. Exit the program.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int count=0;
struct node
{
char name[50];
int sno;
int age;
struct node *next;
struct node *pre;
};
struct node *cur=NULL,*head=NULL;//head is the start node and cur is the current node
void add()/*function to add new nodes*/
{
struct node *newnode=(struct node*) malloc(sizeof(struct node));
char name[50];
int age;
printf("Enter the name :");
scanf("%s",name);
printf("Enter the age :");/*inputting name and age and assigning it to the node*/
scanf("%d",&age);
strcpy( newnode->name,name);
newnode->age=age;
count++;/*glogal variable which gets incremented when a new node comes*/
newnode->sno=count;
if(head==NULL)
{
head=newnode; /*checks if head is null. then assign it is assigned with new node*/
head->pre=NULL;
head->next=head;
cur=head;
}
else
{
newnode->pre=cur;
newnode->next=NULL;/*current node'snextis assigned to new node.previousnode's next is assigned to current node*/
cur->next=newnode;
cur=newnode;/*new node is assigned tocurrent node to keep track of nodes*/
}
}
void displayslno(int sno)
{
struct node *temp=head;
int f=0;
while(temp!=NULL)/*loop through all nodes*/
{
if(temp->sno==sno)/*checks if sno entered equals node's sno*/
{
printf("\nSerial Number : %d",temp->sno);
printf("\nName :%s",temp->name);
printf("\nAge :%d",temp->age);
temp=temp->next;
f=1;/*flag to check if the condition satisfies*/
break;
}
}
if(f==0)
{
printf("\nInvalid Serail Number\n");
}
}
void display()
{
struct node *temp=head;/*function to display all nodes*/
while(temp!=NULL)
{
printf("\nSerial Number : %d",temp->sno);
printf("\nName : %s",temp->name);
printf("\nAge : %d",temp->age);
temp=temp->next;
}
}
int main()
{
struct node *new_nd = (struct node*) malloc(sizeof(struct node));
int sno;
int ch,choice;
do
{
printf("Press options(1/2/3/4)\n1.Enter new data\n2. display a single record\n3.Display entire data\n4.Exit\n");
scanf("%i",&ch);
switch(ch)
{
case 1:add();
break;
case 2:printf("Enter the slno:");
scanf("%i",&sno);
displayslno(sno);
break;
case 3:display();
break;
case 4:printf("Exiting!!!");
break;
default:printf("Invalid Choice\n");
}
if(ch!=4)
{
printf("\nPress 1 to continue\n");
scanf("%d",&choice);
}
}while((choice==1)&&(ch!=4));
return 0;
}