I have undergone a situation where i have to implement a queue type data structure.It is like this:
(1) Suppose there is an array data[50]= {1,2,3,4,5,6};
(2) int Front must point to first index and int rear must point must point to last index.
(3)Now i have to add first and second element of this array. Suppose i do that (i+2=3) and this 3 will be set at last by doing rear+1 (data[rear+1]), Now when the second execution occurs, We don't have to take into account the first two element (they already added), So in this case we can do data[front+2]. But pay attention here please, because this +2 is going to be done first time only , after this it will be just +1 (because we added only one element, and first time we add 2 element).And the element obtained on addition must go to last of the index like "3" obtained will go at last like this {1,2,3,4,5,6,3}.
(4)So we have to take into account
(4.a) Increment of Rear by one on each addition.
(4.b) Increment of Front by one (accept the first addition where we add two elements).
(5) My idea to do this is as follows:
#include <stdio.h>
#define MAX 50
int data[MAX];
int rear = - 1;
int front = - 1;
void main()
{
int rear=6, front=0;
data[size]={1,2,3,4,5,6};
int count=size;
//First do addition of the first two elements
data[rear]= data[0]+data[1];
for(i=front; i<size*2-1 ; i++) //we are doing data*2-1 because we know the final obtained on doing all the addition until there is 1 element will have the size (size*2-1).
{
do
{
//here we do addition data[rear+1]=data[front]+data[rear];
// rear++;
count--;
}while (count>1);
}
for(i=0; i<size*2-1 ; i++)
{
printf("%d ", data[i]); //Now this must print "1,2,3,4,5,6,3,6,9,12,21" (addition of element at front and rear)
}
}
**My doubt is how to increase the Front by two first time addition and by increasing by one after first addition so that first will always point to the element to be added(increasing is not difficult , i have done that). Please help me for Front increment, Algorithm and code will be very grateful.
size, and there are multiple ways to address the problems of full-vs-empty detection in a circular buffer. Some of them here.