Loop

The Bast Loop Statement Out Of For, While, Recursion

Purpose Most programming languages provide for, while, recursion loop statements. Which one is best? for I know how many repeat needed Cannot repeat with certain condition (need to use if and break) Hard to use previous result to next repeated loop Good usage example : print numbers in array. while I do not know how many repeat needed repeat with certain condition Hard to use previous result to next repeated loop Good usage example : count how may words you typed recursion I know how many Stack Memory that will use repeat with certain condition Easy to use previous result to next repeated loop Good usage example: find 88th’s Fibonacci number additional considerable conditions Does your programming language provide tail recursion Program environment such as embedded, Android, or Web Conclusion

Loop vs. Recursion

Definition Saperate big problem into small repeated parts and solve the problem. All Recursion can be converted to Loop. Good and bad points Loop Recursion intuitive complicated Long codes short codes good readability bad readability use less stack memories use much stack memories very low possiblity to get Stack overflow Stack overflow if too mcuh call very low possiblity to get overhead issue overhead issue: call function repeatly will make program slow each level of variable state will not saved each level of variable state will saved because of stack Actual code We should write recursion because it is good for reading and fixing it.

Tail Recursion

Definition A method of recursion optimization Principle When there is recursion, the recursive class remain in stack memory and it will cause overflow. The tail call elimination is created for fixing the overflow issue. If the reucursive class return everything at last, the class does need to remain in stack memory. Other Names tail call elimination tail call optimization How to Change return part of recursion to call function only.