Finding How Many Capital And Small Letters in the Program


Explanation

In C file handling, we can read a program file and count the number of capital and small letters present inside it. In this program, the file is opened in "rt" (read text) mode. Each character is read using fgetc() and checked using character comparison conditions.

How It Works?

  • Step 1: Declare a file pointer using FILE *fp.
  • Step 2: Create two integer variables cap and small to store the count of capital and small letters.
  • Step 3: Open the file using fopen() in read mode.
  • Step 4: Read each character from the file using fgetc().
  • Step 5: Check whether the character is between 'A' to 'Z' and increase the capital letter count.
  • Step 6: Check whether the character is between 'a' to 'z' and increase the small letter count.
  • Step 7: Display the total number of capital and small letters.

Example Program


#include <stdio.h>
#include <conio.h>

main()
{

    FILE *fp;
    int cap = 0, small = 0;
    char ch;

    clrscr();

    fp = fopen("file1.c", "rt");

    while(!feof(fp))
    {

        ch = fgetc(fp);

        printf("%c", ch);

        if(ch >= 'A' && ch <= 'Z')
        {

            cap++;

        }

        if(ch >= 'a' && ch <= 'z')
        {

            small++;

        }

    }

    printf("\n capital latters is %d", cap);

    printf("\n small latters is %d", small);

    fclose(fp);

    getch();

}

Output

#include <stdio.h>

main()
{
  printf("Hello India");
}

capital latters is 3
small latters is 18

Practice Exercises

Task 1: Write a C program to read a text file named data.txt and count how many capital letters and small letters are present inside the file.

Goal: Learn how to read characters from a file and check whether each character is an uppercase or lowercase letter using conditions.

💡 Hint: Open the file using fopen("data.txt","rt"). Use fgetc() to read each character and check:
  • 'A' to 'Z' → Capital letters
  • 'a' to 'z' → Small letters
💡 Show Solution

#include <stdio.h>
#include <conio.h>

main()
{

    FILE *fp;
    int cap = 0, small = 0;
    char ch;

    clrscr();

    fp = fopen("data.txt", "rt");

    while(!feof(fp))
    {

        ch = fgetc(fp);

        if(ch >= 'A' && ch <= 'Z')
        {
            cap++;
        }

        if(ch >= 'a' && ch <= 'z')
        {
            small++;
        }

    }

    printf("\n Capital Letters = %d", cap);

    printf("\n Small Letters = %d", small);

    fclose(fp);

    getch();

}

Output
Capital Letters = 5
Small Letters = 12
Explanation: The program opens the data.txt file in read mode. It reads each character using fgetc() and checks whether the character belongs to the uppercase or lowercase alphabet range. The counters cap and small are increased accordingly, and the final count is displayed.