Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a C++ function that will reverse the characters in a C++ string. The funct

ID: 3762071 • Letter: W

Question

Write a C++ function that will reverse the characters in a C++ string.

The function prototype is:

void reverse( char word[] )

Note: - This function cannot have any local variables inside the function that are arrays.

An Algorithm is outlined below:

Declare two integer subscripts... left and right
Use a loop to find the position in the word array where '' is located
Set right to be one less than than this
Set left to 0
Start second Loop
switch word[left] with word[right]
inc   left by 1
decr right by 1
End loop

Consider this sample word containing the string "together"
...the 't' character is the first char but in position 0
...the NULL character "/0" is the 9th char but in position 8
left will be 0, right will be 8
pass 1="RogetheT" left = 1 right = 7
pass 2="rEgethOt" left = 2 right = 6
pass 3="reHetGot" left = 3 right = 5
pass 4="rehTEgot" left = 4 right = 4

...loop ends when left is greater than right

You may use the following C++ shell...

#include
using namespace::std;
const int MAX_SIZE = 15;     // Max word size of word, 14 chars plus ''
void reverse(char word[]);    // function prototype

void main()
{

char word[MAX_SIZE];
cout << endl << "Enter a word : "; cin >> word;
cout << "You entered the word " << word << endl;
reverse(word);
cout << "The word in reverse order is " << word << endl;

}//END MAIN

void reverse(char word[])
{
// you cannot have any local array variables inside this function

}

Explanation / Answer

// Example program
#include <iostream>
using namespace::std;
const int MAX_SIZE = 15;     // Max word size of word, 14 chars plus ''
void reverse(char word[]);    // function prototype

int main()
{

char word[MAX_SIZE];
cout << endl << "Enter a word : "; cin >> word;
cout << "You entered the word " << word << endl;
reverse(word);
cout << "The word in reverse order is " << word << endl;
return 0;
}//END MAIN

void reverse(char word[])
{
// you cannot have any local array variables inside this function
int len;
for(len=0;word[len]!='';len++){}
int left,right;

right = len-1;
left=0;
char temp;
while(1)
{
    if(left>right)
    {
     break;
     }
     temp = word[left];
     word[left]=word[right];
     word[right]=temp;
     left++;
     right--;
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote