+ 1
Repeat letters
Let say you have a string “bye” And you want to print the duplicate of each letter output would be: Bbye Byye Byee Is it possible to code this using recursion? If not, how would you do it?
1 Réponse
+ 2
Yes, that's possible.
The following code will do as you describe except the first letter is repeated with the same case instead of switching from B to b.
The following code uses 2 recursive functions. One responsible for an individual line. The other for all the lines.
#include <iostream>
using namespace std;
void printWordWithRepeatStyle(const char * word, int repeatIndex) {
if (word[0] != '\0') {
// If this is the character to repeat, print it again.
if (repeatIndex == 0) {
cout << word[0];
}
cout << word[0]; // print current character.
// print rest of string.
printWordWithRepeatStyle(word + 1, repeatIndex - 1);
}
cout << endl; // break the line.
}
void printLinesWithRepeatStyle(const char *word, int line) {
if (word[line] != '\0')
{
printWordWithRepeatStyle(word, line);
printLinesWithRepeatStyle(word, line + 1);
}
}
int main() {
const char * word = "bye";
printLinesWithRepeatStyle(word, 0);
return 0;
}