Hello all, I am not taking a class or asking for help with homework. I am attempting to learn C++ on my own and I do not understand the logic within one of the sample programs within my book.
#include <iostream>
#include <string>
int main()
{
using namespace std;
cout << "Enter a word: ";
string word;
cin >> word;
//physically modify string object
char temp;
int i, j;
for (j = 0, i = word.size() - 1; j < i; --i, ++j)
{
temp = word[i];
word[i] = word[j];
word[j] = temp;
} //end block
cout << word << "\nDone\n";
return 0;
}
Here is the logic part that I don't understand. Within the for loop when you set word = word[j], aren't you setting the first letter to the last letter and then inserting it into temp as well? In the sample run of the program they enter parts and the end result is strap. The program is supposed to spell the word backwards but with the code why isn't the the last letter of the word entered into temp as a result of temp = word and next the first letter being inserted as a result of word[j] = temp? It almost seems to me that the word[j] = temp; is not needed. If anyone can offer insight I would greatly appreciate it.