Reputation: 341
I am currently finding it hard to grasp the output from a simple nested for-loop
int result = 0;
for (int i = 1; i <= 3; i++)
{
for (int j = 1; j <= 2; j++)
{
result = result +i;
}
}
Console.WriteLine(result);
Which gives the output of 12. I understand that the result for j is 1 and 2, but just cannot grasp why the final result is 12 instead of 3?
Can someone explain please?
Upvotes: 1
Views: 53
Reputation: 2703
run that test and you will see:
class Program
{
public static void test()
{
int result = 0;
for (int i = 1; i <= 3; i++)
{
Console.WriteLine("i["+i+"] : ");
for (int j = 1; j <= 2; j++)
{
Console.Write(" when : j["+j+"]");
Console.WriteLine("Adding " + i + "to" + result);
result = result + i;
}
}
Console.WriteLine(result);
Console.ReadLine();
}
static void Main(string[] args)
{
test();
}
}
Upvotes: 1
Reputation: 1500135
Your outer loop has three iterations. On each of those three iterations, you're running the inner loop:
for (int j = 1; j <= 2; j++)
{
result = result +i;
}
Given that the body of the loop doesn't depend on j
, and the inner loop will always run twice, we can replace the whole of the inner loop with:
result = result + i;
result = result + i;
Or to simplify it:
result = result + (i * 2);
So now the whole code is equivalent to:
int result = 0;
for (int i = 1; i <= 3; i++)
{
result = result + (i * 2);
}
Console.WriteLine(result);
So after the first iteration of the outer loop, result
is 2 (we've added 2 to 0).
After the second iteration of the outer loop, result
is 6 (we've added 4 to 2).
After the third iteration of the outer loop, result
is 12 (we've added 6 to 6).
Upvotes: 2
Reputation: 23721
You are adding the value of i
to result
each iteration of the inner loop, and the inner loop runs 3 times (the 3 iterations of the outer loop). Therefore the first time the inner loop runs, you add 1
twice, the second time the inner loop runs you add 2
twice, and the final time it runs you add 3
twice:
result = 1 + 1 + 2 + 2 + 3 + 3 = 12
Upvotes: 2