how to simulate loops for/while using a recursion

This is a discussion on how to simulate loops for/while using a recursion within the C Programming forums, part of the General Programming Boards category; how to build for and while loops using a recursion?...

  1. #1
    Banned
    Join Date
    Oct 2008
    Posts
    1,535

    how to simulate loops for/while using a recursion

    how to build for and while loops using a recursion?

  2. #2
    Registered User
    Join Date
    Dec 2006
    Location
    Canada
    Posts
    3,183
    Code:
    void countdown(int n) {
         if (n == 0) return;
         printf("%d\n", n);
         countdown(n - 1);
    }
    Why would you want to do this, though? It's much simpler with loops, and you won't need to worry about stack overflow.

  3. #3
    Banned
    Join Date
    Oct 2008
    Posts
    1,535
    thanks

  4. #4
    Registered User
    Join Date
    Nov 2008
    Posts
    158
    Code:
    void LoopFor ( int y, int n){
            int x;
    
            for (x=y; x<=n; x++)
               LoopFor (x, y, n);
    }
    
    void main (void)
    {
        LoopFor (0, 100);
    
    }
    Last edited by sergioms; 01-06-2009 at 03:26 PM. Reason: ehuehehhu =p

  5. #5
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by sergioms View Post
    Code:
    void LoopFor ( int y, int n){
            int x;
    
            for (x=y; x<=n; x++)
               LoopFor (x, y, n);
    }
    
    void main (void)
    {
        LoopFor (0, 100);
    
    }
    That won't compile, and recurses 99! times, I should think [which will probably blow the stack to smithereens].

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Template Recursion Pickle
    By SevenThunders in forum C++ Programming
    Replies: 20
    Last Post: 02-05-2009, 08:45 PM
  2. power of 2? without loops or recursion
    By rahuls in forum C Programming
    Replies: 8
    Last Post: 03-20-2003, 04:10 PM
  3. a simple recursion question
    By tetra in forum C++ Programming
    Replies: 6
    Last Post: 10-27-2002, 09:56 AM
  4. When to use recursion ?
    By Unregistered in forum C Programming
    Replies: 7
    Last Post: 01-06-2002, 09:36 PM
  5. selection sorting using going-down and going-up recursion
    By Unregistered in forum C Programming
    Replies: 1
    Last Post: 11-02-2001, 01:29 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21