Tuesday, April 7, 2015

[Data Structures - C] Circular Queue with Array in C Language

It is "Queue" with Array in C Programming language.
There are some functions get, put, printQue. They are important things.


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

int *Queue;
int max = 0;
int front,rear;
int command=0;
int data;
bool isFull = false;

void initQue(void);
void put(int);
bool get(int *data);
void printQue();

int main(int argc, const char * argv[]) {
    initQue();
    while(true) {
        printf("Que Program\n");
        printf("1. Put data\n");
        printf("2. Get data\n");
        printf("3. Print Que\n");
        printf("4. Exit Que\n");
        printf("Select your command : ");
        scanf("%d",&command);
        getchar();
        
        switch (command) {
            case 1:
                if (!isFull) {
                    printf("Enter data what you want to put :");
                    scanf("%d",&command);
                    getchar();
                    put(command);
                } else {
                    printf("Que is full. Please do get at least once");
                }
                break;
            case 2:
                if(get(&data)) {
                    printf("Getting data is %d\n",data);
                } else {
                    printf("Que is empty\n");
                }
                break;
            case 3:
                printQue();
                break;
            case 4:
                exit(0);
            default:
                break;
        }
        
    }
    return 0;
}

void initQue(void) {
    printf("Please enter volume of Que : ");
    scanf("%d",&max);
    getchar();
    Queue = (int *)malloc(sizeof(int)*max);
    front = 0;
    rear = 0;
    printf("Que is created with %d volume\n",max);
}

void put(int data) {
    if(!isFull) {
        Queue[rear++] = data;
    }
    
    if(rear>=max) {
        rear = 0;
    }
    
    if(front==rear) {
        isFull = true;
    }
    
}

bool get(int *data) {
    if(front==rear&&!isFull) {
        return false;
    }
    *data = Queue[front++];
    if(front>=max) {
        front=0;
    }
    isFull = false;
    return true;
}

void printQue() {
    int tempFront = front;
    
    printf("Front -> ");
    
    if (front==rear&&!isFull) {
        printf("Que is Empty.");
        return;
    }
    
    do {
        printf("%d -> ",Queue[tempFront++]);
        if(tempFront>=max) {
            tempFront = 0;
        }
    } while(tempFront!=rear);
        
    printf("Rear\n");
}


No comments:

Post a Comment