Algorithm to Count number of Words in Sentence for Beginners

[5823 views]




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

Algorithm to Count no. of Words in Sentence for Beginners:

Step 1: Start Step 2: Input sentence Step 3: Read characters from 0 to EOL(End of Line) character for 'sentence' and store the count in variable 'sentence_length' Step 4: Initialize i=0, words_count=1; Step 5: Repeat Until i<=sentence_length 5.1 check if character at i position is space(' ') 5.1.1 then words_count=words_count+1; 5.2 i=i+1 Step 6: print "Number of words is" + words_count Step 7: stop

Example:

Input: This is my House Number of words is 4

Explanation:

In above algorithm, we take the sentence as an input from User and store it in variable named 'sentence'. Then we start reading each character of 'sentence' until EOL(End of Line Character) is encountered, by doing so we will count the number of characters present in the given sentence. In above example, the sentence_length will be 17

Now we initialize variable i=0 for iteration and words_count=1 to store the actual word count.

Now, iterate from i=0 to 'sentence_length' (i.e for our example it will be 0 to 17). For each iteration, we will check the character at ith position and see if it is a space (' '), if yes then we will increase words_count by 1.

By the end of iteration(i.e. when i=17, the words_count will be 4 as 3 spaces were encountered as per our example sentence. Now we just print 'words_count' variable value, which is our actual required value.

                 



Having Difficulty understanding above Algorithm and Flowchart? Buy my Personal Notes



Are You Good enough in Algorithms? Prove it!



Comments





Search
Get Answers to your Programming Questions


Recommended Deals ends in








Test Your Skills:

Search Tags

    Pseudocode to find number of words in sentence