Alright, I was solving my assignment and in this particular program, the output for the word 'say' is displayed as 1 even though it occurs twice.
//Start
# include <stdio.h>
# include <string.h>
int main()
{
char Str[100]="Martha! Why did you say that name? Please! Stop! Why did
you say that name?", Words[100][100], Temp[100];
int i, j, k, n, Count;
j=k=0;
//Accepting input
//gets(Str);
Str[strlen(Str)]='\0';
//Copying Each and every word into a 2-D Array from the string
for(i=0;Str[i]!='\0';i++)
{
if(Str[i]==' ')
{
Words[j][k]='\0';
k=0;
j++;
}
else
{
Words[j][k++]=Str[i];
}
}
Words[j][k] = '\0'; //Null character for last word
n=j;
//Sorting the array of words
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(strcmp(Words[i], Words[j])>0)
{
strcpy(Temp, Words[i]);
strcpy(Words[i], Words[j]);
strcpy(Words[j], Temp);
}
}
}
printf("\n");
//Displaying frequecncy of each word
for(i=0;i<n;i+=Count) //Incrementing by count to process the next word
{
Count=1;
{
for(j=i+1;j<=n;j++)
{
if(strcmp(Words[i], Words[j])==0)
{
Count++;
}
}
}
printf("%s\t%d\n", Words[i], Count); //Count is used to display the frequecncy of each word
}
printf("\n");
return 0;
}//End
Here is the output:
Martha! 1
Please! 1
Stop! 1
Why 2
did 2
name? 2
**say 1**
that 2
you 2
As you see, the output displays the frequency of the word 'say' one even though it occurs in the string twice. Check the link for the output on the terminal?
n
is not set up correctly.
With n = j;
, conceptually this should be n = j+1;
for n
to represent n
words and not the last index.
// n = j;
n = j+1;
Without the above change the array is not completely sorted as n
is treated as the word count, yet it is 1-too-small.
Incorrectly sorted array is
Martha!, Please!, Stop!, Why, Why, did, did, name?, say, say, that, that, you, you, name?
Incomplete sort and now using n
as the last index messed up frequency count as "name?"
was found twice, yet not in consecutive order - thus jumping over the first "say"
.
// for (j = i + 1; j <= n; j++) {
for (j = i + 1; j < n; j++) {
Repaired code output
Martha! 1
Please! 1
Stop! 1
Why 2
did 2
name? 2
say 2
that 2
you 2
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.