Tuesday, December 28, 2010

union of two arrays

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

/**
* program for union of two arrays
*/

#include<stdio.h>
#define TRUE 0
#define FALSE 1
void main()
{


int
n1 = 0 , i =0 , n2=0 , j = 0 , flag =FALSE , 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 union of two arrays

// first we will copy first ayyar in result
printf("\n");
for
(i = 0 ; i < n1 ; i++)
{


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


// now we will copy the elements one bt one
// but before that we will check if that element alaready exists in the array
// if it already exists then we will not copy otherwise we will copy
for(i = 0 ; i < n2 ; i++)
{


flag = FALSE ;
for
(j = 0 ; j< r1 ; j++ )
{


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

flag = TRUE;
}
}


if
(flag == FALSE)
{

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




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


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

printf("\b \n");
}

No comments:

Post a Comment