68.1k views
4 votes
Write a function to reverse a given string. The parameter to the function is a string. Function should store the reverse of the given string in the same string array that was passed as parameter. Note you cannot use any other array or string. You are allowed to use a temporary character variable. Define the header of the function properly. The calling function (in main()) expects the argument to the reverse function will contain the reverse of the string after the reverse function is executed.

User Kochez
by
4.4k points

1 Answer

3 votes

Answer:

Following are the program to this question:

#include <iostream> //defining header file

using namespace std;

void reverse (string a) //defining method reverse

{

for (int i=a.length()-1; i>=0; i--) //defining loop that reverse string value

{

cout << a[i]; //print reverse value

}

}

int main() //defining main method

{

string name; // defining string variable

cout << "Enter any value: "; //print message

getline(cin, name); //input value by using getline method

reverse(name); //calling reverse method

return 0;

}

Output:

Enter any value: ABCD

DCBA

Step-by-step explanation:

In the above program code, a reverse method is declared, that accepts a string variable "a" in its arguments, inside the method a for loop is declared, that uses an integer variable "i", in which it counts string value length by using length method and reverse string value, and prints its value.

  • In the main method, a string variable "name" is declared, which uses the getline method.
  • This method is the inbuilt method, which is used to input value from the user, and in this, we pass the input value in the reverse method and call it.
User Dbush
by
4.0k points