For this lab, you will use the following code snippet and fill in the
function bodies for reverse_index
and
reverse_pointer
. You can also view this code seperately in
lab1_handout.cpp. To copy and paste this
code into a file on Sleipnir when using vi, be sure to turn off indenting
using the following command:
:set pasteWhen you are done pasting, you can turn indenting back on for coding using:
:set nopasteHere is the code provided in lab1_handout.cpp:
#include <stdio.h> #include <iostream> using namespace std; // This recursive function uses array subscripts to print the string in reverse // Input: a character array that terminates with '\0' // an integer indicating the current character to inspect // Output: the string in reverse void reverse_index(char s[], int start); // This recursive function uses pointer arithmetic to reverse the string // Input: a pointer to the current character to inspect // Output: the string in reverse void reverse_pointer(char *s); int main() { char *str = "This is a test."; printf("Original string: %s\n", str); printf("Reverse using array subscripts: "); reverse_index(str, 0); printf("\n"); printf("Reverse using pointers: "); reverse_pointer(str); printf("\n"); return 0; }The pseudocode for the recursive function as discussed in class is:
if current character is the null character ('\0') return, do nothing (base case) else call reverse with the next character in the string print the current character return out of the functionYou will need to code
reverse_index
using the subscript operator
to access each character. The parameter int start
is the current
subscript in the string. You will be changing this parameter with each
recursive call.
The reverse_pointer
function instead uses a pointer to the
current character in the string, which is the char *s
parameter.
You will be incrementing this pointer with each recursive call. You will need
to dereference the pointer to compare it to '\0' and to print out the character.
Email the completed lab1.cpp to me on Sleipnir.