Wednesday, July 27, 2016

Program to reverse a string in qbasic with explanation


cls
input"enter the string to reverse";a$
for i = 1 to len(a$)
q$=mid$(a$,i,1)
m$=q$+m$
next i 
print m$
end

                    
len(a$)  = to return the number of characters from the string
mid$(a$,i,1) = to replace a string portion with another string .



program explanation :

the program is started with the input.
then the program goes to a loop which starts from 1 and ends with the length of input.
there is the use of mid$ . why? let me give you a example : if you input a string "closure" then loop is started from 1 to length of  closure i.e 7 and mid$ takes out :

loop count                                     string


1                      c
2                      l
3                      o
4                      s
5                      u
6                      r
7                      e

after that a new string variable is created which stores in given way

if a$="ram" then

1                      p$=r
2                      p$=a
3                      p$=m


m$ where m$ is a new string

m$=a$+m$ 
so that

count                 m$

1                      r 
2                      ar
3                      mar

loop is ended and m is printed. 




No comments:

Post a Comment