C program to check Subsequence, don’t confuse subsequence with substring. In our program we check if a string is a subsequence of another string. User will input two strings and we find if one of the strings is a subsequence of other. Program prints yes if either first string is a subsequence of second or second is a subsequence of first. We pass smaller length string first because our function assumes first string is of smaller or equal length than the second string.

[ad type=”banner”]

C programming code

[pastacode lang=”c” manual=”%23include%20%3Cstdio.h%3E%0A%23include%20%3Cstring.h%3E%0A%20%0Aint%20check_subsequence%20(char%20%5B%5D%2C%20char%5B%5D)%3B%0A%20%0Aint%20main%20()%20%7B%0A%20%20%20int%20flag%3B%0A%20%20%20char%20s1%5B1000%5D%2C%20s2%5B1000%5D%3B%0A%20%0A%20%20%20printf(%22Input%20first%20string%5Cn%22)%3B%0A%20%20%20gets(s1)%3B%0A%20%0A%20%20%20printf(%22Input%20second%20string%5Cn%22)%3B%0A%20%20%20gets(s2)%3B%0A%20%0A%20%20%20%2F**%20Passing%20smaller%20length%20string%20first%20*%2F%0A%20%0A%20%20%20if%20(strlen(s1)%20%3C%20strlen(s2))%0A%20%20%20%20%20%20flag%20%3D%20check_subsequence(s1%2C%20s2)%3B%0A%20%20%20else%0A%20%20%20%20%20%20flag%20%3D%20check_subsequence(s2%2C%20s1)%3B%0A%20%0A%20%20%20if%20(flag)%0A%20%20%20%20%20%20printf(%22YES%5Cn%22)%3B%0A%20%20%20else%0A%20%20%20%20%20%20printf(%22NO%5Cn%22)%3B%0A%20%0A%20%20%20return%200%3B%0A%7D%0A%20%0Aint%20check_subsequence%20(char%20a%5B%5D%2C%20char%20b%5B%5D)%20%7B%0A%20%20%20int%20c%2C%20d%3B%0A%20%0A%20%20%20c%20%3D%20d%20%3D%200%3B%0A%20%0A%20%20%20while%20(a%5Bc%5D%20!%3D%20’%5C0′)%20%7B%0A%20%20%20%20%20%20while%20((a%5Bc%5D%20!%3D%20b%5Bd%5D)%20%26%26%20b%5Bd%5D%20!%3D%20’%5C0′)%20%7B%0A%20%20%20%20%20%20%20%20%20d%2B%2B%3B%0A%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20if%20(b%5Bd%5D%20%3D%3D%20’%5C0′)%0A%20%20%20%20%20%20%20%20%20break%3B%0A%20%20%20%20%20%20d%2B%2B%3B%0A%20%20%20%20%20%20c%2B%2B%3B%0A%20%20%20%7D%0A%20%20%20if%20(a%5Bc%5D%20%3D%3D%20’%5C0′)%0A%20%20%20%20%20%20return%201%3B%0A%20%20%20else%0A%20%20%20%20%20%20return%200%3B%0A%7D” message=”” highlight=”” provider=”manual”/]

Output of program:

Input first string
computer science is awesome
Input second string
tree
YES
[ad type=”banner”]

The logic of function is simple we keep on comparing characters of two strings, if mismatch occur then we move to next character of second string and if characters match indexes of both strings is increased by one and so on. If the first string ends then it is a subsequence otherwise not.

Categorized in: