132k views
2 votes
B. Debug the following program

CLS
REM reversing a word
INPUT "Enter a word"; W$
FOR P= LEN (W$) TO 1
E$ = MID (W$, 1, P)
R$ = E$ + R$
NEXT P
PRINT "Reverse word is "; E$
END​

User Phoebe
by
8.6k points

1 Answer

3 votes

Step-by-step explanation:

There are several issues with the program that prevent it from correctly reversing a word. Here is a corrected version of the code with comments explaining the changes:

CLS

REM reversing a word

INPUT "Enter a word"; W$

R$ = "" REM Initialize R$ to an empty string

FOR P = LEN(W$) TO 1 STEP -1 REM Use STEP -1 to iterate backwards

E$ = MID(W$, P, 1) REM Get the character at position P

R$ = R$ + E$ REM Add the character to the end of R$

NEXT P

PRINT "Reverse word is "; R$ REM Print R$, not E$

END

Here are the changes that were made:

Initialize R$ to an empty string before the loop, since we want to build the reversed word from scratch.

Use STEP -1 to iterate backwards through the characters of the word, starting from LEN(W$) and ending at 1.

Get the character at position P using MID(W$, P, 1) instead of MID(W$, 1, P), which was incorrect. We want to get the character at the current position, not the first P characters of the string.

Add the character E$ to the end of R$ using the concatenation operator +.

Print R$ instead of E$ to display the reversed word.

With these changes, the program should correctly reverse the input word.

User Denis Sadowski
by
7.7k points