Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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
- Read the sentence character by character using a while loop
- Count total characters (excluding spaces) and words
- Calculate average by dividing character count by word count
- 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
doubleensures 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.
Advertisements
