+ 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)); }

12th Feb 2022, 6:06 AM
Mik
Mik - avatar
13 odpowiedzi
+ 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
12th Feb 2022, 6:30 AM
A͢J
A͢J - avatar
+ 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
12th Feb 2022, 7:59 AM
A͢J
A͢J - avatar
+ 4
Thank you Mr AJ But if the last line was: return(n+recuse(n-1)); Program will work the same or change ?
12th Feb 2022, 7:50 AM
Mik
Mik - avatar
+ 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
12th Feb 2022, 8:00 AM
Mafdi
Mafdi - avatar
+ 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.
12th Feb 2022, 8:19 AM
Mafdi
Mafdi - avatar
+ 4
Thank to all help me
15th Feb 2022, 5:23 PM
Mik
Mik - avatar
+ 3
It will become 5 + 4 + 3 + 2 + 20 = 34
12th Feb 2022, 7:56 AM
Mafdi
Mafdi - avatar
+ 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.
12th Feb 2022, 9:12 AM
HungryTradie
HungryTradie - avatar
+ 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
12th Feb 2022, 2:32 PM
A͢J
A͢J - avatar
+ 2
Waiting your help...
12th Feb 2022, 6:07 AM
Mik
Mik - avatar
+ 2
I know factorial , but this recurse complicated me sure , am fixed twenty why 20 in last
12th Feb 2022, 8:13 AM
Mik
Mik - avatar
+ 2
normally the recursive decreases the number but here there is a 20 at the end
12th Feb 2022, 8:17 AM
Mik
Mik - avatar
+ 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
12th Feb 2022, 7:20 PM
Jai Kishan
Jai Kishan - avatar