Can you tell me if this is correct way to do?
This is my sample code in student information in queue. my problem is that I want to insert a student number in the struct but it doesn't repeat when I input the same student number.
#include <stdio.h>
#include <stdlib.h>
struct node
{
char No[12],Name[24],crsysr[10];
float gwa;
struct node *ptr;
}*front,*rear,*temp,*front1;
int frontelement();
void insert(char *data, char *name,char *yearsec,float gwa);
void del();
void empty();
void display();
void create();
void queuesize();
void removeduplicate();
int count = 0;
void main()
{
int ch, pos,i,e;
char no[12], name[24],crsyr[10];
float gwa,tgwa;
create();
while (1)
{
printf("\n 1 - Enque");
printf("\n 2 - Deque");
printf("\n 3 - Front element");
printf("\n 4 - Empty");
printf("\n 5 - Exit");
printf("\n 6 - Display");
printf("\n 7 - Queue size");
printf("\n Enter choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf ("how Many student do you want to enter?: ");
int n;
scanf("%d",&n);
for(int i=0; i<n; ++i)
{
fflush(stdin);
printf("\n Enter Student number : ");
gets(no);
printf("\n Enter Student name : ");
gets(name);
printf("\n Enter Student Year and Sec : ");
gets(crsyr);
fflush(stdin);
printf("\n Enter Student gwa : ");
scanf("%f", &gwa);
insert(no, name, crsyr, gwa);
count++;
}
printf("Press any key to contiue...");
getch();
system("cls");
break;
case 2:
del();
break;
case 3:
e = frontelement();
if (e != 0)
printf("Front element : %d", e);
else
printf("\n No front element in Queue as queue is empty");
system("cls");
break;
case 4:
empty();
break;
case 5:
exit(0);
case 6:
system("cls");
removeduplicate(temp->ptr);
display();
printf("Press any key to contiue...");
getch();
system("cls");
break;
case 7:
queuesize();
break;
default:
printf("Wrong choice, Please enter correct choice ");
break;
}
}
}
void create()
{
front = rear = NULL;
}
void queuesize()
{
printf("\n Queue size : %d", count);
}
void insert(char *data, char *name,char *yearsec, float gwa)
{
if (rear == NULL)
{
rear = (struct node *)malloc(1*sizeof(struct node));
rear->ptr = NULL;
strcpy(rear->No, data);
strcpy(rear->Name, name);
strcpy(rear->crsysr, yearsec);
rear->gwa=gwa;
front = rear;
}
else
{
temp=(struct node *)malloc(1*sizeof(struct node));
rear->ptr = temp;
strcpy(temp->No, data);
strcpy(temp->Name, name);
strcpy(temp->crsysr, yearsec);
temp->gwa=gwa;
temp->ptr = NULL;
rear = temp;
}
}
void display()
{
front1 = front;
int i;
if ((front1 == NULL) && (rear == NULL))
{
printf("Queue is empty");
return;
}
printf("Student Number\t\tName\t\tSection\t\tGwa\n\n");
while (front1 != rear)
{
printf("%s \t",front1->No);
printf("%s \t",front1->Name);
printf("%s \t",front1->crsysr);
printf("%f \t", front1->gwa);
front1 = front1->ptr;
printf("\n");
}
if (front1 == rear)
printf("%s \t",front1->No);
printf("%s \t",front1->Name);
printf("%s \t",front1->crsysr);
printf("%f\t", front1->gwa);
printf("\n");
}
void del()
{
front1 = front;
if (front1 == NULL)
{
printf("\n Error: Trying to display elements from empty queue");
return;
}
else
if (front1->ptr != NULL)
{
front1 = front1->ptr;
printf("\n Dequed Student num : " );
puts(front->No);
printf("\n Dequed Name : ");
puts(front->Name);
printf("\n Dequed Year and section : ");
puts(front->crsysr);
printf("\n Dequed GWA : %f", front->gwa);
free(front);
front = front1;
}
else
{
printf("\n Dequed Student Num : ", front->No);
printf("\n Dequed Name : ", front->Name);
printf("\n Dequed Year and section :", front->crsysr);
printf("\n Dequed GWA : %f", front->gwa);
free(front);
front = NULL;
rear = NULL;
}
count--;
}
int frontelement()
{
if ((front != NULL) && (rear != NULL))
return(front->No,front->Name,front->crsysr,front->gwa);
else
return 0;
}
void empty()
{
if ((front == NULL) && (rear == NULL))
printf("\n Queue empty");
else
printf("Queue not empty");
}
void removeduplicate(struct node *front) {
struct node *ptr1, *ptr2, *duplicate;
ptr1 = front;
while (ptr1 != NULL && ptr1->ptr != NULL)
{
ptr2 = ptr1;
/* Compare the current element with rest of the elements */
while (ptr2->ptr != NULL)
{
if (strcmp(ptr1->No == ptr2->ptr->No && ptr1->Name == ptr2->ptr->Name && ptr1->crsysr == ptr2->ptr->crsysr && ptr1->gwa == ptr2->ptr->gwa)==0)
{
duplicate = ptr2->ptr;
ptr2->ptr = ptr2->ptr->ptr;
free(duplicate);
} else
{
ptr2 = ptr2->ptr;
}
ptr1 = ptr1->ptr;
}
}
}
Related
I am trying to implement linked list in C, having options for creation, insertion, deletion and display.
My code is:
#include <stdio.h>
#include <conio.h>
void createFirst(int);
void appendNode(int);
void insertFirst(int);
void insertNode(int,int);
void deleteFirst();
void deleteNode(int);
void display();
struct Node
{
int data;
struct Node *link;
};
typedef struct Node Node;
Node *start = NULL;
int count=0;
void main()
{
int ch;
do
{
printf("\f\n");
printf("1. Create the list \n");
printf("2. Insert an element at any position \n");
printf("3. Delete an element at any position \n");
printf("4. Display the list \n");
printf("5. Quit \n");
printf("Enter your choice : \n");
scanf("%d",&ch);
switch(ch)
{
case 1:
{
int a;
char c;
printf("Enter the data : \n");
scanf("%d",&a);
createFirst(a);
while(1)
{
printf("Do you want to continue[Y/N] : \n");
scanf(" %c",&c);
if(c=='Y' || c=='y')
{
printf("Enter the data : \n");
scanf("%d",&a);
appendNode(a);
}
else if(c=='N' || c=='n')
{
break;
}
else
{
continue;
}
}
break;
}
case 2:
{
int a,pos;
char c;
printf("Enter the data : \n");
scanf("%d",&a);
printf("Enter the position : \n");
scanf("%d",&pos);
if(pos == 1)
{
insertFirst(a);
}
else
{
insertNode(pos,a);
}
while(1)
{
printf("Do you want to continue[Y/N] : ");
scanf(" %c",&c);
if(c=='N' || c=='n')
{
break;
}
if(c!='Y' && c!='y')
{
continue;
}
printf("Enter the data : \n");
scanf("%d",&a);
printf("Enter the position : \n");
scanf("%d",&pos);
if(pos == 1)
{
insertFirst(a);
}
else
{
insertNode(pos,a);
}
}
break;
}
case 3:
{
int pos;
char c;
printf("Enter the position : \n");
scanf("%d",&pos);
if(pos == 1)
{
deleteFirst();
}
else
{
deleteNode(pos);
}
while(1)
{
printf("Do you want to continue[Y/N] : ");
scanf(" %c",&c);
if(c=='N' || c=='n')
{
break;
}
if(c!='Y' && c!='y')
{
continue;
}
printf("Enter the position : \n");
scanf("%d",&pos);
if(pos == 1)
{
deleteFirst();
}
else
{
deleteNode(pos);
}
}
break;
}
case 4:
{
display();
break;
}
case 5:
{
return;
}
default:
{
printf("Invalid choice \n");
break;
}
}
}while(ch!=5);
}
void createFirst(int d)
{
Node newnode = {d,NULL};
start = &newnode;
count++;
}
void appendNode(int d)
{
Node temp = *start;
while(temp.link != NULL)
{
temp = *temp.link;
}
Node newnode = {d,NULL};
temp.link = &newnode;
count++;
}
void insertFirst(int d)
{
Node newnode = {d,NULL};
newnode.link = start;
start = &newnode;
count++;
}
void insertNode(int n,int d)
{
if(n>count || n<count)
{
printf("Invalid position \n");
return;
}
Node temp = *start;
int i;
for(i=1;i<n-1;i++)
{
temp = *temp.link;
}
Node newnode = {d,NULL};
newnode.link = temp.link;
temp.link = &newnode;
}
void deleteFirst()
{
if(start != NULL)
{
printf("Deleted element : %d \n",(*start).data);
start = (*start).link;
count--;
}
else
{
printf("Underflow \n");
}
}
void deleteNode(int n)
{
if(n>count || n<count)
{
printf("Invalid position \n");
return;
}
Node temp = *start;
int i;
for(i=1;i<n-1;i++)
{
temp = *temp.link;
}
printf("Deleted node : %d",temp.link->data);
temp = *(temp.link->link);
count--;
}
void display()
{
if(start == NULL)
{
printf("The list is empty \n");
return;
}
Node temp = *start;
int i;
for(i=1;i<=count;i++)
{
printf("%d ",temp.data);
temp = *temp.link;
}
}
But:
Whenever the control is going to appendNode function, the program terminates somehow.
After only creating the first node, if i go to display, it is printing some garbage value.
Please somebody help.
Your problem is on the line (inside of appendNode) which contains this: Node temp = *start;. Don't do it that way. Do it this way:
Node *temp = start;
Change the following pointer notations to accomodate this change. Like change the dot operators to the -> operator. Here's the rest of the function:
while(temp->link != NULL)
{
temp = temp->link;
}
Node *newnode = malloc (sizeof(struct Node));
newnode->data = 0;
newnode->link = NULL;
temp->link = newnode;
count++;
Can anyone tell why my recursion is messing up? THANK YOUUUUU
This is stack in C
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <unistd.h>
struct node
{
char stdNum[12], stdName[24], CnY[10];
float gwa;
struct node *link;
};
// Initialized Functions
void createStck();
void traverseStck();
void recursion();
void push();
// Declare Globally to be used in other functions
struct node *TOP = NULL;
struct node *tempTop = NULL, *tempNode = NULL;
bool tempTopExist = false, travesalDone = false, pushTemptoTop = false, firstIteration = false;
struct node *ptr = NULL;
MENU
int main()
{
system("CLS");
int input;
do
{
printf("1 - Creation of Nodes in Stack\n");
printf("2 - Traversal of Nodes in Stack\n");
printf("3 - Addition of Nodes in Stack\n");
printf("4 - Deletion of Nodes in Stack\n\n");
printf("Choice: ");
scanf("%d", &input);
} while (input > 4 || input < 1);
switch (input)
{
case 1:
createStck();
break;
case 2:
traverseStck(TOP);
break;
}
return 0;
}
Creation of Stack
void createStck()
{
struct node *PushNode = NULL;
PushNode = malloc(sizeof(struct node));
PushNode->link = NULL;
TOP = PushNode;
char resp, temp;
do
{
printf("Student Number : ");
scanf("%s", &PushNode->stdNum);
printf("Student Name : ");
scanf("%c", &temp);
scanf("%[^\n]", PushNode->stdName);
printf("Course & Year : ");
scanf("%c", &temp);
scanf("%[^\n]", PushNode->CnY);
printf("GWA : ");
scanf("%f", &PushNode->gwa);
printf("\n(ALERT) Add another node [Y/N]? ");
scanf(" %c", &resp);
if (resp == 'Y' || resp == 'y')
{
printf("\n");
PushNode = malloc(sizeof(struct node));
PushNode->link = TOP;
TOP = PushNode;
}
} while (resp == 'Y' || resp == 'y');
PushNode = NULL;
main();
}
Traversing the stack while also pushing each value into a temporary storage and finally getting it back from that temporary storage
if input = 1 2 3
stack will be 3 2 1
traversing will be 3 2 1
pushing each will end up 1 2 3 (last in last out)
the problem is when I push it back (last in last out) using recursion
void traverseStck(struct node *TOP)
{
struct node *popNode = NULL;
popNode = TOP;
if (popNode == NULL)
{
printf("The Stack is empty!");
}
else
{
do
{
printf("%s\n", TOP->stdNum);
printf("%s\n", TOP->stdName);
printf("%s\n", TOP->CnY);
printf("%f\n\n", TOP->gwa);
TOP = TOP->link;
popNode->link = NULL;
push(popNode);
tempTopExist = true;
popNode = TOP;
} while (TOP != NULL);
travesalDone = true;
push(tempTop);
getch();
main();
}
}
void recursion(struct node *poppedNode)
{
if (poppedNode == NULL)
{
tempTopExist = false;
tempTop = NULL;
tempNode = NULL;
travesalDone = false;
}
else
{
if (firstIteration == false)
{
firstIteration = true;
TOP = poppedNode;
TOP->link = NULL;
recursion(poppedNode->link);
}
else
{
tempNode = poppedNode;
tempNode->link = TOP;
TOP = tempNode;
recursion(poppedNode->link);
}
}
}
void push(struct node *poppedNode)
{
if (travesalDone == false)
{
if (tempTopExist == false)
tempTop = poppedNode;
if (tempTopExist == true)
{
tempNode = poppedNode;
tempNode->link = tempTop;
tempTop = tempNode;
}
}
if (travesalDone == true)
{
tempNode = NULL;
recursion(poppedNode);
firstIteration = false;
}
}
I did not use recursion and just made a copy to be traversed making the original stack untouched.
Solved. Thank you guys
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <unistd.h>
struct node
{
char stdNum[12], stdName[24], CnY[10];
float gwa;
struct node *link;
};
// Initialized Functions to avoid errors
void createStck();
void traverseStck();
void addStck();
void delStck();
void endProg();
// Declared Globally to be used in other functions
struct node *TOP = NULL, *ptr = NULL;
// Check if Stack is already created
bool stackCreated = false;
int main()
{
system("CLS");
int input;
do
{
system("CLS");
printf("1 - Creation of Nodes in Stack\n");
printf("2 - Traversal of Nodes in Stack\n");
printf("3 - Addition of Nodes in Stack\n");
printf("4 - Deletion of Nodes in Stack\n");
printf("5 - End Stack Program\n\n");
printf("Choice: ");
scanf("%d", &input);
} while (input > 5 || input < 1);
switch (input)
{
case 1:
createStck();
break;
case 2:
traverseStck();
break;
case 3:
addStck();
break;
case 4:
delStck();
break;
case 5:
endProg();
break;
}
return 0;
}
void createStck()
{
system("CLS");
if (!stackCreated)
{
struct node *PushNode = NULL;
PushNode = malloc(sizeof(struct node));
PushNode->link = NULL;
TOP = PushNode;
char resp, temp;
do
{
printf("Student Number : ");
scanf("%s", &PushNode->stdNum);
printf("Student Name : ");
scanf("%c", &temp);
scanf("%[^\n]", PushNode->stdName);
printf("Course & Year : ");
scanf("%c", &temp);
scanf("%[^\n]", PushNode->CnY);
printf("GWA : ");
scanf("%f", &PushNode->gwa);
printf("\n(ALERT) Add another node [Y/N]? ");
scanf(" %c", &resp);
if (resp == 'Y' || resp == 'y')
{
printf("\n");
PushNode = malloc(sizeof(struct node));
PushNode->link = TOP;
TOP = PushNode;
}
} while (resp == 'Y' || resp == 'y');
PushNode = NULL;
stackCreated = true;
main();
}
else
{
char choice;
printf("(ALERT) The stack already created!\n");
printf("Do you want to create a stack? [Y/N]: ");
scanf(" %c", &choice);
(choice == 'Y' || choice == 'y') ? (stackCreated = false, createStck()) : (printf("\n(ALERT) You will now be redirected to the main menu!"), sleep(2), main());
}
}
void traverseStck()
{
system("CLS");
ptr = TOP;
if (ptr == NULL)
{
printf("(ALERT) The Stack is empty!, please create a stack before traversing");
sleep(2);
main();
}
else
{
do
{
printf("Student Number : %s\n", ptr->stdNum);
printf("Student Number : %s\n", ptr->stdName);
printf("Course and Year : %s\n", ptr->CnY);
printf("GWA : %f\n\n", ptr->gwa);
ptr = ptr->link;
} while (ptr != NULL);
printf("(ALERT) Press any key to continue...");
getch();
main();
}
}
void addStck()
{
system("CLS");
if (TOP == NULL)
{
char choice;
printf("(ALERT) The stack is empty\n");
printf("Do you want to create a stack? [Y/N]: ");
scanf(" %c", &choice);
(choice == 'Y' || choice == 'y') ? createStck() : (printf("\n(ALERT) You will now be redirected to the main menu!"), sleep(2), main());
}
else
{
struct node *addNode = NULL;
addNode = malloc(sizeof(struct node));
char temp;
printf("Student Number : ");
scanf("%s", &addNode->stdNum);
printf("Student Name : ");
scanf("%c", &temp);
scanf("%[^\n]", addNode->stdName);
printf("Course & Year : ");
scanf("%c", &temp);
scanf("%[^\n]", addNode->CnY);
printf("GWA : ");
scanf("%f", &addNode->gwa);
addNode->link = TOP;
TOP = addNode;
addNode = NULL;
printf("\n(SUCCESS) New Node added on the top of the stack!");
sleep(2);
main();
}
}
void delStck()
{
system("CLS");
if (TOP == NULL)
{
printf("(ALERT) The Stack is empty!, cannot delete if stack does not exist!\n");
}
else if (TOP->link == NULL)
{
TOP = NULL;
printf("(SUCCESS) The stack has been deleted!");
stackCreated = false;
}
else
{
ptr = TOP;
ptr = ptr->link;
TOP = ptr;
ptr = NULL;
printf("(SUCCESS) The top stack has been deleted!");
}
sleep(2);
main();
}
void endProg()
{
system("CLS");
printf("Thank you for using my program - Ace :)");
sleep(2);
exit(1);
}
node * del(node * start,int loc)
{
int l=len(start);
if(loc<1 || loc>l)
{
printf("Deletion not possible. \n");
}
else
{
if(loc==1)
{
node *p;
p=start;
start=start->next;
free(p);
}
else
{
node *p,*q;
p=start;
for(int i=1;i<=loc-1;i++)//check this one.
{
q=p;
p=p->next;
}
q->next=p->next;
free(p);
}
printf("Deletion completed!\n");
}
return start;
}
This is the function and I am calling it from main() as:
case 5:
printf("Enter the node you want to delete. \n");
scanf("%d",temp);
start=del(start,temp);
break;
While deleting any node I am getting segmentation fault!I am stuck at this .
Can anyone help?
here is the full program:-
#include<stdio.h>
#include<stdbool.h>
#include<stdlib.h>
struct Node
{
int data;
struct Node * next;
};
typedef struct Node node;
int len(node * start)
{
if(start==NULL)
return 0;
int c=1;
while(start!=NULL)
{
start=start->next;
c++;
}
return c;
}
node * insert(node* start,int loc,int d)
{
int l=len(start);
node * p=start;
node * temp=(node*)malloc(sizeof(node));
if(loc<1 || loc>l+1)
{
printf("Insertion not posible.!\n");
return start;
}
if(l==0 || loc==1)
{
temp->next=start;
start=temp;
temp->data=d;
printf("Insertion completed.\n");
}
else
{
for(int i=1;i<=loc-2;i++)
p=p->next;
temp->next=p->next;
p->next=temp;
temp->data=d;
printf("Insertion completed. \n");
}
return start;
}
void show(node *start)
{
int l=len(start);
if(l==0)
{
printf("Nothing to print. \n");
}
else
{
for(int i=1;i<l-1;i++)
{
printf(" %d -> ",start->data);
start=start->next;
}
printf(" %d \n",start->data);
}
}
node * destroy(node * start)
{
node * p=start;
while(start!=NULL)
{
start=start->next;
free(p);
p=start;
}
printf("Destroy of linked list completed! .\n");
return NULL;
}
node * del(node * start,int loc)
{
int l=len(start);
if(loc<1 || loc>l)
{
printf("Deletion not possible. \n");
}
else
{
if(loc==1)
{
node *p;
p=start;
start=start->next;
free(p);
}
else
{
node *p,*q;
p=start;
for(int i=1;i<=loc-1;i++)//check this one.
{
q=p;
p=p->next;
}
q->next=p->next;
free(p);
}
printf("Deletion completed!\n");
}
return start;
}
int main()
{
node * start=NULL;
int ch,temp,d;
ch=temp=d=0;
while(ch != -1)
{
switch(ch)
{
case 0:
printf("Enter 0 to show menu.\n");
printf("Enter 1 to create linked list.\n");
printf("Enter 2 to destroy linked list.\n");
printf("Enter 3 to get the length of likned list.\n");
printf("Enter 4 to insert element in the linked list.\n");
printf("Enter 5 to delete element from the linked list.\n");
printf("Enter 6 to view the linked list.\n");
printf("Enter 7 to reverse a linked list.\n");
break;
case 1:
printf("Enter the size of link list to begin with.\n");
scanf("%d",&temp);
for(int i=1;i<=temp;i++)
{
printf("Enter the data to bes inserted to node %d .\n",i);
scanf("%d",&d);
start=insert(start,i,d);
}
break;
case 2:
start=destroy(start);
break;
case 3:
printf("Size of linked list is: %d \n",len(start));
break;
case 4:
printf("Enter the location where you want to insert the data.\n");
scanf("%d",&temp);
printf("Enter the data to be intered.\n");
scanf("%d",&d);
start=insert(start,temp,d);
break;
case 5:
printf("Enter the node you want to delete. \n");
scanf("%d",temp);
start=del(start,temp);
break;
case 6:
show(start);
break;
default:
ch=0;
break;
}
printf("\nEnter your choice? \n");
scanf("%d",&ch);
}
destroy(start);
}
Change:
case 5:
printf("Enter the node you want to delete. \n");
scanf("%d",temp);
start=del(start,temp);
break;
line scanf("%d",temp); to scanf("%d",&temp);
I want to do a search function for this program at void search(void);.
In this function, the user will enter the information at void arrive(void);.
After that, I going to scan the char that user typed, which is bus_num[20], and the program is going to show the bus_type and capacity. Can somebody teach me how to do this ?
#include<conio.h>
#include<stdio.h>
#include<malloc.h>
void arrive(void);
void leave(void);
void search(void);
void print(void);
void length(void);
int count;
struct bus{
char bus_num[20];
char bus_type[20];
int capacity;
struct bus *next;
}*ptr, *temp, *front, *rear;
void main()
{
temp = NULL;
rear = NULL;
front = NULL;
int option = 0;
while (option != 6)
{
printf("\n\n*****menu driven*****\n");
printf("\n\t 1.Arrive");
printf("\n\t 2.Leave");
printf("\n\t 3.Search");
printf("\n\t 4.Print");
printf("\n\t 5.Length");
printf("\n\t 6.Exit");
printf("\n\nSelect a option\n");
scanf("%d", &option);
switch (option)
{
case 1: arrive();break;
case 2:leave();break;
case 3:search();break;
case 4:print();break;
case 5:length();break;
case 6:break;
default: printf("\nInvalid Option\n");
}
getch();
}
getch();
}
void arrive(void)
{
temp = (struct bus*)malloc(1 * sizeof(struct bus));
printf("\nPlease Enter The Bus Registeration Number :");
fflush(stdin);
scanf("%s", &temp->bus_num);
printf("\nPlease Enter The Bus Type :");
fflush(stdin);
scanf("%s", &temp->bus_type);
printf("\nPlease Enter The Bus Capacity :");
fflush(stdin);
scanf("%d", &temp->capacity);
count++;
temp->next = NULL;
if (front == NULL && rear == NULL)
{
front = rear = temp;
return;
}
rear->next = temp;
rear = rear->next;
}
void leave(void)
{
if (front == NULL)
{
printf("\nThere are empty queue\n");
return;
}
if (front == rear&&front != NULL)
{
ptr = front;
printf("%s leaves the queue", &ptr->bus_num);
front = rear = NULL;
free(ptr);
}
else
{
ptr = front;
printf("%s leaves", &ptr->bus_num);
front = front->next;
free(ptr);
}
count--;
}
void print(void)
{
if (front == NULL&&rear == NULL)
{
printf("\nThere are no any Queue\n");
return;
}
ptr = front;
while (ptr != NULL)
{
printf("%s\t", ptr->bus_num);
ptr = ptr->next;
}
}
void length(void)
{
printf("\n Queue size is %d", count);
}
void search(void)
{
}
I have created a program to implement a Circular Queue with insert, delete and display. The insertion is working fine and the deletion too but once I try to enter numbers after deletion, nothing is displayed. Here is my source code:
#include<stdio.h>
#include<conio.h>
#define SIZE 5
int front = -1;
int rear = -1;
int queue[SIZE];
void enqueue(int item);
int dequeue();
void display();
void main()
{
int item, choice, cont = 1;
clrscr();
while(cont == 1)
{
printf("\n1.Enqueue into queue.\n");
printf("\n2.Dequeue from queue.\n");
printf("\n3.display quesue elements\n");
printf("\nEnter your choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nEnter the value of item: ");
scanf("%d",&item);
enqueue(item);
break;
case 2:
item = dequeue();
if(item != NULL)
{
printf("\nItem dequeued: %d\n",item);
}
break;
case 3:
display();
break;
default:
printf("\nInvalid choice.\n");
break;
}
printf("\nDo you want to continue (1/0): ");
scanf("%d",&cont);
}
getch();
}
void enqueue(int item)
{
if(front==0 && rear==SIZE-1)
printf("\n Queue OverFlow Occured");
else if(front==-1 && rear==-1)
{
front=rear=0;
queue[rear]=item;
}
else if(rear==SIZE-1 && front!=0)
{
rear=0;
queue[rear]=item;
}
else
{
rear++;
queue[rear]=item;
}
}
int dequeue()
{
int item = NULL;
if(front == -1 && rear == -1)
{
printf("\nQueue is empty. Dequeue not possible.\n");
}
else
{
item = queue[front];
queue[front] = NULL;
if(front == rear)
{
front = -1;
rear = -1;
}
else
{
front = front + 1;
}
}
return(item);
}
void display()
{
int i;
if(front==-1)
printf("\n No elements to display");
else
{
printf("\n The queue elements are:\n ");
for(i=front;i<=rear;i++)
{
printf("\t %d",queue[i]);
}
}
}
Check this code its working fine.
Few suggestions don't use conio.h [clrscr(), and getch()] these are not standards.
Try the code below it worked for me fine.
CODE
#include<stdio.h>
#define SIZE 5
int front = -1;
int rear = -1;
int queue[SIZE];
void enqueue(int item);
int dequeue();
void display();
int main()
{
int item, choice, cont = 1;
while(cont == 1)
{
printf("\n1.Enqueue into queue.\n");
printf("\n2.Dequeue from queue.\n");
printf("\n3.display quesue elements\n");
printf("\nEnter your choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nEnter the value of item: ");
scanf("%d",&item);
enqueue(item);
break;
case 2:
item = dequeue();
if(item != NULL)
{
printf("\nItem dequeued: %d\n",item);
}
break;
case 3:
display();
break;
default:
printf("\nInvalid choice.\n");
break;
}
printf("\nDo you want to continue (1/0): ");
scanf("%d",&cont);
}
printf("");
return 0;
}
void enqueue(int item)
{
if(front==0 && rear==SIZE-1)
printf("\n Queue OverFlow Occured");
else if(front==-1 && rear==-1)
{
front=rear=0;
queue[rear]=item;
}
else if(rear==SIZE-1 && front!=0)
{
rear=0;
queue[rear]=item;
}
else
{
rear++;
queue[rear]=item;
}
}
int dequeue()
{
int item = NULL;
if(front == -1 && rear == -1)
{
printf("\nQueue is empty. Dequeue not possible.\n");
}
else
{
item = queue[front];
queue[front] = NULL;
if(front == rear)
{
front = -1;
rear = -1;
}
else
{
front = front + 1;
}
}
return(item);
}
void display()
{
int i;
if(front==-1)
printf("\n No elements to display");
else
{
printf("\n The queue elements are:\n ");
for(i=front;i<=rear;i++)
{
printf("\t %d",queue[i]);
}
}
}
OUTPUT
Do you want to continue (1/0): 1
1.Enqueue into queue.
2.Dequeue from queue.
3.display quesue elements
Enter your choice: 3
The queue elements are:
5 5
Do you want to continue (1/0): 1
1.Enqueue into queue.
2.Dequeue from queue.
3.display quesue elements
Enter your choice: 1
Enter the value of item: 43
Do you want to continue (1/0): 1
1.Enqueue into queue.
2.Dequeue from queue.
3.display quesue elements
Enter your choice: 3
The queue elements are:
5 5 43
Do you want to continue (1/0): 1
1.Enqueue into queue.
2.Dequeue from queue.
3.display quesue elements
Enter your choice: 2
Item dequeued: 5
Do you want to continue (1/0): 1
1.Enqueue into queue.
2.Dequeue from queue.
3.display quesue elements
Enter your choice: 3
The queue elements are:
5 43
Do you want to continue (1/0):
Thats a rather confusing code. Since the idea is for the queue to be circular, trying to determine if the queue is full by checking the position of front and rear can be really tricky, aswell as trying to make decisions based on front being higher than rear etc. You can avoid all that. A third variable keeping track of the length of the queue will make your life a whole lot easier.
Try this implementation instead:
#define SIZE 5
int queue[SIZE];
int read = 0, write = 0, size = 0;
void enqueue(int item)
{
if (size >= SIZE)
{
printf("Queue is full");
return;
}
queue[write] = item;
write = (write + 1) % SIZE;
size++;
}
int dequeue()
{
if (size == 0)
{
printf("Queue is empty");
return 0;
}
read %= SIZE;
size--;
return queue[read++];
}
Here is your Fully Functional updated code. I pasted code on Ideone.com Link is link to code
If you don't understand anything just ask. I tried to explain it using comments. And now it is not having any problem that you were facing .
#include<stdio.h>
#include<conio.h>
#define SIZE 5
int front = -1;
int rear = -1;
int queue[SIZE];
void enqueue(int item);
int dequeue();
void display();
void main()
{
int item, choice, cont = 1;
clrscr();
while(cont == 1)
{
printf("\n1.Enqueue into queue.\n");
printf("\n2.Dequeue from queue.\n");
printf("\n3.display quesue elements\n");
printf("\nEnter your choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nEnter the value of item: ");
scanf("%d",&item);
enqueue(item);
break;
case 2:
item = dequeue();
if(item != NULL)
{
printf("\nItem dequeued: %d\n",item);
}
break;
case 3:
display();
break;
default:
printf("\nInvalid choice.\n");
break;
}
printf("\nDo you want to continue (1/0): ");
scanf("%d",&cont);
}
getch();
}
void enqueue(int item)
{
int temp = (rear+1)%SIZE; //EDIT HERE
if(temp == front){
printf("\n Queue OverFlow Occured");
return;
}
else if(front==-1 )
{
front=rear=0;
queue[rear]=item;
return;
}
else{
rear = (rear+1)%SIZE; // EDIT HERE
queue[rear%SIZE]=item;
}
}
int dequeue()
{
int item = NULL;
if(front == rear) // modified condition
{
printf("\nQueue is empty. Dequeue not possible.\n");
}
else
{
item = queue[front];
queue[front] = NULL;
front++; // front must be incremented
if(front > rear)
{
front = -1;
rear = -1;
}
}
return(item);
}
void display()
{
int i;
if(front==-1)
printf("\n No elements to display");
else
{
printf("\n The queue elements are:\n ");
for(i=front;i<=rear;i++)
{
printf("%d\t",queue[i]);
}
}
}