The letter e is the most frequently used letter in English prose, and the letter z is the least frequently used.
QUESTION
The letter e is the most frequently used letter in English prose, and the letter z is the least frequently used. A friend of yours doing a sociology experiment believes that this may not necessarily be true of the writings of first-year college students. To test his theory, he asks you to create a program that will take a text file and print, for each letter of the English alphabet, the number of times the letter appears in the file. (frequency of the letter in the file)
Hint: Use an integer array of size 128, and use the ASCII values of letters to index into the array to store and retrieve counts for the letters.
SUMMARY
A text is taken in a file and is read character by character. The frequency of each character is stored in an array at the ASCII value index of the character. Then the frequency of each character is printed like letter e is the most frequently used letter in English prose.
EXPLANATION
A file named ‘data.txt’ is taken which contains a text. The file is opened in reading mode using ifstream object. Each of the characters is read and its corresponding ASCII value array index is incremented by one. After reading the file, the character and its frequency are printed as output. Also, the loop is iterated to find the most frequent and least frequent character is found and printed.
CODE
#include <iostream> using namespace std; #include <fstream> #include <iomanip> int main() { int arr[123]; for(int j=0;j<123;j++) arr[j]=0; ifstream infile; infile.open("data.txt"); char c; while(infile>>c) arr[int(c)]++; for(int i=0;i<122;i+=4){ cout<<char(i)<<" - "<<arr[i]<<"\t\t"; cout<<char(i+1)<<" - "<<arr[i+1]<<"\t\t"; cout<<char(i+2)<<" - "<<arr[i+2]<<"\t\t"; if((i+3)<122) cout<<char(i+3)<<" - "<<arr[i+3]<<endl; } int large=0,largeIndex,small=999999,smallIndex; for(int j=0;j<123;j++){ if(arr[j]>large){ large=arr[j]; largeIndex=j; } if(small>=arr[j]){ small=arr[j]; smallIndex=j; } } cout<<endl<<"Most frequent character is \'"<<char(largeIndex); cout<<"\' with frequency-"<<large<<endl; cout<<"Least frequent character is \'"<<char(smallIndex); cout<<"\' with frequency-"<<small<<endl; }
OUTPUT
Also Read: Read the question given below about data structures and write code in C++