I am a beginner. I think the main issue I have is with flags. (I cannot use a break command to stop the loops). Ex:
A={1,2,3,4,5} B={1,2,3,6}
I have to generate a new array with the previous ones, without duplicates. So: C={1,2,3,4,5,6}.
#include <stdio.h>
#include <stdlib.h>
#define M 5
#define N 4
int main() {
int A[M]={1,2,3,4,5};
int B[N]={1,2,3,6};
int U[M+N]; //M+N is the maximum size. it'll decrease with a counter.
int i=0, j=0,count=0,flag=0;
while(i<M){ //Array A is copied into Array U.
U[count]=A[i];
count++; //counter that will determine the size.
i++;
}
i=0,j=0;
while(i<M){
j=0;
flag=0;
while(flag==1 || j<N){ //check if the flag is on or if the array is ended.
if(B[j]!=A[i]){ // check if the element of the b array is different from
//the element of array A (cause i already copied the array A)
count++; //i make some space for the element to be copied.
U[count]=B[j];
}
else flag=1; //if the flag is on it means the element was equal, so i just
j++; //go to the next one
}
i++;
}
for(i=0;i<count;i++)
printf(" %d ", U[i]); //here i print, it prints the first 5 values from Array a correctly, for the other ones is a mess.
return 0;
}
My idea is to copy the longest array (A) to the new one (C) and then scan the second one (B) and checking each value with each value of the array A. If the value is different (out all of the values in A) I add the B value into C, otherwise I start to check the next value of array B with all of the values in A.