Find the number of capital letters in a file

As a first step to solve this problem, we need to have a file descriptor with a read (“r”) mode to read the contents of the file.

// fopen to open file with parameter "r" for read mode.
fp = fopen("/Users/ramesha/first.txt", "r");

In this problem, we need to read each character and need to check if that character is in capital letter boundary (i.e., between ‘A’ to ‘Z’). If so, then we need to increment the capital letter count to 1, we need to do this until we reach the end of the file.

// to read each character and check if it reaches last character.
(ch = fgetc(fp)) != EOF
// increase capital count if character falls under capital letter bounds
if (ch >= 'A' && ch <= 'Z')
{
   capCount++;
}

Below is the complete C program to find the number of capital letters in a text file. The runtime for this program is O(N), where N is the size of the file.

int main()
{
 	FILE *fp;
 	char ch;
	int capCount = 0;
 	fp = fopen("/Users/ramesha/first.txt", "r");
 	while ((ch = fgetc(fp)) != EOF)
 	{
 		if (ch >= 'A' && ch <= 'Z')
 		{
 			capCount++;
 		}
 	}
        cout << "Capital letters count is: << capCount << endl;
 	return 0;
}
// Output
Capital letters count is: 10

It is all about finding the number of capital letters in a text file using C, if you know any better solution for this, please let our readers know by commenting here below. Happy Learning!.

See more:
http://rjp.b44.myftpupload.com/c-program-to-get-number-of-lines-in-a-file/
http://rjp.b44.myftpupload.com/c-program-to-convert-file-contents-to-upper-case/