facebook like button

10 August, 2011

Program 72: Queue implementation on array

The need:
    To show how queue concept can be implemented on an array in the simplest way possible.
The code:
-----------------------------------------------------------

/*
This is a program showing the queue implimentation on integer array
We can have array implementation on array of any datatype including derived datatypes
This program does not include any user defined function
In this front and rear are taken as array indices
program writtem by RP Singh
compiled and tested on C-free4.0 standard
*/

#define MAX 10
#include<stdio.h>
#include<stdlib.h>

int main()
{
    int i=0,arr[MAX];
    char c='y';
    int front=0,rear=-1,current_item;        //I follow the convention of takingthese values of front and rear when queue is empty
    printf("Enter 3 items into queue\n");
    while(c=='y'||c=='Y')
    {
        printf("\nEnter integer %d\t=>\t",++i);
        scanf("%d",&current_item);                    //this is the value taken from user
        if(rear==MAX-1)
        printf("cannot enqueue because the array end has been reached.\n");
        else
        arr[++rear]=current_item;                    //enqueing an item
        printf("item %d inserted into queue successfully\n\n",current_item);
        printf("Enter press y to enqueue more items. else press any other key.\n");
        fflush(stdin);
        c=getchar();
    }
    printf("all items successfully entered into queue\n");
    printf("value of front = %d\t rear = %d\n",front,rear);
    printf("length of queue is %d\n",rear-front+1);
    printf("\n\npress any key to dequeue and see all values you entered\n");
    fflush(stdin);
    getchar();
    printf("all items you entered are listed below\n");
    while(front<=rear)
    {
        printf("%d\n",arr[front++]);                    //dequeing an item
    }
    return 0;
}

-----------------------------------------------------------
Remarks:
This is a simple program showing implementation of queue concept on array. For simplicity I have taken a simple integer array. I also have not used any UDFs here. I just wanted to show that queue is an abstract entity, we dont even need enqueue and dequeue to implement that on simplest level. The only thing to remember is the concept of queue.

No comments:

Post a Comment

feel free to ask your doubts... if any
you can post your doubts on
www.facebook.com/programsimply