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.
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.
For any inquiry, Contact us at firstname.lastname@example.org