Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS235102 Data Structures Appendix 1 How to transfer a simple loop- expression to a recursive function (factorial calculation)

Similar presentations


Presentation on theme: "CS235102 Data Structures Appendix 1 How to transfer a simple loop- expression to a recursive function (factorial calculation)"— Presentation transcript:

1 CS235102 Data Structures Appendix 1 How to transfer a simple loop- expression to a recursive function (factorial calculation)

2 How To Transfer A Loop To A Recursive Program Step 1: Use if, label and goto statements to replace a loop statement a loop statement Step 2: Replace the initial assignment of loop statement as a function call and add statement as a function call and add necessary variables as arguments necessary variables as arguments Step 3: Replace the label statement as a recursive function function Step 4: Replace the incremental and goto statements as a recursive call as a recursive call

3 main() { int i, n, value; value = 1; for ( i<=n; ) { *value = *value * i; printf (“%d! = %d\n”, i, value); }} i=1; i++ The initial assignment is moved to the outside area of for loop conditional expression is placed in an if() statement incremental is placed at the end of for loop if (i<=n) { Add a label in front of the if statement and a goto statement at the end of if body goto L1; The block forms the recursive function L1: Replace the initial assignment of loop statement as a function call Replace the label statement as a recursive function name void factor(int i, const int n, int *value) { factor(1, n, &value); } Necessary variables as arguments factor(i+1, n, value); Replace the incremental and goto statements as a recursive call A simple loop program The final recursive function (call)


Download ppt "CS235102 Data Structures Appendix 1 How to transfer a simple loop- expression to a recursive function (factorial calculation)"

Similar presentations


Ads by Google