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.

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 of activities on this page