In: Computer Science
Reversing certain segments of the alphabet, using a recursive function. (C++)
1. Obtain the following string: abcdefghijklmnopqrstuvwxyz (as input or using initialization)
2. Using recursion, write a reverse function that reverses the characters in a string or character array given two indices (starting and ending). The string or the character array should reflect the reversal.
3. Read indices as input 11,18 (i.e. letters 12,19)
4. Call the reverse function to reverse letters: 12-19
5. Read indices as input 4,22 (i.e. letters 5,23)
6. Call the reverse function to reverse letters: 5,23
7. Using the reverse function, reverse the alphabet
8. Print the reversed string or character array.
Your output should contain:
abcdefghijksrqponmltuvwxyz
abcdwvutsrqponmlkjihgfexyz
zyxwvutsrqponmlkjihgfedcba
NOTE: your recursive function should modify the original string passed in as an argument, NOT make additional copies of the original string
What I've got so far:
(Just a prototype) -- Doesn't completely follow the instructions, Just showing the general direction I've been trying to go in.
// I'm a bit confused on how to transform the string from "abcdefg" to "abedcfg"
// Alright, Here it is...
# include
# include
using namespace std;
void reverse(string& alpha, int x, int y)
{
if ((x - 1) == y)
{
return;
}
cout << alpha[y - 1];
reverse(alpha, x , y - 1);
}
int main()
{
string alpha = "abcdefg";
reverse(name, 3, 5);
// My output: edc
// The output I wanted: abedcfg ( When cout << alpha )
return 0;
}
Code:
# include<iostream>
#include<string>
using namespace std;
void reverse(string& alpha, int x, int
y) //function reverse
{
char t;
if ((x>y))
{
//here does not use any additional string.
return;
}
t=alpha[x];
alpha[x]=alpha[y];
alpha[y]=t;
reverse(alpha, x+1 , y - 1);
}
int main()
{
string alpha;
int u,k;
cout<<"enter
string:";
//reading input string.
cin>>alpha;
cout<<"enter starting index:"; //reading
starting index.
cin>>u;
cout<<"enter ending
index:"; //reading ending index.
cin>>k;
reverse(alpha, u, k);
cout<<endl<<"your modified string is
"<<alpha; //printing modified
string
return 0;
}
Output 1:
Output 2:
Output 3: