In you code s
is a string
variable that holds some characters. And as you said you want to display its contents in reverse order.
In order to do that, you have to navigate through the contents of s
from back to front. To do that, as shown in your code you used for-loop
.
Let's say s
contains 10
characters. Since you are accessing your string s
back-to-front, the last character found at the 10 - 1 = 9th
index, because it starts counting from 0, not 1.
EDIT with Example
string original = "Hello";
string reverse;
for (int i = original.size() - 1; i >= 0; i--) {
reverse += original[i];
}
cout << reverse << endl;
As you can see in the above example, original
is a string
variable which holds five characters, and reverse
is also a string
variable which is about to hold the contents of original
in reverse order. In order to reverse the contents of original
, we must navigate through it back-to-front
.
original[4] = o
original[3] = l
original[2] = l
original[1] = e
original[0] = H
The above characters will be added one by one at each iteration of the for-loop as shown below:
reverse = ""; //it was empty first
reverse = reverse + original[4]; // now it holds the last character -> o
reverse = reverse + original[3]; // now it holds the characters -> ol
reverse = reverse + original[2]; // now it holds the characters -> oll
reverse = reverse + original[1]; // now it holds the characters -> olle
reverse = reverse + original[0]; // now it holds the characters -> olleh