Nested loops sequence logic in c#

Viewed 37

i need help to understand the logic sequence of this c# code. What i dont understand is, a) why after condition (currentLoops == numberOfLoops) is true and return. The value of currentLoops changing from 2 to 1. which i think currentLoops value should be 2 because NestedLoops(currentLoops + 1).

b) why after condition in for loops is met (counter <= numberOfLoops) the base value of counter changing from 1 to 2 thus make loops[0] = 2;

i already use debugger but it seems that the logic doesnt make any sense to me.

class RecursiveNestedLoops
{
    static int numberOfLoops;
    static int numberOfIterations;
    static int[] loops;
    static void Main()
    {
        
        numberOfLoops = 2;
        numberOfIterations = 4;
        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]);
           
        }
        
    }
}
0 Answers
Related