Solution to Queue Exercise

Implementation using flowgorithm

Download the file here: https://drive.google.com/file/d/1adiH9SG9vbXVNBydWC5tKR1_9i9y9ZPj/view?usp=sharing

Coded Implementation in C

Code is split into 3 files:

main.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char userInput[5];
    int data = -9999;



    puts("\nEnter a valid command: add, remove, peek , exit\n");
    scanf("%s", userInput);
    while(strcmp("exit",userInput)!=0)
    {
        if (strcmp("add",userInput)==0)
        {
            puts("\nEnter data to add to the end of the queue\n");
            scanf("%d", &data);
            enqueue(data);
        }
        else if (strcmp("remove",userInput)==0)
        {
            data = dequeue();
            printf("\nremoved %d from the front of the queue\n",data);
        }
        else if (strcmp("peek",userInput)==0)
        {
            data = peek();
            printf("\npeeking at front : %d\n",data);
        }
        else
        {
            puts("\nInvalid command entered. Ensure that your command is in lowercase\n");
        }

        puts("\nEnter a valid command: add, remove, peek , exit\n");
        scanf("%s", userInput);
    }
    puts("\nExiting Program...\n");



    return 0;
}

Queue.h

#include <stdio.h>
#ifndef QUEUE_H_INCLUDED
#define QUEUE_H_INCLUDED

void enqueue(int newData);
int dequeue();
int peek();



#endif // QUEUE_H_INCLUDED

Queue.c

#define MAX_SIZE 5

int sizeOfQueue = 0;
int head = 0;
int tail = -1;

int queueData[MAX_SIZE];



void enqueue(int newData)
{
    if (sizeOfQueue==MAX_SIZE)
        puts("Error in \"void enqueue(int newData)\". Queue is full" );
    else
    {
        queueData[++tail]= newData;
        sizeOfQueue++;
    }


}

int dequeue()
{
    int result=-999;
    if (sizeOfQueue==0)
        puts("error in \"int dequeue()\". Queue is empty, -999 returned");
    else
    {
        result=queueData[head++];
        sizeOfQueue--;
    }
    return result;

}

int peek()
{
    int result=-999;
    if (sizeOfQueue==0)
        puts("error in \"int peek()\". Queue is empty, -999 returned");
    else
        result=queueData[head];


    return result;

}


© 2020  Vedesh Kungebeharry. All rights reserved. 

Leave a comment