Skip to main content

Problem Solving Example: Reversing a string

Sequencing principles demonstrated

A variation.

Prerequisite content

Prior to asking the learner to solve a problem, the following content is provided.

About For-loops

A for loop runs a specific number of times. The general form of a for loop in C++ is:

for (<starting statement>; <test condition>; <do statement>) {
...
}

<starting statement> will be run prior to the loop and is used for initialization purposes. <test condition> is an expression. The loop will keep running while this expression evaluates to true. <do statement> is the statement to run after each execution of the loop.

The effect of this staement will eventually cause test_condition to evaluate to false.

The code below illustrates traversing a string txt in the forward direction using a for loop:

for (int i = 0; i < txt.length(); i++)
cout << str[i] // Display the character at position i

Problem

Given a string txt, print the string in reverse.

Solution

for (i = txt.length(); i >= 0; i--)
cout << txt[i] // Display the character at position i

Analysis

This is variation of the code presented earlier:

for (int i = 0; i < txt.length(); i++)
cout << str[i] // Display the character at position i