Create a free account on Computer Sir Ki Class and unlock access to valuable learning resources.
Exam Paper Downloads: After registering and logging in, you can download exam question papers in PDF format to practice and prepare for your exams.
Student Support: Get assistance with your doubts, queries, and questions related to your studies. Our support is here to help you understand topics and resolve your learning difficulties.
Register today and make your exam preparation easier and more effective!
Problem Statement - Word count assuming well formed sentence
Write a program to count words in a given input sentence by a user, assuming that the sentence is well formed in a way that there are no initial or leading spaces and no extra spaces between words.
Related codes are those codes where similar programming concepts are in use. They are different from alternate codes in the sense that they may not have same purpose and results.
:
Run Output
Input a sentence (Less than 100 chars): Today I met a very decent person
No. of words in given sentences = 7
char str[101]; cout<<“Input a sentence (Less than 100 chars): ” ; cin.getline(str,80);
Collecting user input string. char array size is 1 more as space for null termination is given if full 100 character sentence is given.
int wc=0; //Word count variable wc initialised to 0. for(int i=0;str[i]!=”;++i) //Loop till end of sentence by checking up to null termination character { if(str[i]==’ ‘) wc++; //word count is increase as soon as space character is found in the string. }
cout <<“No. of words in given sentences = “<<wc+1<<endl;
Since there would be no space after the last word so counted spaces are increased by 1 to account for last word. Remember that we are talking of well formed sentences.
Notes
This code is quite condition specific. If enter is given directly without giving any word then it gives output as 1.
It also gives incorrect output for extra spaces any where in the sentences.
Independent punctuation can also be counted as words.