I need to write a function that receive two arguments, n and 2 characters, from void main and then to print the first character n times and the second character n*2. I can only use recursion, not strings or anything more advanced. I tried different variations but after the recursion the prog isn't going down to the statement of printf to print ch2 twice. can someone help?
Thanks in advance.
#include<stdio.h>
void string_rec(int num, char ch1, char ch2)
{
if (num == 0)
return 0;
else
{
printf("%c",ch1);
return string_rec(num-1, ch1, ch2);
printf("%c%c", ch2, ch2);
}
}
Run Code Online (Sandbox Code Playgroud)
它不会去那里,因为return停止了该功能。二printf是遥不可及。删除那个return。
void string_rec(int num, char ch1, char ch2)
{
if (num == 0)
return;
else
{
printf("%c", ch1);
string_rec(num - 1, ch1, ch2); // don't return here
printf("%c%c", ch2, ch2);
}
}
int main() {
string_rec(5, 'a', 'b');
}
Run Code Online (Sandbox Code Playgroud)
此外,由于该函数被定义为返回void,请将return 0;上述更改为return;。如果你愿意,你也可以像这样简化它:
void string_rec(int num, char ch1, char ch2)
{
if (num != 0)
return;
printf("%c", ch1);
string_rec(num - 1, ch1, ch2);
printf("%c%c", ch2, ch2);
}
Run Code Online (Sandbox Code Playgroud)