jrliv
6/26/2017 - 5:45 PM

Example of using recursion with executing nested loops. From Fundamentals of Computer Programming with C# http://www.introprogramming.info/w

Example of using recursion with executing nested loops. From Fundamentals of Computer Programming with C# http://www.introprogramming.info/wp-content/uploads/2013/07/Books/CSharpEn/Fundamentals-of-Computer-Programming-with-CSharp-Nakov-eBook-v2013.pdf

static int numberOfLoops;
static int numberOfIterations;
static int[] loops;

static void Main()
{
  Console.Write("N = ");
  numberOfLoops = int.Parse(Console.ReadLine());
  Console.Write("K = ");
  numberOfIterations = int.Parse(Console.ReadLine());
  loops = new int[numberOfLoops];
  NestedLoops(0);
}

static void NestedLoops(int currentLoop)
{
  if (currentLoop == numberOfLoops)
  {
    PrintLoops();
    return;
  }
  for (int counter=1; counter<=numberOfIterations; counter++)
  {
    loops[currentLoop] = counter;
    NestedLoops(currentLoop + 1);
  }
}

static void PrintLoops()
{
  for (int i = 0; i < numberOfLoops; i++)
  {
    Console.Write("{0} ", loops[i]);
  }
  Console.WriteLine();
}

//  N = 2
//  K = 3
//  1 1
//  1 2
//  1 3
//  2 1
//  2 2
//  2 3
//  3 1
//  3 2
//  3 3