Reputation: 955
i have this code ... for a function who get 7 numbers from the user and put it into array number 1.... and second create a random numbers and put them into array number 2....check if there is a common values ...(not only in the same place for example: not only if ar1[1]==ar2[1] ... but to check for all places if there is a common values)....and to put the different values in third array...to create third array and put the not common values in it ... this is my code:
//includes
# include <stdio.h>
# include <conio.h>
# include <stdlib.h>
# include <time.h>
//define
#define N 7
//prototype
void randomArray(int maxVal,int ar2[]);
int main()
{
//variables/arrays
int ar1[N],ar2[N],ar3[N],i,z,t,temp,maxVal,counter;
printf("Please Enter %d numbers: ",N);
for(i=0;i<7;i++)
{
scanf("%d",&ar1[i]);
}
while(1)
{
printf("Please enter a max value: ");
scanf("%d",&maxVal);
if(maxVal>0)
break;
}
randomArray(maxVal,ar2);
getch();
return 0;
}
//randomArray
void randomArray(int maxVal,int ar2[])
{
int i;
for(i=0;i<N;i++)
{
/* get random value between minVal and maxVal */
ar2[i] = (rand() % (maxVal+1 - 1)) + 1;
}
}
Upvotes: 0
Views: 728
Reputation: 13533
Here's the simple, brute force approach. It first compares each element in array 1 against every element in array 2 and stores it if it's not in array 2. Then it does the same thing for array 2. Then it prints array 3.
Note: you need to change the size of array 3 to N*2 in case there are no matches. Also, set all elements in array 3 to 0 first to mark as a non-result. Or keep track of array 3's length.
int ar3[N*2] = {0};
int index = 0;
//Check 1st array
printf("Array 1:\t");
for (int i = 0; i < N; i++) {
bool in_array = false;
for (int k = 0; k < N; k++) {
if (ar1[i] == ar2[k]) {
in_array = true;
break;
}
}
if (!in_array) {
ar3[index++] = ar1[i];
}
printf(" %d", ar1[i]);
}
//Check 2nd array
printf("\r\nArray 2:\t");
for (int i = 0; i < N; i++) {
bool in_array = false;
for (int k = 0; k < N; k++) {
if (ar2[i] == ar1[k]) {
in_array = true;
break;
}
}
if (!in_array) {
ar3[index++] = ar2[i];
}
printf(" %d", ar2[i]);
}
// Print result
printf("\r\nUnique:\t");
for (int i = 0, j = 0; i < N*2; i++) {
if (0 == ar3[i]) {
break;
}
printf(" %d", ar3[i]);
}
If this works for you, please accept as correct answer.
Upvotes: 1