Please send questions to
st10@humboldt.edu .
//-------------------------------------------------------------
// File: writeBackward.cpp
// Name: Sharon M. Tuttle
// last modified: 1-29-05
//
// Contract: writeBackward : string int -> void
//
// Purpose: write the first <charsToWrite> characters in string <str>
// in reverse order to the screen
//
// preconditions:
// * charsToWrite <= str.length()
// * charsToWrite >= 0
//
// postconditions:
// * the first <charsToWrite> characters in <str> are written
// in reverse order to the screen, but <str> is unchanged
//
// Examples: for string str1 = "hello there",
// writeBackward(str1, 11) should cause:
// ereht olleh
// ...to be written to the screen
// for string str2 = "",
// writeBackward(str2, 0) should cause:
//
// (nothing; the empty string) to be written to
// the screen.
// for string str3 = "f",
// writeBackward(str3, 1) should cause:
// f
// ...to be written to the screen.
//-------------------------------------------------------------
#include <iostream>
#include <string>
#include <cassert>
using namespace std;
void writeBackward (string str, int charsToWrite)
{
// assertions we can write to verify preconditions
assert(charsToWrite <= str.length());
assert(charsToWrite >= 0);
// base case #1: if no characters to reverse, write nothing
if (charsToWrite == 0)
{
return;
}
// base case #2: if 1 character to reverse, simply write
// that character
else if (charsToWrite == 1)
{
cout << str[0];
}
// recursive case: otherwise, write the last character,
// followed by the 1st (charsToWrite-1) characters
// written in reverse order
else
{
cout << str[charsToWrite-1];
writeBackward(str, (charsToWrite-1));
}
}