In: Computer Science
Programing in C
Create a text file with 1000 random H's and T's, then write a program to count how many times each of the pairs HH, HT, TH, TT occur. Each should occur equally often. (use getchar(), read until EOF.) Regard the file as a sequence of pairs (so pairs do not overlap.) If there are an odd number of characters, ignore the last one.
Example output:
HH occured 113 times
HT occured 128 times
TH occured 133 times
TT occured 126 times
#include
#include
int main(void)
{
// initialise variables
FILE *fp;
int c1,c2;
int hhCount=0,ttCount=0,htCount=0,thCount=0;
fp = fopen("texgt.txt", "r");
if(fp==NULL)
{
// if error in opening a file
printf("Error in opening the file..!!");
exit(1);
}
while((c1 = fgetc(fp)) != EOF)
{
// read second character
c2=fgetc(fp);
if(c2==EOF)
break;
if(c1=='H')
{
if(c2=='H') // this is HH
hhCount++;
else // This is HT
htCount++;
}
else
{
if(c2=='H') // this is TH
thCount++;
else // this is TT
ttCount++;
}
}
// print output
printf("HH occured %d times\n",hhCount);
printf("HT occured %d times\n",htCount);
printf("TH occured %d times\n",thCount);
printf("TT occured %d times\n",ttCount);
fclose(fp);
return 0;
}
==================
SCREENSHOT:
OUTPUT:
RANDOM FILE:
HHTTTTHTHTTHHTTHTHHTHTTHTTTHTHTTTTTTTHHTTTHTTTHHHTHTHTTHHTHTTTTTTTTTTTTTHTHHTHHTHTTHTHHTTTHTHHHTHHHHTHTTHHTHTHTHHHHTHHTHTTTHTHTHHTHHHHHHTHHHTTHTHTTHHHHHHHHHHTHTTHHTHTHHHTTHTTHHTHHTHHTTHTTTTTTHTHTHTHHHHTHTHHHHHTHHTTTHTHTTTTTHTHTHHHHTHHTTHHHTHTHTHTTTHHHHTHHTTTHHTTTHTHTHTHTHTHHHHHHHTTHTHTHHHTTTHTHHHHTHHTHTTTHHTHTHHTTTTTHTHTTTHHHTTTTHHHHTTHTTTHHHTHTTHTTHTHHTTTHHTHHTHTTTTTHTHTTHTHTTHTTHTTTHTHHHHTHHTHTHTHHHTTTTTTHHTTHHHTTTHTHHHTHTTTHTHHTTHHHTTTHTHHTHHTTHTHHHHHTHHT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