Make a program that will implement a cartesian product i.e. a direct product of 2 arrays.
The program will ask the user for the size and elements of the 2 arrays. Then the program will
display the cartesian product.
{1,2} x {3,4} = {(1,3), (1,4), (2,3), (2,4)}Enter size of set A: 2A1: 1A2: 2Enter size of set B: 2B1: 3B2: 4{1,2} x {3,4} = {(1,3), (1,4), (2,3), (2,4)}The code below is very straight forward. Note that there is a discrepancy with the comma after each element. You can also download the full Visual Studio C++ 2010 Project and the Windows Executable from the attachments below.
CSC101_ASSN_01.C
#include <stdio.h>// Im using visual studio C++// and it does't have the capability// to dimension arrays with non constant// integers.#define MAX_ITEMS 100int main() {int x, y;
int arrA[MAX_ITEMS];
int arrB[MAX_ITEMS];
int lengthA, lengthB;
lengthA = lengthB = 0;
printf("Enter size of set A: ");
scanf("%d", &lengthA);
for (x=0; x<lengthA; x++) {
printf("A%d: ", x + 1);
scanf("%d", &arrA[x]);
}
printf("Enter size of set B: ");
scanf("%d", &lengthB);
for (y=0; y<lengthB; y++) {
printf("B%d: ", y + 1);
scanf("%d", &arrB[y]);
}
printf("{");
for (x=0; x<lengthA; x++) {
printf("%d", arrA[x]);
if (x < lengthA - 1)
printf(",");
}
printf("} x {");
for (y=0; y<lengthB; y++) {
printf("%d", arrB[y]);
if (y < lengthB - 1)
printf(",");
}
printf("} = {");
for (x=0; x<lengthA; x++) {
for (y=0; y<lengthB; y++) {
printf("(%d,%d)", arrA[x], arrB[y]);
}
}
printf("}\n");
return 0;
}Note that I'm using the Visual Studio C++ Compiler hence there is no support for non constant array dimensions. Doing the following code listing would result to an error.
int x = 5;int myarray[x];That is why i wrote a constant define preprocessor as the initialization limit for my arrays. There is a separate length variable though which acts as the assumed length of the array. You may refer to the code listing below for an example.
// this is only a temporary fix for // Visual Studio C++ Compilers.
define ARR_MAX 999; // actual lengthint my_arraylimit = 20; // assumed lengthint my_array[ARR_MAX];int x = 0;// ask for inputs from user for all// indexes of the assumed length.for (x; x<my_arraylimit; x++){ printf("Enter Input %d: ", x); scanf("%d", &my_array[x]);}March 10, 2011
9:06 PM