Write a function intgetCount(QUEUE q) to count the number of elements in a circu
ID: 3890501 • Letter: W
Question
Write a function intgetCount(QUEUE q) to count the number of elements in a circular queue without using any looping statements. Initial value of front (F) and rear (R) is
zero. Each time after inserting an element into the queue the rear pointer points to the last element inserted. Front pointer always points to a location previous to the element to be deleted as shown in the figure below. Assume that neither Insert function nor the queue maintains the count information.
Trace the algorithm for the following cases
a. F-0 R-4 b. R=1 F=2Explanation / Answer
Function int getCount(QUEUE q) to count the number of elements in a circular queue without using any looping statements is given below:
int getCount(QUEUE q)
{
int count;
if(F==R)
{
count = 0;
}
else if(F<R)
{
count = R - F;
}
else if(F>R)
{
count = (MAX_SIZE - F - 1) + (R + 1);
}
return count;
}
Explanation : Here initial value of front (F) and rear (R) is zero and when the queue is empty F and R would have the same value. MAX_SIZE is the capacity of the circular queue i.e. the maximum number of elements that the circular queue can hold. The variable count will hold the number of elemens in the circular queue and it will be returned by the function.
The above said function for counting the number of elements in the circular queue is now applied for the given two cases.
For both the cases MAX_SIZE is 5.
Case a) Here F = 0, and R = 4. So F is not equals to R (so if block will not be executed), F is less than R ; hence the else if block for (F<R) would be executed here: count would be
count = R - F
= 4 – 0
=4
Next else if block for (F>R) also would not be executed here;
The count value will be returned by the function and the value is 4 now.
So the number of elements in this case will be 4.
Case b) Here F = 2, and R = 1. So F is not equals to R (so if block will not be executed), F is not less than R (hence the else if block for (F<R) will not be executed), F is greater than R; hence next else if block for (F>R) would be executed here; and count would be
count = (MAX_SIZE - F - 1) + (R + 1)
= (5 – 2 – 1) + (1 + 1)
= 2 + 2
= 4
The count value will be returned by the function and the value is 4 now.
So the number of elements in this case will be 4.
/*If this helps you, please let me know by giving a positive thumbs up. In case you have any queries, do let me know. I will revert back to you. Thank you!!*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.