I'm kind of confused about how the modulus operator works.

Suppose i have x % y with x > y. So if x was 6 and y was 2, then 6 % 2 would produce 0.

But i don't really get what happens when x < y :eek:

In this program some crazy **** happens that's gettin me a bit confused here.

The book says that the program basically wraps around the queue back to 0 when the end of the array is encountered.

``````#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#define LEN 100

void initqueue(int);
void put(char);
char get();
void queueerror();

static char *q;
static int N, head, tail, cnt;

int main(void)
{
char input[LEN];
puts("Enter a string:");
fgets(input, LEN, stdin);

int maxN = strlen(input);
initqueue(maxN);

char *token, delim[] = " ";
token = strtok(input, delim);
while (token != NULL)
{
if (isalnum(*token))
put(*token);
if (*token == '*')
printf("I released %c\n", get());
token = strtok(NULL, delim);
}

return 0;
}

void initqueue(int maxN)
{
q = (char *)malloc((maxN+1)*sizeof(char));
N = maxN + 1; head = N;
}

void put(char item)
{
q[tail++] = item;
tail = tail % N;
}

char get()
{
}

void queueerror()
{
puts("Stack is either full or empty!");
exit(0);
}``````

But i don't really get what happens when x < y

The result of division is 0 and the remainder is x. 2 % 6 would result in 2. If you assign the result back to x, the behavior is a no-op because the same value is assigned back.

The book says that the program basically wraps around the queue back to 0 when the end of the array is encountered.

Yes. Let's say that N is 11 and tail is 10. 10 % 11 is 10, which holds true for any case where x < y in x % y. That's why it's safe to always take the remainder when wrapping indexes like this.

Once tail becomes 11 though, the wrapping becomes apparent. 11 % 11 is 0, obviously. 12 % 11 is 1, 13 % 11 is 2, and so on until x once again becomes evenly divisible by y at 22 and the result wraps around to 0. Repeat until you get bored or exceed the limits of a signed integer. :)

OHH OK TY ty ty that makes much sense now ^_^V

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.18 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.