QBasic Program to Count the Number of Words in a Sentence

Write a QBasic program to count the number of words in a sentence.

For example,

Input
My Name is John Smith
Output
5

Method 1

The number of words in a typical sentence is one more than the number of spaces ( ” ” ) in a sentence. In this method, we use a loop to count the number of spaces in the sentence then add 1 to it to get the number of words.

QBasic – Count Number of Words in a Sentence

CLS
INPUT "Enter a Sentence: ", str$
no_of_space = 0

FOR i = 1 TO LEN(str$)
  IF MID$(str$,i,1) = " " THEN
    no_of_space = no_of_space + 1
  END IF
NEXT i

PRINT "No of Words: "; no_of_space + 1
END

QBasic – Count Number of Words in a Sentence using Function

DECLARE FUNCTION count_no_of_words(str$)

CLS
INPUT "Enter a Sentence: ", str$
PRINT "No of Words: "; count_no_of_words(str$)
END

FUNCTION count_no_of_words(str$)
no_of_space = 0
FOR i = 1 TO LEN(str$)
  IF MID$(str$,i,1) = " " THEN
    no_of_space = no_of_space + 1
  END IF
NEXT i
count_no_of_words = no_of_space + 1
END FUNCTION

Method 2

There is one problem with the previous program. The program will give the wrong answer if

  1. There are multiple spaces between 2 words.
  2. There are spaces at the beginning of the sentence.
  3. There are spaces at the end of the sentence.

To solve this problem,

  1. We ignore the spaces at the beginning of the sentence.
  2. We ignore the spaces at the end of the sentence.
  3. Consecutive spaces are only counted once.

QBasic – Count Number of Words in a Sentence

CLS
INPUT "Enter a Sentence: ", str$
no_of_space = 0

FOR i = 1 TO LEN(str$)
  IF MID$(str$,i,1) = " " THEN

    IF i > 1 THEN
      no_of_space = no_of_space + 1
    END IF

    WHILE i <= LEN(str$) AND MID$(str$, i, 1) = " "
      i = i + 1
    WEND

    IF i = LEN(str$) + 1 THEN
      no_of_space = no_of_space - 1
    END IF

  END IF
NEXT i

PRINT "No of Words: "; no_of_space + 1
END

QBasic – Count Number of Words in a Sentence using Function

DECLARE FUNCTION count_no_of_words(str$)

CLS
INPUT "Enter a Sentence: ", str$
PRINT "No of Words: "; count_no_of_words(str$)
END

FUNCTION count_no_of_words(str$)
no_of_space = 0

FOR i = 1 TO LEN(str$)
  IF MID$(str$,i,1) = " " THEN

    IF i > 1 THEN
      no_of_space = no_of_space + 1
    END IF

    WHILE i <= LEN(str$) AND MID$(str$, i, 1) = " "
      i = i + 1
    WEND

    IF i = LEN(str$) + 1 THEN
      no_of_space = no_of_space - 1
    END IF

  END IF
NEXT i

count_no_of_words = no_of_space + 1
END FUNCTION

Output

output

Read

Leave a Comment