Good morning!
I have this code for union of two arrays:
Code:
#include<stdio.h>
#include<conio.h>
void main()
{
int A[10], B[10], C[10], i, j, k = 0, n, m, flag = 0;
printf("How many elements does array A have?\n");
scanf("%d", &n);
printf("Please enter the elements of array A\n");
for (i = 0; i<n; i++)
{
scanf("%d", &A[i]);
}
printf("How many elements does array B have?\n");
scanf("%d", &m);
printf("Please enter the elements of array B\n");
for (j = 0; j<m; j++)
{
scanf("%d", &B[j]);
}
for (i = 0; i<n; i++)
{
C[k] = A[i];
k++;
}
for (i = 0; i<n; i++)
{
flag = 0;
for (j = 0; j<m; j++)
{
if (B[i] == C[j])
{
flag = 1;
break;
}
}
if (flag == 0)
{
C[k] = B[i];
k++;
}
}
printf("\n The union of A and B is:\n");
for (i = 0; i<k; i++)
{
printf("%d", C[i]);
}
getch();
}
The problem is as follows: The program runs, but when I give for example 2 elements in A: 1 and 2, and 3 elements in B: 2, 3 and 4 it returns the union as 123, when it should be 1234. Where did I go wrong? Also, how exactly does "flag" work?