Find Word Frequency in File in C, C++, Java & Python – Code with Explanation & Examples in Short and Simple

   

C Program

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main() {
    FILE *f = fopen("data.txt", "r");
    char word[100], target[20] = "apple";
    int count = 0;
    while (fscanf(f, "%s", word) != EOF)
        if (strcasecmp(word, target) == 0) count++;
    fclose(f);
    printf("'%s' appears %d times\n", target, count);
}

C Output

Input:  
Apple is sweet. I like apple. apple is my favorite.  

Output:  
'apple' appears 3 times


C++ Program

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    ifstream f("data.txt");
    string w, target = "apple"; int c = 0;
    while (f >> w) if (w == target) c++;
    cout << "'" << target << "' appears " << c << " times\n";
}

C++ Output

Input:  
Apple is sweet. I like apple. apple is my favorite.  

Output:  
'apple' appears 3 times


JAVA Program

import java.nio.file.*; import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        String text = Files.readString(Path.of("data.txt")).toLowerCase();
        long count = Arrays.stream(text.split("\\W+"))
                           .filter(w -> w.equals("apple")).count();
        System.out.println("'apple' appears " + count + " times");
    }
}

JAVA Output

Input:  
Apple is sweet. I like apple. apple is my favorite.  

Output:  
'apple' appears 3 times


Python Program

from collections import Counter
words = open("data.txt").read().lower().split()
print("'apple' appears", Counter(words)["apple"], "times")

Python Output

Input:  
Apple is sweet. I like apple. apple is my favorite.  

Output:  
'apple' appears 3 times


In-Depth Explanation
Example
Suppose you are provided with a file consisting of a paragraph or sentence like:
"Apple is sweet. I like apple. apple is my favorite."
You need to identify the number of occurrences of the word "apple" in the file. It doesn't matter if it's in lowercase or uppercase—what's important is that you match the word correctly.

If you execute the code, the output informs you that the word "apple" occurs 3 times, accurately counting all instances regardless of its case (in most applications).

Real-Life Analogy
Think about reading a book and attempting to count how many times your name is mentioned. You thumb through each page, read each line, and keep track mentally. That's precisely what this program does—faster and more efficiently. It is the electronic equivalent of that mental accounting.

This method is extensively practiced in search engines (such as Google), PDF readers, or eBook software when a person searches for a keyword and wishes to know how many times it's referenced. It's also a basic concept in natural language processing (NLP) where word frequency is utilized to gauge significance or relevance. 

Why It Matters
Word frequency is crucial in text mining, data analysis, sentiment detection, spam filtering, and information retrieval. For instance, in a review system, the frequent occurrence of the word "bad" can signal poor sentiment. In SEO, keyword density analysis is a straightforward application of this reasoning.

Again, in interviews, this question shows you how to:

Read from files

Parse words cleanly

Handle casing issues (such as "Apple" vs "apple")

Use dictionaries (such as Counter in Python)

Use string operations and loops

This basic logic fuels massive systems—such as processing millions of tweets, YouTube comments, or support requests in real time.

Learning Insights
This code reinforces your hold on:

File I/O operations (opening, reading, closing files)

String manipulation (tokenizing, comparing words)

Basic data structures (arrays, maps, counters)

Case-insensitive comparison methods

Processing punctuation and whitespaces cleanly

Although the logic is simple, the idea is scalable and powerful. The same idea can be applied to create a word cloud generator, auto-summarizer, or tag recommender.

Interview & Real-World Use
In coding interviews, interviewers often ask questions such as "find the most common word", "verify frequency of a keyword in a file", or "count frequency of a word in a document". These questions are very frequent—particularly in string or file operation-based rounds.

In actual-use scenarios, this code might be included in:

Autocomplete logic in search bars

Dashboards for text analytics

Keyword filters in emails

Document indexing software

SEO keyword audits for blogs
One of the most basic programming tasks is to count the occurrence of a word within a file, particularly in text processing, document analysis, and keyword optimization. Whether you're creating a search function, content cleaning, or reviewing analysis, this idea is helpful. The examples in C, C++, Java, and Python are introductory, extremely concise, and complete, which will make it easy for you to master the art of word counting. Grasping this logic is instrumental in becoming proficient in file handling, string operations, and solving actual coding problems.