C/C++ Program to Count Number of Uppercase and Lowercase Letters in a File

Write a program to count the number of uppercase and lowercase letters ( characters ) in a file in C/C++.

For example,

Text File Content
Hello, My name is John Smith
Nice to Meet You

Output
Uppercase: 7
Lowercase: 28

The logic to count the number of uppercase and lowercase from a file is very simple. We simply read each character of the file using fgetc() and check if the character is uppercase or lowercase. We maintain 2 counters to keep track of the number of uppercase and lowercase characters.

#include <stdio.h>

int main() {

	int upper = 0, lower = 0;
	char c;

	// open file - text.txt
	// the second parameter "r" denotes we are only reading the content of the file
	// we cannot manipulate the content of the file
	FILE* fp = fopen("text.txt", "r");

	// if file doesn't open due to some problem, then terminate the program
	if (fp == NULL)
		return 0;


	while (1) {

		// fgets() reads each character of the file	
		c = fgetc(fp);

		// break the loop on reaching the EOF - End of File character
		if (c == EOF)
			break;

		// if c is uppercase alphabet, increment upper
		if (c >= 'A' && c <= 'Z')
			++upper;
		// if c is lowercase alphabet, increment lower
		else if (c >= 'a' && c <= 'z')
			++lower;

	}

	fclose(fp);

	printf("Uppercase: %d\nLowercase: %d", upper, lower);

}

Output

Uppercase: 4
Lowercase: 18

Content of the file – text.txt

Hello, My name is John Smith.

Read

Leave a Comment

Your email address will not be published. Required fields are marked *