I was a Computer Science Student. But i didn’t coded much. For loops are quite simple to me and if it was nested for loop, my head starts to spin.
Tell me how can i master in nested for loops. Where shall i start to practice?
Once my class staff told us that any application which uses less for loops is the most efficient one. Is that real?
Suggest me any book or paper on for loops or links!!
deceze:How about you give us an example nested loop and tell us what you don't understand about it?
I cannot able to explain it fully. Whenever i start to think of a function which needs 2 for loops(nested), firts two iterations goes smooth. After that if i add any other calculation inside the inner loop, after a second its all gone. I cannot continue. So, then i have to run the loop in PC as smaller one, then i build it to a fully functional one.
Ok, Leave me. What you all do, i mean, how you start if you have to build a function which needs more than 2 nested for loops.
Suggest me any book or paper on for loops or links!!To solidify your understanding of 2 for loops, you can try practicing at http://www.codingbat.com/java – moreover, there’s instant and (mostly) thorough grading!
String-3 or Array-3 problems can use 2 for loops.
If you have a 2D array, and you need to reach all the indices, you could use 2 for loops. Thus, similarly, if you have a 3D array, you can use 3 nested loops. Remember that the inside of a loop ends before the outside — so if you have 2 loops, the inside code would loop for the amount of time the inner loop specifies, for the number of times that the outside loop specifies. You can draw a diagram:
The visual representation:
If I assign letters:
with X1 being the first part of X (before the nested for loop) and X2 the second part (after the nested for loop), the order of execution is:
A1, C1, G, H, C2, D1, I, J, D2, A2, B1, E1, K, L, E2, F1, M, N, F2, B2
So you don’t need to picture n-dimensional arrays when you’re looking at for loops.
Once my class staff told us that any application which uses less for loops is the most efficient one. Is that real?
If your for loop involves calculating a value like a formula, it would be faster and probably more efficient to just plug things into the formula. But generally the slowest Big O algorithm would affect the program’s efficiency the most – so a stand-alone for loop that depends on
n(as its stop condition) wouldn’t slow down a program much more if it also had nested for loops that depend onn.