Solved

# Enqueue in C (algorithm)

Posted on 2004-11-22
642 Views
I have the following algorithm:

if(queue->rear == queue-maxsize)
queue->rear = 0;
queue-queueAry[queue->rear] = itemPtr;

All that this is doing is checking to see if the queue is full and then inserting the item at the beginning of the queue if it is.  The thing is, I need to do this without using an if statement, any suggestions??

0
Question by:wiggs1006

LVL 45

Expert Comment

Hmmm....  You want to insert the item at the front of the queue if the queue is full?  Seems like a VERY strange thing to do...

However, you don't need an if() statement to insert an item to the front of a list.

Item = malloc (sizeof (Item_t));

Kent
0

LVL 2

Author Comment

The queue is not full it is just at the end and there is empty space in the front so that is where we need to insert the new item.  Without the if statement.  Does this make more sense?
0

LVL 3

Accepted Solution

You can use the modulus operator for this. E.g.:

queue->rear = (queue->rear + 1) % (queue->maxsize + 1);
queue->queueAry[queue->rear] = itemPtr;

thus queue->rear will never be greater than queue->maxsize
0

LVL 7

Expert Comment

Side note:

Please don't let yourself get used to solving problems without basic tools (such as the if statement). Real life problems are hardly ever solved this way; this is merely academic nonsense.
0

LVL 2

Author Comment

I am holding a lab for undergraduates and the teacher is having them come up with another way to do enqueue without the if statement.  I totally agree with you here, and it stumped me when they came to me with questions.  I did tell them that his seemed odd to me, and at this point they are very discouraged.  It is their first introduction to data structures.  Anyways, thanks for the help, have a good Thanksgiving.

Corey
0

## Featured Post

### Suggested Solutions

An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of fu…
The goal of this video is to provide viewers with basic examples to understand how to use strings and some functions related to them in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use nested-loops in the C programming language.