Reverse a string.
Example 1:
Input:
str = "hello"
Output: "olleh"
Example 2:
Input:
str = "world"
Output: "dlrow"
1. Input Reading:-
The program starts by declaring a string variable str.
It uses cin to read a string input from the user and stores it in the str variable. The user enters a
string, and that string becomes the value of str.
2. String Length Calculation:-
After reading the input string, the code calculates the length of the string using the length() function and
stores it in the integer variable n. This step is necessary to determine the length of the string, which is
needed for iterating over its characters.
3. Reversing the String:-
The code enters a while loop with the condition i < j, where i starts at 0 and j starts at n - 1. These two
pointers (i and j) are used to swap characters in the string to reverse it. Inside the loop, the swap
function is used to swap the characters at positions i and j in the string str. This effectively
reverses the characters at these positions. After the swap, i is incremented by 1, and j is decremented
by 1, bringing the pointers closer to each other for the next iteration.
4. Exiting the Loop:- The loop continues until i is no longer less than j. When i becomes
equal to or greater than j, the loop exits
because there are no more characters to swap.
5. Printing the Reversed String:-Finally, the code prints the
reversed string using cout.