C Program for Pattern Matching

CWC
4 Min Read

In C Programing, Pattern matching is the way of checking a series of pattern or a sequence of digits or string with some other pattern and find out if it matches or not, in pattern recognition, the match usually has to be exact.

A pattern can be a series of digits, a string, different types of colors arranged in order. The order is really important in case of pattern matching.

We begin the code with including the header files “stdio.h” and “conio.h” which helps in input and output of data and holds the output screen.

We used an array to input a string of numbers one by one. If you are using an array to input string of numbers, you have to count the actual number of digits present in the string and input that number.

printf("enter the count of numbers in the string");
scanf("%d",&f);

After counting the number we now input the digits one by one which will then be stored in the array “no[]”

printf("enter the string of numbers one by one");
for(i=0;i<f;i++)
{
scanf("%d",&no[i]);
}

After input of the main string, we follow the same steps for the sub-string which is to be matched,

printf("enter the count of numbers in the sub-string");
scanf("%d",&f1);
printf("enter the sub-string of numbers one by one");
for(i=0;i<f1;i++)
{
scanf("%d",&s[i]);
}

We count the number of digits in sub-string too and then input the string.

From here the main part begins, initialize a for loop ‘i’ and run it until the value is less than or equal to the number of digits in the main string and take another for-loop ‘j’ inside it and run it until it is less than or equal to the number of digits in the sub-string.

for(i=0;i<f;i++)
{
for (j=i;j<(f1+i);j++)
{
if (no[j]==s[c])
c=c+1;
}

Now check if all the values of first sub-string or digits of sub-string are found in the main string anywhere in continuation then increment the value of variable “c” and after the termination of the loop check if the value of “c==f1” then print “substring found”.

if(c==f1)
{
printf("sunbstring found");
break;
}

Else we initialize the value of “c=0” and increment the value of first loop and repeat the process. On the end of the first loop if nowhere the pattern is found then the value of c will never be equal to the number of digits in sub-string and hence “substring not found” will be displayed on the output screen.

if(c!=f1)
printf("substring not found");

I have used a sequence of digits or a string of digits and initialize it using array, you can use different kind or pattern for running pattern matching like strings, etc. most important thing is to understand the logic.

C Program for Pattern Matching Output

Download: Source Code C Program for Pattern Matching

[sociallocker]Source Code C Program for Pattern Matching
Password:codewithc.com[/sociallocker]

Share This Article
Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

English
Exit mobile version