### Need help reversing a word

So I missed a lecture where the professor went over character arrays and now I don't really know what I am doing. Here are the instructions:

1. Start by prompting the user for a 5-letter word and saving it into a string. 2. Create a loop that iterates through every character cell and reverses the order of the word by saving it into an array of 5 characters.
3. Display the original word and the new reversed word.

Here's what I have so far. Any help is appreciated.

 ``12345678910111213141516171819202122232425262728293031`` `````` #include #include using namespace std; int main() { string word; char word2[5]; int x = 0; word2[0]=word[4]; word2[1]=word[3]; word2[2]=word[2]; word2[3]=word[1]; cout << "Enter a 5-letter word." << endl; cin >> word; cout << "The original word is " << word << "." << endl; while (x<5) { word2[x] = word[]; x=x+1; } cout << "The word in reverse is " << word2 << "." << endl; return 0; ``````
Hello, character arrays are simply arrays of characters. (Please review: https://www.codingunit.com/cplusplus-tutorial-character-sequence-using-arrays)

Here's my solution to your exercise:

 ``1234567891011121314151617181920212223242526272829303132333435363738394041`` ``````#include #include int main() { int c = 0; std::string word; char inversedWord[5]; std::cout << "Enter a 5-letter word: "; std::cin >> word; // Check if the word contains more than 5 letters while (word.length() > 5) { // If so, empty the word and prompt the user to enter another word // This loop structure will keep executing until the length of the word // is less than or equal to 5 word.empty(); std::cout << "Enter a 5-letter word: "; std::cin >> word; } // Loop through the original word starting from the last letter to the first letter // while assigning the letters to the inversedWord char array for (int i = word.length() - 1; i >= 0; --i) { inversedWord[c] = word[i]; c++; } std::cout << "The original and the reversed words: \n"; std::cout << word << "\n"; // Display the reversed word for (unsigned int i = 0; i < word.size(); ++i) { std::cout << inversedWord[i] << ""; } return 0; }``````
Last edited on
Thank you very much. Do you know how I could get it to output like this?:

The original word is horse
The word in reverse order is esroh
Highlight line 31 and 32 and paste the following:

 ``123`` ``````std::cout << "The original word is: "; std::cout << word << "\n"; std::cout << "The word in reverse order is: ";``````
Topic archived. No new replies allowed.