Recursion (slightly off-topic)

Discussion in 'C++' started by Gaijinco, Nov 20, 2005.

  1. Gaijinco

    Gaijinco Guest

    I'm trying to convert this:

    for(int i=0; i<5; ++i)
    for(int j=0; j<5; ++j)
    for(int k=0; k<5; ++k)
    cout << i+1 << j+1 << k+1 << endl;

    Into a recusive function. But I ended with:

    #include <iostream>
    using namespace std;

    void permute(int);
    int A[3];

    int main(){

    permute(0);

    return 0;
    }

    void permute(int n){

    for(int i=0; i<5; ++i){

    A[n]=i+1;

    if(n<3){
    permute(n+1);
    } else {
    for(int j=0; j<3; ++j)
    cout << A[j];
    cout << endl;
    }
    }
    }

    Which doesn't work! I'm lost here, could anyone give me a clue?
    Gaijinco, Nov 20, 2005
    #1
    1. Advertising

  2. Gaijinco

    Rade Guest

    > if(n<3){

    Probably:

    if (n+1 < 3) {
    Rade, Nov 20, 2005
    #2
    1. Advertising

  3. Gaijinco

    John C Guest

    You are very close! (but it's late and being the Saturday of a very long
    week, there is drinking involved)

    Shouldn't that be if(n<2)? If n==2 you will call permute(3) which will
    cause A[3] = I+1; and there ain't no A[3]

    On 11/19/05 8:37 PM, in article
    , "Gaijinco"
    <> wrote:

    >
    > void permute(int n)

    {
    >
    > for(int i=0; i<5; ++i)

    {
    >
    > A[n]=i+1;
    >
    > if(n<3) ////////////////////// if (n<2) here

    {
    > permute(n+1);
    > }

    else
    {
    > for(int j=0; j<3; ++j)

    {
    > cout << A[j];

    }
    > cout << endl;
    > }
    > }

    }
    John C, Nov 20, 2005
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Paul Kraus
    Replies:
    1
    Views:
    981
  2. John O'Conner
    Replies:
    1
    Views:
    466
    totojepast
    Jan 30, 2004
  3. PowerSlave2112

    A Legal Question (slightly off-topic)

    PowerSlave2112, Jan 25, 2005, in forum: HTML
    Replies:
    6
    Views:
    485
    Starshine Moonbeam
    Jan 26, 2005
  4. Ken Fine
    Replies:
    3
    Views:
    360
    Steven Cheng [MSFT]
    Jun 23, 2008
  5. Nick

    Slightly off-topic, but...

    Nick, Nov 15, 2009, in forum: C Programming
    Replies:
    2
    Views:
    314
Loading...

Share This Page