Click here to Skip to main content
15,892,222 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,

I am trying to better understand nested loops.

Say I have a for loop for time, this instance a parent loop as follows:

C#
int i;
int j;

for (int i = 0; i <=99; i++)
{
  for (j = 0; i <=99; j++)
  {
    blahh...
  }
}


In this instance does this mean that for every repition of variable i, variable j gets executed?

A tad confusing.

Cheers
Keil
Posted
Updated 28-Apr-14 17:51pm
v2
Comments
Laiju k 28-Apr-14 23:46pm    
for i=0 => j 0-99 loops works
then for i=1 it continues till i=99 j=99
Аslam Iqbal 29-Apr-14 0:21am    
Inner loop is infinite..................................................

All the steps in the inner loop gets executed for every single execution of the outer loop.
 
Share this answer
 
Quote:
In this instance does this mean that for every repition of variable i, variable j gets executed?
Yes, you are right. Ideally it should happen.

For every i, inner loop should continue till j is 99.

But you have a problem here. The inner loop checks the condition i<=99, which is wrong. You should check j<=99.
C#
for (j = 0; i <=99; j++)
 
Share this answer
 
v2
Comments
Аslam Iqbal 29-Apr-14 0:20am    
Inner loop continues to infinite time. here for (j = 0; i <=99; j++) no increment for i. So, i<99 is always true.
Laiju k 29-Apr-14 0:28am    
you are right to the question.but we have to use j in the condition instead of i.
then only it will work on j's values else it is infinite as you said.
Yes, my mistake. Just a eye slip. :P
Updating my answer now.
add console write line as below, you can see the how each iteration values are changing

C#
for (int i = 0; i <=99; i++)
{
  for (j = 0; j <=99; j++)
  {
    Console.WriteLine(string.Format("i={0}, j={1}", i,j));
  }
}
 
Share this answer
 
v2
It will execute 10000 (100X100) time!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900