C program to find Cartesian Product of two sets

 Cartesian product is a mathematical operation that returns a set (or product set or simply product) from multiple sets. That is, for sets A and B, the Cartesian product A × B is the set of all ordered pairs (ab) where a ∈ A and b ∈ B. Products can be specified using set-builder notation, e.g.



Let us take an example of 3✕3 Cartesian product: -


Let A = {a, b, c} and B = {d, e, f}
The Cartesian product of two sets is
A x B = {a, d}, {a, e}, {a, f}, {b, d}, {b, e}, {b, f}, {c, d}, {c, e}, {c, f}}



Concept For the Code:-

In this program we declare 3 array a, b and c of length 50, now we declare variable i, s1, s2, j, and k. Now we ask all the variables value from the user to compute the Cartesian product. The use of For Loop is to take out the Cartesian product until the user inputted condition is met.


CODES

#include <stdio.h>
#include <conio.h>
int main()
{
    int a[50], b[50], c[50], i, s1, s2, j, k;
    printf("Enter how many elements in set 1\n");
    scanf("%d", &s1);
    printf("Enter how many elements in set 2\n");
    scanf("%d", &s2);
    printf("Enter elements of set 1\n");
    for (i = 0; i < s1; i++)
    {
        scanf("%d", &a[i]);
    }
    printf("Enter elements of set 2\n");
    for (i = 0; i < s2; i++)
    {
        scanf("%d", &b[i]);
    }
    printf("cartessian product=");
    printf("{");
    for (i = 0; i < s1; i++)
    {
        for (j = 0; j < s2; j++)
        {
            printf("(%d,%d)", a[i], b[j]);
            printf(",");
        }
    }
    printf("}");
}
Share To:

Arogya Thapa Magar

Post A Comment:

0 comments so far,add yours