Write a C program to calculate the average word length of a sentence using while loop

In C programming, calculating the average word length of a sentence involves counting the total characters (excluding spaces) and dividing by the number of words. This program demonstrates how to use a while loop to process user input character by character and calculate the average word length.

Syntax

while(condition) {
    // Process each character
    // Count characters and words
}

Algorithm

  1. Read the sentence character by character using a while loop
  2. Count total characters (excluding spaces) and words
  3. Calculate average by dividing character count by word count
  4. Return the average as a double value

Example: Calculate Average Word Length

This program reads a sentence and calculates the average length of words using a while loop −

#include <stdio.h>

double calculateWordLength(const char *stmt) {
    int charCount = 0;
    int wordCount = 1;
    
    while (*stmt != '
' && *stmt != '\0') { if (*stmt != ' ') { charCount++; } else if (*stmt == ' ') { wordCount++; } stmt++; } return (double)charCount / wordCount; } int main() { char stmt[100]; int i = 0; double avgLen; printf("Enter a sentence: "); while ((stmt[i] = getchar()) != '
') { i++; } stmt[i] = '\0'; avgLen = calculateWordLength(stmt); printf("Average word length: %.2f
", avgLen); return 0; }
Enter a sentence: Tutorials Point is the best resource
Average word length: 5.17

How It Works

  • The main function reads input character by character using getchar() in a while loop
  • The calculateWordLength() function processes each character to count letters and words
  • Non-space characters increment charCount
  • Space characters increment wordCount
  • The average is calculated as (double)charCount / wordCount

Key Points

  • The while loop continues until a newline character is encountered
  • Word count starts at 1 to account for the last word (no trailing space)
  • Type casting to double ensures floating-point division
  • The program handles sentences with multiple spaces correctly

Conclusion

This program effectively demonstrates using while loops for character-by-character processing in C. The average word length calculation provides useful text analysis functionality with proper handling of spaces and word boundaries.

Updated on: 2026-03-15T13:45:37+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements