C Programming
I am trying to also print the frequency and the occurrence of an input text file. I got the occurrence to but cant get the frequency.
Formula for frequency is "Occurrence / total input count", this is the percentage of occurrence.
Can someone please help me to get the frequency to work.
Code:
int freq[26] = {0};
fgets(input1, 10000, (FILE*)MyFile);
for(i=0; i< strlen(input); i++) {
freq[input[i]-'a']++;
count++;
}
printf("Text count = %d", count);
printf("\n");
printf("Frequency of plain text\n");
for(int i=0;i<26;i++){
char temp = 'a' + i;
printf("%c : %d : %f\n",temp,freq[i],(float)(freq[i]/count));
Results:
Text count = 868
Frequency of plain text
a : 64 : 0.000000
b : 11 : 0.000000
c : 37 : 0.000000
d : 31 : 0.000000
e : 109 : 0.000000
f : 15 : 0.000000
g : 13 : 0.000000
h : 30 : 0.000000
i : 68 : 0.000000
j : 2 : 0.000000
k : 6 : 0.000000
l : 37 : 0.000000
m : 18 : 0.000000
n : 61 : 0.000000
o : 56 : 0.000000
p : 21 : 0.000000
q : 3 : 0.000000
r : 54 : 0.000000
s : 64 : 0.000000
t : 77 : 0.000000
u : 44 : 0.000000
v : 12 : 0.000000
w : 11 : 0.000000
x : 1 : 0.000000
y : 22 : 0.000000
z : 1 : 0.000000
//include headers
#include<stdio.h>
#include<string.h>
//driver function
int main(){
//file pointer
FILE *MyFile;
//create frequency array
int freq[26] = {0};
//open file in reading mode
MyFile = fopen("input.txt" , "r");
//create a character array of size 10000
char input[10000];
//count stores total input count of letters
int count=0;
//read till EOF(end-of-file)
while(!feof(MyFile)){
//input text
fgets(input, 10000, (FILE*)MyFile);
//iterate through string
for(int i=0; i< strlen(input); i++){
//increment count of alphabets read
if(input[i]<='z' && input[i]>='a')
freq[input[i]-'a']++;
//increment total count
count++;
}
}
//print total text count
printf("Text count = %d", count);
//newline
printf("\n");
//heading
printf("Frequency of plain text\n");
//for all characters from a to z
for(int i=0;i<26;i++){
//current character
char temp = 'a' + i;
//print it's occurrence and frequency
printf("%c : %d : %f\n",temp,freq[i],(freq[i]/(float)count));
}
return 0;
}
input file(input.txt)
abcdbdbdbdbdhasuhfsakdjajbfkdjgkjdngsithosietnsnskbsgbnsklgbnskbnslibnsbn
dnfbdsskjdfbsjbskjfbsjk
output
Text count = 97
Frequency of plain text
a : 4 : 0.041237
b : 16 : 0.164948
c : 1 : 0.010309
d : 11 : 0.113402
e : 1 : 0.010309
f : 5 : 0.051546
g : 4 : 0.041237
h : 3 : 0.030928
i : 3 : 0.030928
j : 8 : 0.082474
k : 9 : 0.092784
l : 2 : 0.020619
m : 0 : 0.000000
n : 9 : 0.092784
o : 1 : 0.010309
p : 0 : 0.000000
q : 0 : 0.000000
r : 0 : 0.000000
s : 16 : 0.164948
t : 2 : 0.020619
u : 1 : 0.010309
v : 0 : 0.000000
w : 0 : 0.000000
x : 0 : 0.000000
y : 0 : 0.000000
z : 0 : 0.000000
CODE
INPUT/OUTPUT
input.txt
output
So if you still have any doubt regarding this solution please feel free to ask it in the comment section below and if it is helpful then please upvote this solution, THANK YOU.
Get Answers For Free
Most questions answered within 1 hours.