Queue using Circular Array using C
A circular queue is a data structure which connects the last index with the first element. This makes the queue to be handled in efficient manner.
The elements of the queue are given below….
- · Front: It is the index of front element.
- · Rear: It is the index of last element.
- · Count: it finds the queue is full or empty.
- · The array size is fixed(a_Size).
·
Member functions:
- · Enqueue(),dequeue(),print_queue()
Program:
#include <stdio.h>
#define a_Size 5
void enqueue(int queue1[], int *q_rear, int *q_front, int
value) {
if ((*q_rear + 1)
% a_Size == *q_front) {
printf("The Queue is Full\n");
return;
}
if (*q_front ==
-1) *q_front = 0;
*q_rear = (*q_rear
+ 1) % a_Size;
queue1[*q_rear] =
value;
}
if (*q_front ==
-1) {
printf("The Queue is Empty\n");
return;
}
printf("The
element is Deleted: %d\n", queue1[*q_front]);
if (*q_front ==
*q_rear) {
*q_front = -1;
*q_rear = -1;
} else {
*q_front =
(*q_front + 1) % a_Size;
}
}
void print_queue(int queue1[], int q_front, int q_rear) {
if (q_front == -1)
{
printf("The Queue is Empty\n");
return;
}
int i = q_front;
printf("The
Queue elements are: ");
while (i !=
q_rear) {
printf("%d ", queue1[i]);
i = (i + 1) %
a_Size;
}
printf("%d\n", queue1[q_rear]);
}
int
queue1[a_Size];
int q_front = -1,
q_rear = -1;
int ch, value;
printf("\n1. Enqueue\n2. Dequeue\n3. Display\n4. Exit\nEnter your
choice: ");
scanf("%d", &ch);
switch (ch) {
case 1:
printf("Enter the value to perform enqueue: ");
scanf("%d", &value);
enqueue(queue1, &q_rear, &q_front, value);
break;
case 2:
dequeue(queue1, &q_rear, &q_front);
break;
case 3:
print_queue(queue1, q_front, q_rear);
break;
case 4:
return 0;
default:
printf("Choice is invalid. Try again.\n");
}
}
}
Output:
1. Enqueue
2. Dequeue
3. Display
4. Exit
Enter your choice: 1
Enter the value to perform enqueue: 34
1. Enqueue
2. Dequeue
3. Display
4. Exit
Enter your choice: 3
The Queue elements are: 34
1. Enqueue
2. Dequeue
3. Display
4. Exit
Enter your choice: 1
Enter the value to perform enqueue: 45
1. Enqueue
2. Dequeue
3. Display
4. Exit
Enter your choice: 1
Enter the value to perform enqueue: 56
1. Enqueue
2. Dequeue
3. Display
4. Exit
Enter your choice: 1
Enter the value to perform enqueue: 78
1. Enqueue
2. Dequeue
3. Display
4. Exit
Enter your choice: 3
The Queue elements are: 34 45 56 78
1. Enqueue
2. Dequeue
3. Display
4. Exit
Enter your choice:
2
The element is Deleted: 34
1. Enqueue
2. Dequeue
3. Display
4. Exit
Enter your choice: 3
The Queue elements are: 45 56 78
1. Enqueue
2. Dequeue
3. Display
4. Exit
Enter your choice: 4
Yes. The Code Execution Successful. Let you try it in your
editor. Hope , this code is useful to you. Happy Coding!!!
Comments
Post a Comment