Reputation: 13
I have a question about for loop; Code is below
for (int i = 0; i <= 3; i++)
{
for (int j = 0; j < 2; j++)
{
Console.WriteLine("J");
}
Console.WriteLine("I");
}
Output of this code is;
J J I J J I J J I J J I
My question is : at first for loop "i" is 0 and condition is true so, loop goes to second loop j is 0 and condition is true. It writes "J", then j++ is working and now J is 1. Second loop is writing "J" again and then increase it to 2 so second for loop condition is false and it goes to first for loop, It writes "I" and then increases the first loop i is 1 right now so first for loop condition is true and it goes second one: Question starts here. J was 2, how is the J went 0 after first loop condition true again and write 2 J again?
I hope I can tell you my problem properly. Thank you so much
Upvotes: 1
Views: 144
Reputation: 216273
Your code, after the external loop ends the first iteration, it continues and re-execute the inner loop. But the re-execution means a reinitialize for the indexer variable with j=0 so it prints again two times the value "J"
You can see the difference in these two examples. The first one is your current code, the second one is without reinitializing the j variable
void Main()
{
Test1();
Test2();
TestWithWhile();
}
void Test1()
{
for (int i = 0; i <= 3; i++)
{
// At the for entry point the variable j is declared and is initialized to 0
for (int j = 0; j < 2; j++)
{
Console.Write("J");
}
// At this point j doesn't exist anymore
Console.WriteLine("I");
}
}
void Test2()
{
// declare j outside of any loop.
int j = 0;
for (int i = 0; i <= 3; i++)
{
// do not touch the current value of j, just test if it is less than 2
for (; j < 2; j++)
{
Console.Write("J");
}
// After the first loop over i the variable j is 2 and is not destroyed, so it retains its exit for value of 2
Console.WriteLine("I");
}
}
Finally a third example shows using two nested while loops to mimic the same logic applied with the for loops in your code. Here you can see the flow that leads to the reinitializations of the variable j
void TestWithWhile()
{
int i = 0; // this is the first for-loop initialization
while (i <= 3) // this is the first for-loop exit condition
{
int j = 0; // this is the inner for-loop initialization
while (j < 2) // this is the inner for-loop exit condition
{
Console.Write("J");
j++; // this is the inner for-loop increment
}
Console.WriteLine("I");
i++; // this is the first for-loop increment
}
}
Upvotes: 1