Tuesday, December 28, 2010

intersection of two arrays

/****************************
* Umang B Bhatt *
* bhatt.umang7@gmail.com *
*****************************/

/**
* program for intersection of two arrays
*/

#include<stdio.h>
void main()
{


// here for the program of union intersection and minus
// of arrays, we assume that there is no repetation of numbers in
// sinble array
int n1 = 0 , i =0 , n2=0 , j = 0 , no1[100] , no2[100];

int
result[200];
int
r1 = 0 ;

printf("How many numbers you want to scan in first array ? ");
scanf("%d",&n1);
if
(n1 < 0 || n1 > 100 )
{


printf("Invalid number. It must be brtween 1 to 100");
}

else

{

// logic for scanning the numbers
for(i = 0 ; i < n1 ;i++)
{


printf("Enter element %d: ", i);
scanf("%d",&no1[i]);
}
}


printf("How many numbers you want to scan in second array ? ");
scanf("%d",&n2);
if
(n2 < 0 || n2 > 100)
{


printf("Invalid number. It must be brtween 1 to 100");
}

else

{

// logic for scanning the numbers
for(i = 0 ; i < n2 ;i++)
{


printf("Enter element %d: ", i);
scanf("%d",&no2[i]);
}
}



// now the intersection of two arrays
// now we will copy the elements one by one
// if some element exist in both the arrays then only we will copy them
for(i = 0 ; i < n1 ; i++)
{


for
(j = 0 ; j< n2 ; j++ )
{


if
(no1[i] == no2[j] )
{

result[r1++] = no1[i];
}
}
}


// now display the array
printf("\nTHe array (intersection) is : ");
for
(i = 0 ; i < r1 ; i++ )
{


printf(" %d," , result[i] );
}

printf("\b \n");
}

No comments:

Post a Comment