I had written a program of pattern matching in 'c' language. But it always show me the wrong output. Using the same to same logic I had written the code in 'c++' language & it works perfectly well there but not in 'c'.
According to my program, firstly I need to enter the size of the "text" & "pattern" that I want to enter. Then according to the size, the character array should store the corresponding number of characters in it using for loop. But for ex. if I enter the size of text to be 5, it stores only 2 characters & then displays a wrong answer further.
#include<stdio.h>
int p, t, c, LOC, i, j;
void main()
{
printf("Enter size of Text and Pattern\n");
scanf("%d %d",&t,&p);
char pat[p];
char txt[t];
printf("Enter the Text\n");
for(i=0;i<t;i++)
{
scanf("%c",&txt[i]);
}
printf("Enter the Pattern\n");
for(i=0;i<p;i++)
{
scanf("%c",&pat[i]);
}
int MAX=t-p+1;
for(i=0;i<MAX;i++)
{
int count=0;
c=0;
for(j=i;j<i+p;j++)
{
if(pat[count]==txt[j])
{
count++;
c++;
}
else
break;
}
if(c==p)
{
LOC=i+1;
break;
}
}
if(LOC!=0)
printf("Pattern found at location: %d",LOC);
else
printf("NOT FOUND\n");
}
Expected:
Enter size of Text and Pattern
5 2
Enter the Text
abbca
Enter the Pattern
bc
Pattern found at location: 3
Actual:
Enter size of Text and Pattern
5 2
Enter the Text
abb
Enter the Pattern
a
NOT FOUND