Reputation: 37
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);
}
}
Upvotes: 0
Views: 628
Reputation: 327
You need to remove return keyword, Bcz void type they can't return anything that why you're getting the warring.
Follow the below code maybe that help you find your solution.
- code
void string_rec(int num, char ch1, char ch2)
{
if (num == 0)
return;
else
{
printf("%c",ch1);
string_rec(num-1, ch1, ch2);
printf("%c%c", ch2, ch2);
}
}
Upvotes: 0
Reputation: 16876
It's not going there because return
stops the function. The second printf
is unreachable. Remove that 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');
}
Also, since the function is defined as returning void
, change the return 0;
above to return;
. If you want, you can also simplify it like this:
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);
}
Upvotes: 8