Search code examples
c#for-loopnested-loops

How do nested for loops work in c#


I'm not sure how this code is compiled (using visual studio code just fyi)

int i,j;

for(i=0; i<=6; i++) {

    for (j=1; j<=7-i; j++) {

        Console.Write("*");

    }
    Console.Write("\n"); 
 }

My question is when the code is beginning to get compiled, the first for loop is tested and it will be true, then the nested for loop is then tested and it will be true so "Console.Write(" * "); is written. But then from here I do not understand what happens or why it happens. Does the compiler then run Console.Write(" \n "); or...


Solution

  • variables change like this.

    i = 0 : j changes from 0 to 7 ( 7- i, but i = 0)
    i = 1 : j changes from 0 to 6 (7 - i, i = 1)
    .
    .
    .
    .
    i = 6: j changes from 1 to 1 (7 - i, i = 6)
    

    in each i-loop you're printing j-loop and a new line character.

    |j-loop|i-loop|
    |******|'\n'  |
    

    So, you will get the output,

    ******* 
    ****** 
    *****
    ****
    ***
    **
    *