Search code examples
calgorithmloopsnested-loopsbreak

I can't figure out how this loop not breaking and give the right value. It just keeps adding up


Code to bring copy the unique value from array A to B. And return the number of unique value which is the number of element in B

#include <stdio.h>
int func(int A[], int B[], int n)
{
 int i, j, inc = 0;
    for(i = 0; i < n; i++)
    {
        for(j = 0; j < i; j++)
        {
            if(A[i] == A[j])
            
                break;

this break supposed to break out the inner loop incrementally

        if(i == j)
        {
            B[inc] = A[i];
            inc++;
        }
        }
     
    }
  
 
}
int main()
{
    int A[100] = {1, 3, 4, 5, 3, 2, 5, 4, 1, 0};
    int B[100];
    int c;
    c = func(A, B, 10);
    printf(" %d", c);
}

Solution

  • Your test for i against j is misplaced. It belongs outside, but after, the inner loop. And, of course, you need to return inc.

    #include <stdio.h>
    int func(int A[], int B[], int n)
    {
        int i, j, inc = 0;
        for (i = 0; i < n; i++)
        {
            for (j = 0; j < i; j++)
            {
                if (A[i] == A[j])
                    break;
            }
            if (i == j)
            {
                B[inc] = A[i];
                inc++;
            }
        }
        return inc;
    }
    
    int main()
    {
        int A[100] = {1, 3, 4, 5, 3, 2, 5, 4, 1, 0};
        int B[100];
        int c;
        c = func(A, B, 10);
        printf("%d\n", c);
        for (int i=0; i<c; ++i)
            printf("%d ", B[i]);
        fputc('\n', stdout);
    }
    

    Output

    6
    1 3 4 5 2 0 
    

    That is the correct answer. there are six unique values in the source array, 0...5 inclusively.