PoorProgrammer PoorProgrammer - 2 months ago 10
C Question

C Program Doesn't Work Properly (Sets, Arrays, Loops)

C Program Doesn't Work Properly (Sets, Arrays, Loops)

pls help

Output:

Complement of A to B: 0110010010,
but is must be: 0100000010

printf("A \\ B: ");
for (int i = 0; i < SizeOfU; i++)
{
for (int j = 0; j < SizeOfB; j++)
{
if ((U[i] == A[j]) && (A[i] != B[j]))
{
i++;
j = 0;
printf("1");
}

Answer

In your code you have:

for (int i = 0; i < SizeOfU; i++)
{
  for (int j = 0; j < SizeOfB; j++)
  {
    if ((U[i] == A[j]) && (A[i] != B[j]))

The variable i is an index for the array U[], while j is an index for the array B[]. The problem is that you are using both the index i and j also for A[]. This is clearly wrong; you are in fact reading past the end of A[], but only luck has prevented you from getting a segmentation fault.

Try to write the algorithms without using the array U[]. For the union, you can just print out the elements of A[], followed by the elements of B[] that are not also in A[].

Comments