Recursive calls and Practice Problems

2022. 6. 4. 00:37Coding - C

Recursive Call: A function calling itself repeatedly. There must be some kind of end code, or it will cause an infinite loop. This is easier for us to make, but it takes a lot of time compared to for and while loops because this is one command of repeatedly calling itself while for the loops, each loop is one command. 

 

This is a for loop, and we can see that each time the loop goes on, the value of i will be added to result. 

http://www.tcpschool.com/c/c_function_recursive

 

This is the same code with the above, except for that we used recursive call. The format is like rSum(5) = 5 + rSum(4) = 5 + 4 + rSum(3) and so on, until it becomes 5 + 4 + 3 + 2 + rSum(1). The if statement in this is needed because without it, the code won't stop, as it will keep calling itself. 

http://www.tcpschool.com/c/c_function_recursive

 

 

Practice Problem

Problem #1: Factorials

 

This is the for loop for the factorials, and if int n = 5, then the loop will go on, accumulating the value of i to v, being 1*2*3*4*5. 

This is the same factorial calculator, but by using recursive calls. Every time the loop goes on and calls itself, it will call the value 1 less than the previous value and multiple that. For example, if n is 5, then it will first call 5, then 4, which multiplies to 5, then 3, 2, 1, then end, resulting in 120.

 

Problem #2: Fibonacci Sequence

 

Fibonacci sequence is the one that adds the previous two values to get the next one. For example, 1, 1, 2, 3, 5, 8, 13... This for loop calculates the fibonacci sequence, as starting from i = 2, as two values are needed for the first value, ans is the addition of the two values. If n is less than 2, it will jsut return that value because we can't create the first fibonacci value. This is what I attempted, but failed.

This is also a code for fibonacci sequence. Each time, the last's value will go into the variable tmp, changing every loop. Then the cur, which will change every loop, will be saved into last, then the tmp's value will be accumulated to cur every loop. This is the right answer, and I copied from the internet.

Ironically, the recursive call for fibonacci sequence is way easier, as if the value is 1 or 2, we can jsut return 1, and we can just call the previous and the 2nd previous value over and over again to get the fibonacci sequence.