0

I am having problem in the c implementation of circular queue. The enqueue operation is not working properly. The value is not getting initialised in the array.

the structure for queue is:

typedef struct
{   
    int a[5];
    int tail;
    int head;
    int cap;
 }Que;

the enqueue function:

    int enque(Que *q,int num) 
 {
    if((q->head)==(q->tail ))
        return -1;
    if(q->head==-1)
        q->head=0;
    q->a[q->tail]=num;
    (q->tail) ++;
    if(q->tail ==q->cap)
    q->tail=0;
    return 0;
}

the dequeue function:

    int deque(Que *q)
{
    if((q->head)==-1)
     return -1;

    int b= q->a[q->head];
    (q->head)++;
    if(q->head==q->cap)
        q->head=0;
    if(q->head==q->tail)
        q->head=-1;

    return b;
}

the head is position of the index to be dequeued and tail is the index where the element has to be added. The initial values of head is -1 , tail is 0 and cap is 5. These values have been set by another function.

@Klas Lindbäck Here is the complete code:

#include <stdlib.h>
#include <stdio.h>
typedef struct
{   
int a[5];
    int tail;
    int head;
    int cap;
}Que;
int deque(Que *q)
{
    if((q->head)==-1)
     return -1;

    int b= q->a[q->head];
    (q->head)++;
    if(q->head==q->cap)
        q->head=0;
    if(q->head==q->tail)
        q->head=-1;

    return b;
}
void initialize(Que *q)
{
    q->head=-1;
    q->tail=0;
    q->cap=5;
}
int enque(Que *q,int num) 
{
    if((q->head)==(q->tail ))
        return -1;
    if(q->head==-1)
        q->head=0;
    q->a[q->tail]=num;
    printf("%d \n",q->a[q->tail]);
    (q->tail) ++;
    if(q->tail ==q->cap)
    q->tail=0;
    return 0;
}
int main()
{
    Que q;
    initialize(&q);
    int i=1;
    for(;i<=5;i++)
    {
        int num;
        printf("input a number: ");
        scanf("%d",num);
        enque(&q,num);
    }
    int c=q.a[0];
    printf("%d  %d  %d\n",q.a[2],c,q.a[3]);

}

1 Answer 1

1

I cannot find anything wrong in your enque/deque functions. The problem lies elsewhere.

I tested your code with the following main:

int main(int argc, char**argv) {
  int var = 7456;
  Que q;
  q.head=-1; q.tail=0; q.cap=5;

  enque(&q, 12);
  enque(&q, 6);
  printf("First queue value =%d\n", deque(&q));
  return 0;
}

and the output was

First queue value =12

Edit:

Error is here:

    scanf("%d",num);

Change it to:

    scanf("%d", &num);
Sign up to request clarification or add additional context in comments.

1 Comment

Problem found. See Edit in my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.