Monday, 19 December 2016

Write a program to implement union and intersection?

Q.: Write a program to implement union and intersection?

/*   ##########################

     Girfa : Student Help
     For More Program Visit : http://girfahelp.blogspot.in/p/c-language.html
     Program to implement union and intersection
     ##########################*/
#include<stdio.h>
#include<conio.h>
#define MAX 5
int check_avl(int [],int,int); /* Check a number exist in an array */
void print(int [],int); /* Print an arrar*/
void main()
{
     int ar1[MAX],ar2[MAX],uni[MAX*2],ins[MAX];
     int uni_index,int_index,flag=0,i,j;
     clrscr();
     printf("\nFirst Array Input\n");
     for(i=0;i<MAX;i++)
     {
          printf("Enter %d Position number>> ",i+1);
          scanf("%d",&ar1[i]);
     }
     printf("\nSecond Array Input\n");
     for(i=0;i<MAX;i++)
     {
          printf("Enter %d Position number>> ",i+1);
          scanf("%d",&ar2[i]);
     }

     //Merge first array to union
     for(i=0,uni_index=0;i<MAX;i++)
     {
          if(check_avl(uni,ar1[i],uni_index)==1)
              uni[uni_index++]=ar1[i];
     }
     //Merge Second array to union
     for(i=0;i<MAX;i++)
     {
          if(check_avl(uni,ar2[i],uni_index)==1)
              uni[uni_index++]=ar2[i];
     }
     //Merge both array to to Intersection
     for(i=0,int_index=0;i<MAX;i++)
     {
          for(j=0,flag=0;j<MAX;j++)
          {
              if(ar1[i]==ar2[j])
              {
                   flag=1;
                   break;
              }
          }
          if(flag==1)
          {
              ins[int_index++]=ar1[i];
          }
     }

     printf("\n\tFirst Array\n");
     print(ar1,MAX);
     printf("\n\tSecond Array\n");
     print(ar2,MAX);
     printf("\n\tUnion Array\n");
     print(uni,uni_index);
     printf("\n\tIntersection Array\n");
     print(ins,int_index);
     getch();

}
int check_avl(int ar[],int n,int s)
{
     int i,flag=0;
     for(i=0;i<s;i++)
     {
          if(ar[i]==n)
          {
               flag=1;
              break;
          }
     }
     if(flag==1)
          return 0;
     else
          return 1;
}
void print(int ar[],int s)
{
     int i;
     for(i=0;i<s;i++)
          printf("\t%d",ar[i]);
}

No comments:

Post a Comment