Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a C program named as getMostFreq.c that takes input text file as arguments

ID: 3576212 • Letter: W

Question

Write a C program named as getMostFreq.c that takes input text file as arguments, outputs the most frequent letter (ignoring cases) and displays how many times that letter appears. If the text file does not exist, print out an error message to the terminal. For example, sample outputs could be like below $cat test.txt This is a list of courses. CSC 1010 - COMPUTERS & APPLICATIONS $./countC test.txt Most frequent letter is 's', it appeared 8 times $./countC NotExist.txt Error: file not exist. Put the source code of getMostFreq.c in your answer sheet. In your answer sheet, please also attach screenshots of the outputs using the test.txt file in the example.

Explanation / Answer

#include<stdio.h>
#include <stdlib.h>
#include<string.h>
int main()
{
//File pointer created
FILE * file;
//File open in read mode
file = fopen( "demo.txt" , "r");
char arr[255];
int c = 0, d = 0, occur[26] = {0}, max, loc = 0;
//Checks file can be opend or not
if (file)
{
//Loops till end of the file
while (!feof(file))
{
//Reads one character from the file and stores it in the array
fscanf(file, "%c", &arr[d++]);
}
//Adds null termination at the end of the array
arr[d-1] = '';
}
//Displays the error message if file unable to open
else
{
printf("ERROR: File not exist.");
exit(0);
}
//Close the file
fclose(file);
printf(" Original String = %s", arr);
//Loops till end of the string
for(c = 0; c < arr[c] != ''; c++)
{
//Checks for the upper case
if(isupper(arr[c]))
//Find out the position for the alphabet (ascii value of A is 65)
d = arr[c] % 65;
//Lower case
else
//Find out the position for the alphabet (ascii value of a is 97)
d = arr[c] % 97;
//Updates the occurrence of alphabet position counter by 1
occur[d]++;
}
//Assumes the zero position value is the maximum occurance
max = occur[0];
//Loops for 26 alphabets
for(c = 1; c < 26; c++)
{
//Checks current occurance value is maximum
//Then the earlier one thand update the maximum
if(occur[c] > max)
{
max = occur[c];
loc = c;
}
}
printf(" Most frequent letter is '%c', it appears %d times ", loc + 97, occur[loc]);
}

Output:

Original String = This is imagination.         

Most frequent letter is 'i', it appears 5 times

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote