This is a C++ Program to Find the Number of Words in a Given Sentence.
The program takes a string and counts the number of words in it.
1. The program takes a string.
2. Using a for loop, the number of spaces in the string are counted.
3. The total number of words will be number of spaces plus 1.
4. The result is printed.
5. Exit.
Here is the source code of C++ Program to Find the Number of Words in a Given Sentence. The program output is shown below.
#include<iostream>
#include<string.h>
using namespace std;
int main ()
{
char str[50];
int count = 0, i;
cout << "Enter a string : ";
gets(str);
for (i = 0; str[i] != '\0';i++)
{
if (str[i] == ' ')
count++;
}
cout << "Number of words in the string are: " << count + 1;
return 0;
}
1. The user is asked to enter a string and stored in the array ‘str’. A variable ‘count’ is initialized as 0.
2. Using for loop, for every space(‘ ‘) in the string, count is incremented.
3. The loop continues till the end of the string.
4. Increment the value of count by 1 and then the result is printed, which is the total number of words.
Case 1 : Enter a string : Mosaic Number of words in the string are : 1 Case 2 : Enter a string : 1 2 3 4 5 Number of words in the string are : 5 Case 3 : Enter string 1 : The sun shines brightly. Number of words in the string are: 4
Sanfoundry Global Education & Learning Series – C++ Programs.
To practice all C++ programs, here is complete set of 1000+ C++ Programming examples.
- Get Free Certificate of Merit in C++ Programming
- Participate in C++ Programming Certification Contest
- Become a Top Ranker in C++ Programming
- Take C++ Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Practice Programming MCQs
- Buy C++ Books
- Buy Computer Science Books
- Apply for Computer Science Internship
- Apply for C++ Internship