Re-Arranging a String Imput
Author |
Message |
JamesV
|
Posted: Tue Sep 28, 2010 1:11 pm Post subject: Re-Arranging a String Imput |
|
|
Re-Arranging a String Imput
This is my first program in my programming class I havent been able to get.
The question is as reads:
Have the user input a word of any length. The program should display the word with each letter moved to the left 1 position. Repeat this procedure until the original word is restored.
Eg. If input was: "math"
Then Output:
athm
thma
hmat
math
I realise that I need to use i for statment, but nothing seems to be working for me.
Thanks for the help! |
|
|
|
|
|
Sponsor Sponsor
|
|
|
DemonWasp
|
Posted: Tue Sep 28, 2010 6:49 pm Post subject: RE:Re-Arranging a String Imput |
|
|
Well, first, think about this: how many times are you going to output your word? Once per letter in the word, right?
Since you start on the next letter each time, let's iterate a variable called "startingNumber" from 1 to length ( word ). This should be pretty simple.
Now, inside that "outer" for-loop, we need to actually output the word starting from that position.
There are simpler / easier ways to do the following, so if you come up with something better, by all means go ahead. I'll walk you through the most obvious solution.
Let's say we're partway through the word. The word is "buffalo" and our startingNumber is 5, so we should start our output with the fifth letter (a). We want to output from position 5 to the end of the word, position 7. But wait, length ( word ) is 7! What a coincidence!
Take a moment and you should be able to convince yourself that this always works out.
So we'll have a for-loop inside the "outer" loop that starts at startingNumber and ends at length ( word ). Then, all it has to do is output the letter at that position in the word (you should have been taught how to do this already).
So we've printed the second part of the original word. What about the first?
Well, we'll have to start at the first character and print until just before the one we started at, right?
By now, that should sound an awful lot like:
for i : 1 .. length ( word ) - 1 |
|
|
|
|
|
JamesV
|
Posted: Fri Oct 01, 2010 10:19 am Post subject: Re: Re-Arranging a String Imput |
|
|
Thank you for your help!
I ended up figuring it out, without using for i : 1 .. length ( word ) - 1
If you have any suggestions or shorter code, please feel free to share.
Here is my code:
Turing: | var word : string
var y : int := 1
put "Enter a word"
get word
cls
for i : 1 .. length (word )
put word (i .. *) ..
if i > 1 then
loop
put word (1 .. y )
y := y + 1
exit when y > 0
end loop
else
put " "
end if
end for
|
|
|
|
|
|
|
|
|