Thursday, 12 September 2013

Elements are not being inserted in different positions in the queue and value is not showing correctly

Elements are not being inserted in different positions in the queue and
value is not showing correctly

Here is my en_queue function for insertion of new elements in different
conditions.
void en_queue(int *queue,int max,int front,int rear)
{
int ch1;
printf("\n Enter element to add->");
scanf("%d",&ch1);
if(front==0 && rear==(max-1))
{
printf("\n Caution!! Queue Overflow!!");
}
else if(rear==(max-1) && front>0)
{
rear=0;
queue[rear]=ch1;
printf("\n %d added to the queue where front fo the queue has room
but rear does not" ,ch1);
}
else if(front==-1 && rear==-1)
{
front=rear=0;
queue[rear]=ch1;
printf("\n %d added to the queue where this is the first element
to the queue" ,ch1);
}
else
{
rear++;
queue[rear]=ch1;
printf("\n %d added to the queue where the element added in the
rear" ,ch1);
}
}
and here is my show_queue function.
void show_queue(int *newqueue,int front,int rear)
{
int i=0;
for(i=front;i<=rear;i++)
{
printf("%d",newqueue[i]);
}
}
By the print statements, I examine that always the elements are being
inserted into the first position. So, my best guess is the rear and front
elements are not getting updated successfully but I am unable to find why.
Also, I should have seen the correctly inserted first value at least by
the show_queue function; instead, I am seeing garbage values but the
values are constant viz. 4235968 everytime.
UPDATE- Here is the main function as requested.
#include<stdio.h>
#include<stdlib.h>
#define MAX 10
void en_queue(int *,int, int, int);
void show_queue(int *,int,int);
int main()
{
int queue[MAX],front=-1,rear=-1,ch;
do{
printf("\n <<Queue MENU>>");
printf("\n 1. Add Element");
printf("\n 2. Delete Element");
printf("\n 3. Show Queue");
printf("\n 4. Exit menu");
printf("\n Enter your choice->");
scanf("%d", &ch);
switch(ch)
{
case 1: en_queue(queue,MAX,front,rear);
break;
/* case 2: del_queue(queue,MAX,front,rear);
break;*/
case 3: printf("\n The queue is->");
show_queue(queue,front,rear);
break;
case 4:exit(0);
default: printf("\n Invalid Choice!!!");
return 0;
}
}while(ch!=4);
return 0;
}

No comments:

Post a Comment