Help with assigning array

How can you assign the intersection array? I tried to do it and all I get was

21 21 21 21 21 21 21 21 21 21

What I wanted was 3 7 14 17 21


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
 #include <iostream>
using namespace std;


const int SIZE = 10;

void getIntersection(int setA[], int setB[], int intersection[], int SIZE);
void showIntersection(int intersection[], int SIZE);


int main()
{
	int setA[SIZE] = { 2,3,5,7,9,10,14,17,20,21 };
	int setB[SIZE] = { 1,3,4,7,8,11,14,16,17,21 };
	int intersection[SIZE] = { 0 };

	getIntersection(setA, setB, intersection, SIZE);
    showIntersection(intersection, SIZE);
	return 0;
}

void getIntersection(int setA[], int setB[], int intersection[], int SIZE)
{
	for (int i = 0; i < SIZE; i++)
	{
		for (int j = 0; j < SIZE; j++)
		{
			if (setA[i] == setB[j])
			{
				for (int n = 0; n < SIZE; n++)
				{
					intersection[n] = setA[i];
				}
			}
		}
	}

	
	
}

void showIntersection(int intersection[], int SIZE)
{
	for (int i = 0; i < SIZE; i++)
	{
		cout << intersection[i] << " ";
	}
}
Last edited on
Maybe like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int getIntersection(int setA[], int setB[], int intersection[], int SIZE)
{
    int k = 0;
    for (int i = 0; i < SIZE; i++)
    {
        for (int j = 0; j < SIZE; j++)
        {
            if (setA[i] == setB[j])
            {
                if (k < SIZE)
                {
                    intersection[k] = setA[i];
                    ++k;
                }
            }
        }
    }

    return k;    
}

The return value is how many values belong to the intersection.
Ok, thank you. I got it.
Registered users can post here. Sign in or register to post.