Search code examples
logicqbasic

How to count frequency of each letter of word in qbasic or c language?


Successfully counted each letter but letter order can't display sequentially as in word. For example- Input word-bbinood Output=b2i1n1o2d1

Here my program in qbasic:

INPUT "Enter the string:", A$
n = LEN(A$)

FOR i = 97 TO 122

    FOR j = 1 TO n
        IF CHR$(i) = MID$(A$, j, 1) THEN
            count = count + 1
        END IF
    NEXT
    FOR j = 1 TO n
        IF (MID$(A$, j, 1) = CHR$(i)) THEN
            PRINT CHR$(i), count
            j = n
        END IF

    NEXT

    count = 0
NEXT

Solution

  • Okay, here's code that should work in Qbasic.

    DEFINT A-Z
    DIM char(1 TO 255) AS STRING * 1
    DIM outp(1 TO 255) AS STRING
    INPUT "Type your string: ", inp$
    
    '**** Comment out the following line if you want upper and lower cases
    '**** treated separately:
    inp$ = LCASE$(inp$)
    
    FOR i = 1 TO LEN(inp$)
      char(i) = MID$(inp$, i, 1)
    NEXT i
    
    l = 0
    FOR i = 1 TO LEN(inp$)
      k = 1
      FOR j = 1 TO i - 1
        IF char(j) = char(i) THEN GOTO skplet
      NEXT j
      l = l + 1
      FOR j = i + 1 TO LEN(inp$)
        IF char(j) = char(i) THEN k = k + 1
      NEXT j
      outp(l) = char(i) + LTRIM$(STR$(k))
    skplet:
    NEXT i
    
    FOR i = 1 TO l
      PRINT outp(i);
    NEXT i
    

    Note that, as remarked in the comment, upper and lower case will be treated as the same letters as this answer stands. If you want them to be treated separately, simply delete or comment out the inp$ = LCASE$(inp$) line. Hope this helps!