219k views
3 votes
Design a simple algorithm for the string-reverse problem (given a string of characters, your algorithm should return the string with the characters reversed). Example input "CAT" → output "TAC". Don't forget to consider special cases!

User Mjmitche
by
4.4k points

1 Answer

5 votes

Answer:

Simple algorithm for string-reverse problem:

Start

Declare a string variable

Declare position variables i, j and temp

Input the string to be reversed

Find length of string

Position i at first and j at last element of string

Swap the positions i and j of string element using loop and temp

Increment i and decrement j at each iteration

Store the swapped position of string

Display the reversed string in output

Stop

Step-by-step explanation:

The corresponding C++ program of above algorithm is:

#include<iostream> //to use input output functions

using namespace std; // to access objects like cin cout

int main () { //start of main function

string str; //declare a string

char temp; // declare a temp variable

int i, j; // declare position variables

cout << "Enter a string : "; //prompts user to enter a string

getline(cin, str); //reads the input string

j = str.size() - 1; //positions j at the last character of str

for (i = 0; i < j;) { //positions i at first character of str, checks if i is less then j

temp = str[i]; //assigns the element of str at ith position to temp

str[i] = str[j]; //swaps elements at positions i and j

str[j] = temp; //assigns the element of str at jth position to temp

i++; //increments i

j--; } //decrements j

cout << "\\Reverse string : " << str; //displays the reversed string

return 0; }

The program along with the output is attached.

Design a simple algorithm for the string-reverse problem (given a string of characters-example-1
User Lakshay
by
5.2k points