Top Menu

WELCOME TO COMSATSBLOG ...............
THIS BLOG IS SPECIALLY FOR STUDENTS OF COMSATS ABBOTTABAD WHICH WILL CONTAIN NOTES ,TEXT BOOKS,SOLUTIONS AND MINI PROJECTS TO THE ENGINEERING PROGRAMS WHICH ARE VERY USEFUL FOR YOU ...........
SO FOLLOW THIS BLOG AND IF YOU HAVE ANY INFORMATION OR STUDY MATERIAL RELATED TO ENGINEERING PROGRAMS THEN SEND IT TO ME ON SulemanSunShine@gmail.com
DON'T FORGET TO REGISTER YOURSELF ON THIS BLOG JUST CLICK ON ''JOIN THIS SITE''....
THANKS.........

Monday, October 28, 2013

Program to implement a Queue using Array with front always at zero

/*Implementation of queues using arrays*/
/*Queue implementation with front always at zero*/
#include <iostream.h>
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

#define MAX 10

typedef struct queue
{int front, rear;
int arr[MAX];
}queue;

/*Enqueue will increment rear by one and add new element
at this subscript*/

void enqueue(queue *q, int x)
{if(q->rear==MAX-1)
{cout<<"Queue Overflow!";
exit(1);
}
q->arr[++q->rear]=x;
}

/*Front is always kept at zero.
Deletion involves shifting of elements to the left by one
position and rear gets decremented by one*/

int dequeue(queue *q)
{
int i,no;
if(q->rear<q->front)
{cout<<"Queue Underflow!";
exit(1);
}
no=q->arr[q->front];
/*fixed front at zero results in shifting of elements*/
for(i=q->front;i<q->rear;i++)
q->arr[i]=q->arr[i+1];
q->arr[q->rear]=0;
q->rear--;
return no;
}

void display(queue *q)
{int i;
for(i=q->front;i<=q->rear;i++)
cout<<q->arr[i];
}

void main()
{
int ch,num;
queue q;
q.front=0;
q.rear=-1;
while(1)
{
clrscr();
cout<<"\nMenu";
cout<<"\n1. Enqueue";
cout<<"\n2. Dequeue";
cout<<"\n3. Display";
cout<<"\n4. Exit";
cout<<"\nEnter your choice?";
cin>>ch;
switch(ch)
{
case 1:
cout<<"\nEnter number?";
cin>>num;
enqueue(&q,num);
break;
case 2:
num=dequeue(&q);
cout<<"\nElement removed from the queue is "<<num;
break;
case 3:
display(&q);
break;
case 4:
exit(0);
default:
cout<<"\nInvalid choice!";
}
getch();
}
}

No comments:

Post a Comment