fork download
  1. #include <stdio.h>
  2.  
  3. typedef struct {
  4. int n;//the cardinal of the set
  5. int set[100];
  6. } TSet;
  7.  
  8. void read(TSet *p) {
  9. printf("number of elements N = ");
  10. scanf("%d",&p->n);
  11. for(int i = 0; i < p->n; ++i) scanf("%d",&p->set[i]);
  12. }
  13.  
  14. int belongTo(TSet p, int elem){
  15. int is = 0;
  16. for(int i = 0; i < p.n && !is; ++i) {
  17. if(elem == p.set[i]) {
  18. is = 1;
  19. }
  20. }
  21. return is;
  22. }
  23.  
  24. void display(TSet p) {
  25. for(int i = 0; i < p.n-1; ++i) printf("%d, ",p.set[i]);
  26. printf("%d",p.set[p.n-1]);
  27. printf("\n");
  28. }
  29.  
  30. int main(int argc, char const *argv[]) {
  31. TSet A, B,//first and second sets
  32. I, //intersection
  33. D, //difference
  34. R; //union
  35. I.n = 0;
  36. D.n = 0;
  37.  
  38. //read the first set
  39. read(&A);
  40. //read the second set
  41. read(&B);
  42.  
  43. printf("Set A:\n");
  44. display(A);
  45. printf("Set B:\n");
  46. display(B);
  47. R = B;
  48.  
  49. for(int i = 0; i < A.n;++i) {
  50. if(belongTo(B, A.set[i])==1) {
  51. I.set[I.n++] = A.set[i];
  52. } else {
  53. D.set[D.n++] = A.set[i];
  54. R.set[R.n++] = A.set[i];
  55. }
  56. }
  57. printf("Intersection:\n");
  58. display(I);
  59. printf("Difference:\n");
  60. display(D);
  61. printf("Union:\n");
  62. display(R);
  63. return 0;
  64. }
Success #stdin #stdout 0.01s 5544KB
stdin
5
1
2
3
4
5
3
-1
2
3
stdout
number of elements N = number of elements N = Set A:
1, 2, 3, 4, 5
Set B:
-1, 2, 3
Intersection:
2, 3
Difference:
1, 4, 5
Union:
-1, 2, 3, 1, 4, 5