C PROGRAM
Program to count number of words in a sentence |C Program|
Introduction
Understanding and manipulating strings is a crucial skill in programming, and counting words in a sentence is a common task. In this blog post, we'll explore a C program that counts the number of words in a sentence, unraveling the code to provide insights into string handling and word counting.
Code
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main() {
char s[200];
int count = 0, i;
printf("Enter a sentence:\n");
scanf("%[^\n]s", s);
for (i = 0; s[i] != '\0'; i++) {
if (s[i] == ' ' && s[i + 1] != ' ')
count++;
}
printf("Number of words = %d\n", count + 1);
getch();
}
Output
Enter a sentence:
The quick brown fox jumps over the lazy dog.
Number of words = 9
Explanation
1. Header Files:
The program includes the standard input/output header <stdio.h>, the console I/O header <conio.h>, and the string manipulation header <string.h>.
2. Main Function:
The main function initiates the program.
Users are prompted to enter a sentence, and the input is stored in the character array s.
3. Word Counting Logic:
The program utilizes a for loop to iterate through each character in the input string.
It checks for spaces (' ') and ensures that consecutive spaces are not counted as separate words.
The variable count keeps track of the number of spaces encountered, which corresponds to the number of words minus one.
4. Result Display:
The program prints the total number of words in the entered sentence.
5. User Interaction:
Users receive clear feedback about the number of words in the provided sentence.
Conclusion
This C program provides a concise and efficient solution for counting the number of words in a sentence. Understanding how to navigate and manipulate strings is essential for various programming tasks.
Experiment with different sentences, analyze the flow of the program, and consider optimizations or alternative approaches. This example serves as a valuable introduction to string handling and word counting in programming. Happy coding!
Post a Comment
0 Comments