Advertisement
Vermiculus

Loops and Recursion

Apr 30th, 2012
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.62 KB | None | 0 0
  1. // Loop structures can always be expressed as recursion
  2.  
  3. // Here's an example with a simple while loop:
  4. method() {
  5.     while(condition) {
  6.         do_stuff();
  7.     }
  8.     // return stuff
  9. }
  10.  
  11. // And its recursive counterpart:
  12. method() {
  13.     if(condition) {
  14.         do_stuff();
  15.         method();
  16.     }
  17.     // return stuff
  18. }
  19.  
  20. // Same thing, but with a do-while loop instead:
  21. method() {
  22.     do {
  23.         do_stuff();
  24.     } while (condition);
  25.     // return stuff
  26. }
  27.  
  28. // And its recursive counterpart:
  29. method() {
  30.     do_stuff();
  31.     if(condition) {
  32.         method();
  33.     } else {
  34.         // return stuff
  35.     }
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement