Tuesday, June 8, 2010

Simple Queue in C using Fixed size array

1: #include <stdio.h>
2: 
3: //implementing a queue(fifo) structure
4: //using array with constant size
5: //not using dynamic memory
6: 
7: #define CAP 10
8: 
9: int enqueue(int *q,int *size,int data)
10: {
11:   if(*size == CAP)
12:     return 0;
13:     
14:   q[(*size)++] = data;
15:   return 1;
16: }
17: 
18: int dequeue(int *q, int *head)
19: {
20:   return q[(*head)++];
21: }
22: 
23: int main(int argc, char **argv)
24: {
25:   int arr[CAP];
26:   int head = 0;//starting index of the queue
27:   int size = 0;//size of the queue
28:   int i = 0;
29: 
30:   while(enqueue(arr,&size,i++));
31:   
32:   for(;;)
33:   {
34:     if (head == size)
35:       break;
36:     else  
37:       printf("element is %d \n",dequeue(arr,&head));
38:   }
39:   getchar();
40:   printf("hello world\n");
41:   return 0;
42: }
43: 

No comments: