7.3. Traversal through a string with a loopΒΆ

A lot of computations involve processing a string one character at a time. Often, they start at the beginning, select each character in turn, do something to it, and continue until the end. This pattern of processing is called a traversal. One way to write a traversal is with a while loop:

Activity: CodeLens 7.3.1 (stringWhileLoop)

This loop traverses the string and displays each letter on a line by itself. The loop condition is index < len(fruit), so when index is equal to the length of the string, the condition is false, and the body of the loop is not executed. The last character accessed is the one with the index len(fruit)-1, which is the last character in the string.

Write a while loop that starts at the last character in the string and works its way backwards to the first character in the string, printing each letter on a separate line. For reference, the CodeLens above shows an example of a word printed letter by letter.

Before you keep reading...

Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.

Show Comments

Another way to write a traversal is with a for loop:

Each time through the loop, the next character in the string is assigned to the variable char. The loop continues until no characters are left.

You have attempted 1 of 7 activities on this page