+ 4

Please help me to correct my code

Recursive void function that print hello ntimes https://code.sololearn.com/czE7WqmwJ5aS/?ref=app

10th Feb 2020, 11:34 PM
Amal Gil
Amal Gil - avatar
10 Respostas
+ 5
If you reached zero, you have to abort the function: void count(int n){ if (n==0) { printf("there is nothing"); return; } else printf("hello\n"); count(n-1); }
11th Feb 2020, 12:21 AM
HonFu
HonFu - avatar
+ 14
count(n-1) for decrement n and output "hello" until n=0
12th Feb 2020, 1:33 PM
Hmd(inactive)
+ 12
You are welcome 😊
12th Feb 2020, 1:38 PM
Hmd(inactive)
+ 11
void count(int n){ if (n==0) printf("there is nothing"); else { printf("hello\n"); count(n-1); } } int main(){ int n; printf("entrer an integer :\n"); scanf("%d",&n); printf("we have :\n"); count(n); }
11th Feb 2020, 12:38 AM
Hmd(inactive)
+ 2
You can't print a void function. Just call the function because you have all print statements inside the function. if(n == 0) after printf() you should also stop the function otherwise you will get an infinite loop.
10th Feb 2020, 11:57 PM
Denise Roßberg
Denise Roßberg - avatar
+ 2
Thanks guys
12th Feb 2020, 1:37 PM
Amal Gil
Amal Gil - avatar
+ 1
How can I stop the function because I dropped in infinite loop Hello hello.......
11th Feb 2020, 12:07 AM
Amal Gil
Amal Gil - avatar
+ 1
Why please count (n-1)
12th Feb 2020, 1:25 PM
Amal Gil
Amal Gil - avatar
+ 1
##Are we should change the parameters while we are calling the recursive function Can we write count(n+1) ##So what the difference between count (n-1) and count (n+1) ##is the purpose only to avoid infinite loop
12th Feb 2020, 1:29 PM
Amal Gil
Amal Gil - avatar
+ 1
There are all sorts of recursive functions, but they have one thing in common: They need to have a base case, that determines when they should stop. Here the base case is (if n==0). So if n wouldn't decrease, the recursion would never end. If the base case was (if n>=1000), you could use (n+1) as well, but then (n-1) would be wrong (unless you'd start with n>=1000 of course 😉).
12th Feb 2020, 1:33 PM
HonFu
HonFu - avatar