Respuesta :

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

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 << "\nReverse string : " << str;  //displays the reversed string

   return 0;  }

The program along with the output is attached.

Ver imagen mahamnasir
Q&A Education