Consider this data sequence: \"fish bird reptile reptile bird bird bird mammal f
ID: 3768145 • Letter: C
Question
Consider this data sequence: "fish bird reptile reptile bird bird bird mammal fish". There is a CONSECUTIVE REPETITION of length 3 (the three consecutive birds) and a CONSECUTIVE REPETITION of length 2 (the two reptiles). There are also several SINGLETONs of length 1 (a singleton fish, a singleton bird, a singleton mammal, and another singleton fish).
Write some code that uses a loop to read in a sequence of words, terminated by the "xxxxx". The code assigns to t the number of CONSECUTIVE REPETITIONS that were read. (For example, in the above data sequence that value would be 2.)Assume that t has already been declared but not initialized . Assume that there will be at least one word before the terminating "xxxxx".
For this exercise, you may assume the maximum length of a word is 8.
Explanation / Answer
Program:
#include <stdio.h>
#include <string.h>
int main(void) {
char str1[8],str2[8]="",str3[8]="";
int t=0;
printf("Enter the sentence:");
while(1)
{
scanf("%s",str1);
//strcmp will return 0 if two strings are same
if(strcmp(str1,"xxxxx") == 0)
{
break;
}
else
{
if(strcmp(str1,str2) == 0)
{
if(strcmp(str1,str3) != 0)
{
//incrementing count for number of repetitions
t=t+1;
// copying string1 to string 3
strcpy(str3,str1);
}
}
strcpy(str2,str1);
}
}
// printing the output
printf("The number of repetitions are: %d",t);
return 0;
}
OUTPUT:
Enter the sentence:
fish bird reptile reptile bird bird bird mammal fish xxxxx
The number of repetitions are: 2