In programming, each character of a string has an assigned index, starting from zero to length – 1. Index 0 starts from the first character and the last character's index is length – 1. Special characters and white spaces also he an assigned index.
For example: If we consider the string "Hello World";
Characters H e l l o W o r l d Index 0 1 2 3 4 5 6 7 8 9 10Here, the length will be 11 and the indexing will be from 0 to 10.
In the following algorithm, we will be using the same logic to reverse the given string.
Algorithm to reverse a string: Step 1. Start Step 2. Read the string from the user Step 3. Calculate the length of the string Step 4. Initialize rev = “ ” [empty string] Step 5. Initialize i = length - 1 Step 6. Repeat until i>=0: 6.1: rev = rev + Character at position 'i' of the string 6.2: i = i – 1 Step 7. Print rev Step 9. Stop Explanation:The algorithm starts by taking the string to be reversed as input from the user. After that, the length of the string is calculated and stored in a variable, say 'length'. To store the reversed string, we are initializing a variable 'rev' as an empty string.
We will reverse the string by accessing the string from its last character. To do so, we are starting a loop with initial value i = length – 1. In this loop, we are reversing the string, one character at a time by performing: rev = rev + character at position 'i'. Here, the '+'' operator performs the concatenation of the characters of the string in reverse order. After that, the value of 'i' is decremented by 1. This loop runs until i >= 0. Once this loop ends, we he the reversed string in the variable rev.
Flowchart to reverse a string: Remove WaterMark from Above Flowchart Try Out our String Reverser Tool Online