+ 6
Can someone explain this recursive to me?
#include<stdio.h> #include<stdlib.h> int recurse(int n); int main(){ printf("%d",recurse(5)); return 0; } int recurse(int n){ if(n<=1) return 20; return(2+recurse(n-1)); }
13 ответов
+ 10
Mik_RDC
recurse(5)
2 + recurse(4)
2 + 2 + recurse(3)
2 + 2 + 2 + recurse(2)
2 + 2 + 2 + 2 + recurse(1)
2 + 2 + 2 + 2 + 20
= 28
+ 6
Mik_RDC
Working process will be same just value will be change based on (n - 1)
5 + recurse(4)
5 + 4 + recurse (3)
5 + 4 + 3 + recurse (2)
5 + 4 + 3 + 2 + recurse (1)
5 + 4 + 3 + 2 + 20
= 34
+ 4
Thank you Mr AJ
But if the last line was:
return(n+recuse(n-1));
Program will work the same or change ?
+ 4
the stdlib is unused.
we have a recursive function, it takes an int, and returns an int.
we give it five, it will keep calling itself if the input is greater than one. (the base case / end of recursion).
if the input is 1 or less, it will return 20.
if the input is greater than 1, it will return 2 plus calling itself with the same input minus 1.
--------------------------------
print(r(5))
r(5) + r(4) + r(3) + r(2) + 20
2 + 2 + 2 + 2 + 20
output:
28
+ 4
if the input is 1 or less it will just return 20 (base case to end the Recursion).
you can use any number like 0, 1, 40, any number as you need.
+ 4
Thank to all help me
+ 3
It will become
5 + 4 + 3 + 2 + 20
= 34
+ 3
G'day Mik_RDC that 20 at the end is strange.
It must be part of the aim of the program, eg each person costs $2 and the first person in the taxi costs $20.
+ 3
Mik_RDC
20 at the end because on (n <= 1) function will return 20 so this is not a strange thing.
When n is 0 then else will not execute so further execution will stop there and final result will be print
+ 2
Waiting your help...
+ 2
I know factorial , but this recurse complicated me sure , am fixed twenty why 20 in last
+ 2
normally the recursive decreases the number but here there is a 20 at the end
+ 2
recurse(5)
2 + recurse(4)
2 + 2 + recurse(3)
2 + 2 + 2 + recurse(2)
2 + 2 + 2 + 2 + recurse(1)
2 + 2 + 2 + 2 + 20 // base condition start work and return back control
= 28