2

I created this program that read two arrays from the user(L1 and L2) and prints L1 - L2 if L2 is a sub array of L1.For example, if L1 ={'a','2','c','d','e'} and L2 ={'2','c','d'} then it should print {'a', 'e'}. But I am having some problem in the output. I get correct output only for some values but for most I am getting a L2 is not a sub array of L1.

#include<stdlib.h>
#include<stdio.h>

int main() {
    int n1, n2, j = 0, i = 0, temp = 0, a = 0;

    //ARRAY INPUT
    printf("Enter number of characters in L1: ");
    scanf("%d", &n1);
    int l1[n1];
    for (int i = 0; i < n1; i++) {
        printf("Enter character %d: ", i + 1); 
        scanf(" %c", &l1[i]);
    }
    printf("Enter number of characters in L2: ");
    scanf("%d", &n2);
    int l2[n2];
    for (int i = 0; i < n2; i++) {
        printf("Enter character %d: ",i + 1); 
        scanf(" %c", &l2[i]);
    }
    
    //FOR L1 > L2
    while (i < n1) {
        if(l1[i] == l2[j]) {
            i++;
            j++;
            if (j == n2) {
                a = 1; 
                break;
            }
        }
        else {
            i = temp + 1;
            temp = i;
            j = 0;
        }
    }
    
    if (a == 0) {
        printf("l2 is not a sub array of l1");
    }
    else if (a == 1) {
        printf("{");
        for (int i = 0; i < n1; i++) {
            if (i >= temp && i < (temp + n2)) 
                continue;
            printf("%c ", l1[i]);
        }
        printf("}");
    }

    exit(0);
}```
Chris
  • 26,361
  • 5
  • 21
  • 42
  • What is supposed to print if L1 is `{'a','a','b','a'}` and L2 is `{'a'}`? In that case, is it supposed to print: `"b"`, `"a b a"`, or `"a a b"` ? Similarly if L1 is `{'a','a','b','a'}` and L2 is `{'a', 'a'}`, what does it print? – selbie Sep 19 '21 at 19:28
  • "a b a" and "b a" respectively – Sparsh Arora Sep 19 '21 at 19:39
  • You have: `scanf("% c",&l2[i]);`. I'm pretty sure you did not mean to put a space between `%` and `c`. This same issues exists twice. – Chris Sep 19 '21 at 19:50
  • yaa that was a mistake I changed that its `" %c"` now but still the same problem – Sparsh Arora Sep 19 '21 at 19:53
  • Don't use `scanf()` when you want to read input. Use `fgets()` then parse the result with `sscanf()`. `scanf()` is very error-prone and you should really avoid it. – Zakk Sep 20 '21 at 00:00

1 Answers1

1

Your 'Arrays' should be a char array instead of an int.

char l1[n1];
char l2[n2];
Jaguar Nation
  • 122
  • 11