0

Nested for loplops

hi . im a new c# learner and i have a problem with nested for loops and i dont know how it works .do first loop need to complete before it goes to another for or first inneresr loop ends or all togheter run one step. please help. thank you.

29th Apr 2017, 5:13 PM
Abolhasan Me
Abolhasan Me - avatar
5 Answers
+ 19
Nested for loop, let's take an example- for(int m=0;m<10;m++) { for(int n=0;n<10;n++) { Console.WriteLine("Hello"+m+" "+n); } } In above example, First of all the outer loop will start with value m=0, then inner loop will execute for n=0 to n=9, after then the outer loop complete its first iteration. Then again outer loop execute for m=1, again inner loop execute for m=1 and n=1 to n=9, then outer loop finish its second iteration. This is how inner loop runs 10 times from 0 to 9 for each outer loop iteration which is also from 0 to 9, i.e. total iterations of inner loop= 10×10=100
29th Apr 2017, 5:24 PM
Sachin Artani
Sachin Artani - avatar
+ 16
@Abolhasan, Exactly 😉 You get it.
29th Apr 2017, 5:56 PM
Sachin Artani
Sachin Artani - avatar
+ 14
run this code to see how it works: https://code.sololearn.com/cb0hMIeZBb3H/#cs For each iteration of outer loop inner loop runs all its iterations. For example: for(int x=0; x<5; x++){ for(int y=0; y<5; y++){ // do something } } for each iteration of x, y runs 5 iterations. So, y runs 5 times 5 in the example. Hope this helps.
29th Apr 2017, 5:38 PM
Ulisses Cruz
Ulisses Cruz - avatar
+ 1
thanks a lot. it helps me understand that. ok now for three loops . the first loop start with 1 iteration.second loop run with 1 iteration and third loop run 10timed for example and again second loop start its second iteration then third loop again have 10 iteration and... after second loop run 10 time the first loop start its second loop and all that happen again. is it true?
29th Apr 2017, 5:54 PM
Abolhasan Me
Abolhasan Me - avatar
+ 1
thank you so much.♡♡♡♡♡
29th Apr 2017, 5:57 PM
Abolhasan Me
Abolhasan Me - avatar