In this article, we will write an Algorithm to count the number of words in a sentence and try to explain it in as simple words as we can.
Algorithm to Count no. of Words in Sentence for Beginners:
1 2 3 4 5 6 7 8 9 10 11 | Input sentence Read characters from 0 to EOL(End of Line) character for 'sentence' and store the count in variable 'sentence_length' Initialize i=0, words_count=1; Repeat Until i<=sentence_length if character at i position is space(' ') then words_count=words_count+1; i=i+1 end if print "Number of words is" + words_count |
Output:
1 2 3 4 | Input: This is my House Number of words is 4 |
C++ Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | #include <iostream> using namespace std; int main() { char str[80]; cout << "Enter a string: "; cin.getline(str,80); int words = 0; // Holds number of words for(int i = 0; str[i] != '\0'; i++) { if (str[i] == ' ') //Checking for spaces { words++; } } cout << "The number of words = " << words+1 << endl; return 0; } |
Python Code(for):
1 2 3 4 5 6 7 8 9 10 11 12 | # Python program to Count Total Number of Words in a String str1 = input("Please Enter your Own String : ") total = 1 for i in range(len(str1)): if(str1[i] == ' ' or str1 == '\n' or str1 == '\t'): total = total + 1 print("Total Number of Words in this String = ", total) |
pseudocode of square and cube
alert (6)