PoorProgrammer2 - 20 days ago 4x

C Question

Program skips one object in a set (array).

clang -ggdb3 -O0 -std=c99 -Wall -Werror prog.c -o prog

Output:

Exclusive or (XOR) of A and B: 1 9 10 (But it should be: 1 **2** 9 10)

Union of A and B: 1 3 6 9 10 (But it should be: 1 **2** 3 6 9 10)

What is wrong with this program? Please help!

`#include <stdio.h>`

int main(void)

{

int U[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

int A[] = {2, 3, 6, 9};

int B[] = {1, 3, 6, 10};

int SizeOfU = sizeof(U) / sizeof(int);

int SizeOfA = sizeof(A) / sizeof(int);

int SizeOfB = sizeof(B) / sizeof(int);

printf("Exclusive or (XOR) of A and B: ");

for (int i = 0; i < SizeOfU; i++)

{

for (int j = 0; j < SizeOfB; j++)

{

if ((A[j] != B[j]) && ((U[i] == A[j]) || (U[i] == B[j])))

{

printf("%i ", U[i]);

i++;

j = 0;

}

}

}

printf("\n");

printf("Union of A and B: ");

for (int i = 0; i < SizeOfU; i++)

{

for (int j = 0; j < SizeOfA; j++)

{

if ((U[i] == A[j]) || (U[i] == B[j]))

{

printf("%i ", U[i]);

j = 0;

i++;

}

}

}

printf("\n");

return 0;

}

Answer

Your logic is bonked for several reasons. You are assuming that integer values will be in the same index of A and B. You really are only evaluating B. Undefined behavior if the length of A is less than B....

For the XOR case, think of it like this: For every item in U, find the items that appear in A or B, but not both:

```
for (int u = 0; i < SizeOfU; u++)
{
int inA = 0;
int inB = 0;
for (int a = 0; a < SizeOfA; a++)
{
inA = (A[a] == U[u]);
if (inA)
{
break;
}
}
for (int b = 0; b < SizeOfB; b++)
{
inB = (B[b] == U[u]);
if (inB)
{
break;
}
}
if ((inA && !inB) || (!inA && inB))
{
printf("%d", i);
}
}
printf("\n");
```

This solves the XOR set case. I'll leave the solution for the OR case as an exercise for you.

Source (Stackoverflow)

Comments