Register Now

Login

Lost Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Login

Register Now

Welcome to All Test Answers

String Reverser C++

String Reverser
Write a recursive function that accepts a string as irs argument and prints the string in
reverse order. Demonstrate the function in a driver program.

Answer:



// String Reverser
#include <iostream>
using namespace std;

// Function prototype
void strReverse(char *);

int main()
{
	// Constant for array size
	const int SIZE = 81;

	// Array for string input
	char input[SIZE];

	// Get a string.
	cout << "What is your name? ";
	cin.getline(input, SIZE);

	// Display it backwards.
	cout << "Your name backward is "; 
	strReverse(input);
	cout << endl;
	return 0;
}

//********************************************************
// Function strReverse                                   *
// This function accepts a pointer to a null-terminated  *
// string as its argument. The function uses recursion   *
// to display the string backward.                       *
//********************************************************

void strReverse(char *str)
{
	if (*str == '\0')	// Reached the end of the string
	{
		return;
	}
	else
	{
		strReverse(str + 1);
		cout << *str;
	}
}



About

Leave a reply

Captcha Click on image to update the captcha .

error: Content is protected !!