Experiment 4
Program 4a
Aim : To implement queues using Array using C-program .
Code :
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
struct node {
int data;
};
void Add(struct node arr[], int* rear, int data) {
if (*rear >= MAX_SIZE - 1) {
printf("\nQueue is full\n");
return;
}
arr[++(*rear)].data = data;
}
void deq(struct node arr[], int* front, int* rear) {
if (*front > *rear) {
printf("\nQueue is empty\n");
return;
}
printf("\nDequeued: %d\n", arr[(*front)++].data);
}
void display(struct node arr[], int front, int rear) {
if (front > rear) {
printf("\nQueue is empty\n");
return;
} else {
printf("\nThe queue elements are:\n");
for (int i = front; i <= rear; i++) {
printf("%d\n", arr[i].data);
}
printf("\n");
}
}
int main() {
struct node arr[MAX_SIZE];
int front = 0;
int rear = -1;
int ch = 0;
while (ch != 4) {
printf("\n1: Enqueue\n");
printf("2: Dequeue\n");
printf("3: Display Queue\n");
printf("4: Exit\n\n");
printf("Enter choice: ");
scanf("%d", &ch);
switch (ch) {
case 1:
{
int data;
printf("\nEnter the data: ");
scanf("%d", &data);
Add(arr, &rear, data);
}
break;
case 2:
deq(arr, &front, &rear);
break;
case 3:
display(arr, front, rear);
break;
}
}
return 0;
}
Output :
/tmp/8Ul12yLmWV.o
1: Enqueue
2: Dequeue
3: Display Queue
4: Exit
Enter choice: 1
Enter the data: 1
1: Enqueue
2: Dequeue
3: Display Queue
4: Exit
Enter choice: 1
Enter the data: 2
1: Enqueue
2: Dequeue
3: Display Queue
4: Exit
Enter choice: 1
Enter the data: 3
1: Enqueue
2: Dequeue
3: Display Queue
4: Exit
Enter choice: 2
Dequeued: 1
1: Enqueue
2: Dequeue
3: Display Queue
4: Exit
Enter choice: 3
The queue elements are:
2
3
1: Enqueue
2: Dequeue
3: Display Queue
4: Exit
Enter choice:
Result:
queues using Array using C-program are implemented.