Answer to Question #137052 in C for AJAY KUMAR

Question #137052
Write a program to implement Queue and its operation (like create, insert, delete,
search) using array data structure.
1
Expert's answer
2020-10-06T23:36:15-0400
#include <stdio.h>
#include<stdlib.h>

#define MAX 50

void insert();

void delete();

void display();

void Search();

int queue_array[MAX];
int rear = -1;
int front = -1;

int main() {
    int choice;
    while (1) {
        printf("\n----------MENU------------\n");
        printf("1.Insert element to queue \n");
        printf("2.Delete element from queue \n");
        printf("3.Display all elements of queue \n");
        printf("4.Search element in queue \n");
        printf("5.Quit \n");
        printf("Enter your choice : ");
        scanf("%d", &choice);
        switch (choice) {
            case 1:
                insert();
                break;
            case 2:
                delete();
                break;
            case 3:
                display();
                break;
            case 4:
                Search();
                break;
            case 5:
                printf("You exit the program");
                exit(0);
            default:
                printf("Wrong choice \n");
        }
    }
}

void insert() {
    int add_item;
    if (rear == MAX - 1)
        printf("Queue Overflow \n");
    else {
        if (front == -1)
            /*If queue is initially empty */
            front = 0;
        printf("Inset the element in queue : ");
        scanf("%d", &add_item);
        rear = rear + 1;
        queue_array[rear] = add_item;
    }
}

void delete() {
    if (front == -1 || front > rear) {
        printf("Queue Underflow \n");
        return;
    } else {
        printf("Element deleted from queue is : %d\n\n", queue_array[front]);
        front = front + 1;
    }
}

void display() {
    int i;
    if (front == -1)
        printf("Queue is empty \n");
    else {
        printf("Queue is : \n");
        for (i = front; i <= rear; i++)
            printf("%d ", queue_array[i]);
        printf("\n");
    }
}

void Search() {

    int found = 0, i = 0, item, position;
    printf("Enter element to search: ");
    scanf("%d", &item);
    for (i = front; i <= rear; i++) {

        if (queue_array[i] == item) {
            found = 1;
            position = i;
            break;
        }
    }

    if (found == 1) {
        printf("Element %d is found in the queue on position %d\n\n ", item, position);
    } else {
        printf("\nElement %d is not found in the queue\n\n", item);
    }

}

Output:




Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS