Write a C program to check whether the given array is a subset of another array.
#include <stdio.h>
#define MAX 256
int main() {
int array[MAX], subArr[MAX];
int flag, n1, n2, i, j;
/* get the number of elements in first array */
printf("Enter the number of elements in First Array:");
scanf("%d", &n1);
/* get the number of elements in sub array */
printf("Enter the number of elements in Second Array:");
scanf("%d", &n2);
/* get the entries for first array from user */
printf("Enter entries for first array:\n");
for (i = 0; i < n1; i++) {
printf("Array[%d]: ", i);
scanf("%d", &array[i]);
}
/* get the entries for subarray from the user */
printf("Enter entries for second array:\n");
for (i = 0; i < n2; i++) {
printf("subArr[%d]: ", i);
scanf("%d", &subArr[i]);
}
/* Error validation */
if (n1 < n2) {
printf("Second array is not the subset of first array!!\n");
return 0;
}
#define MAX 256
int main() {
int array[MAX], subArr[MAX];
int flag, n1, n2, i, j;
/* get the number of elements in first array */
printf("Enter the number of elements in First Array:");
scanf("%d", &n1);
/* get the number of elements in sub array */
printf("Enter the number of elements in Second Array:");
scanf("%d", &n2);
/* get the entries for first array from user */
printf("Enter entries for first array:\n");
for (i = 0; i < n1; i++) {
printf("Array[%d]: ", i);
scanf("%d", &array[i]);
}
/* get the entries for subarray from the user */
printf("Enter entries for second array:\n");
for (i = 0; i < n2; i++) {
printf("subArr[%d]: ", i);
scanf("%d", &subArr[i]);
}
/* Error validation */
if (n1 < n2) {
printf("Second array is not the subset of first array!!\n");
return 0;
}
/* checking whether second array is the subset of first array */
for (i = 0; i < n2; i++) {
flag = 0;
for (j = 0; j < n1; j++) {
if (subArr[i] == array[j]) {
flag = 1;
break;
}
}
if (!flag)
break;
}
/* print the result */
if (flag) {
printf("Second array is the subset of first array\n");
} else {
printf("Second array is not the subset of first array\n");
}
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter the number of elements in First Array:5
Enter the number of elements in Second Array:3
Enter entries for first array:
Array[0]: 10
Array[1]: 50
Array[2]: 40
Array[3]: 30
Array[4]: 20
Enter entries for second array:
subArr[0]: 40
subArr[1]: 20
subArr[2]: 10
Second array is the subset of first array
Enter the number of elements in First Array:5
Enter the number of elements in Second Array:3
Enter entries for first array:
Array[0]: 10
Array[1]: 50
Array[2]: 40
Array[3]: 30
Array[4]: 20
Enter entries for second array:
subArr[0]: 40
subArr[1]: 20
subArr[2]: 10
Second array is the subset of first array
No comments:
Post a Comment