cstringfor-loopintegernested-for-loop

Why an integer has different value even when its position is not changed


I was trying to do one coding questions solve, that says:

Write an alternate version of squeeze(s1, s2) which deletes each character in s1 which matches any character in the string s2.".

Well i did code it and working version is.

#include <stdio.h>

char s1a[1001], s2a[1001];

void squeeze() {
    int i, j, k;
    extern char s1a[], s2a[];

    for (i = 0; s2a[i] != '\0'; i++) {
        for (k = j = 0; s1a[j] != '\0'; j++) {
            if (s1a[j] != s2a[i]) s1a[k++] = s1a[j];
        }
        s1a[k] = '\0';
    }
    printf("%d/n", k); /*k's value*/
}

int main() {
    int c, s1 = 0, i = 0, j = 0;
    extern char s1a[], s2a[];

    while ((c = getchar()) != EOF && i < 1000) {
        if (c != '\n' && s1 == 0) {
            s1a[i++] = c;
        }
        else if (c == '\n' && s1 == 0) {
            s1a[i] = '\0';
            i = 0;
            s1++;
        }
        else if (c != '\n' && s1 == 1) {
            s2a[j++] = c;
        }
        else if (c == '\n' && s1 == 1) {
            s2a[j] = '\0';
            j = 0;
            squeeze();
            printf("%s\n", s1a);
            s1a[0] = '\0';
            s2a[0] = '\0';
            s1 = 0;
        }
    }
}

I did input "hello\nhell\n".

It works fine but 13'th line in this code was outside of both for loops before where print k (at 15'th line) is so at then it was printing k as 5 and when i added string terminator where it is now, it prints k as 1. It just works fine and prints "o" but before it was printing "ooooo".

Edit: The issue was with my understanding as s1a had 5 o's at end so k was 5 when not terminating after it was shrink.


Solution

  • The question is confusing because you're showing only the working code. You seem to be asking why k gave a different answer when you terminated the s1a string after both loops completed compared to the correct time where you terminate it after each pass of the outer loop.

    The reason is because the inner loop expects s1a to be terminated at its current size.

    If s1a was {h, e, l, l, o, \0}, and you removed the 'h' but did not write a new terminator, you would be left with {e, l, l, o, o, \0}. When you do write a new terminator, get {e, l, l, o, \0, \0}.

    So each time you scan to see if there are instances of a letter, you scan only the part of the string that still matters, and k never reaches the indexes of the abandoned characters at the end.