Computer Science Canada

How to teach nested loops?

Author:  Zeroth [ Mon Oct 20, 2008 3:37 pm ]
Post subject:  How to teach nested loops?

Right now, I am a TA for a couple of first year cosci courses, and some of my students are having a bit of difficulty grasping how nested loops run. I was just wondering if anyone has any advice on what kind of analogies, samples, have worked?

Author:  jbking [ Mon Oct 20, 2008 3:43 pm ]
Post subject:  RE:How to teach nested loops?

Looping over all the elements of a 2-dimensional array would be one example where you'd have a nested loop.

Alternatively, for an n-dimensional array it could be kind of scary for some I'd think. Wink

Also along these lines, matrix multiplication would be a bit more concrete if they are familiar with matrix algebra.

Author:  Vermette [ Mon Oct 20, 2008 6:07 pm ]
Post subject:  RE:How to teach nested loops?

A 2d array would be ideal imo, but the concept of such a thing itself might be a little alien. You could use as a real world example a set of i numbered cardboard boxes with j books in each. Show them a nested array in psuedocode to read the title of all the books.

Author:  wtd [ Mon Oct 20, 2008 7:02 pm ]
Post subject:  RE:How to teach nested loops?

For concrete counting loops, try expanding the outer loop out as it would appear if the code were written linearly.

Author:  gitoxa [ Mon Oct 20, 2008 9:36 pm ]
Post subject:  RE:How to teach nested loops?

I think a good way to show how nested loops work would be to set up a multiplication table.
Simple, easy, fast. Chances are if they don't understand nested loops, they haven't touched 2d array yet.

Author:  [Gandalf] [ Tue Oct 21, 2008 5:56 am ]
Post subject:  RE:How to teach nested loops?

Make sure they understand why the second for loop is executed for each iteration of the first, and that it has to be this way to work as expected.

Author:  Zeroth [ Mon Oct 27, 2008 11:40 am ]
Post subject:  Re: How to teach nested loops?

Thanks for all the advice guys. Working with the teacher of the course, I developed a rather effective and graphic example of code that shows how Nested loops work. Outer loop iterated from 100-199, and the inner loop iterated through letters in an array. It would print out the number, and then each letter in the array is printed, all in one line. I had a lot of "OH!"'s . Always a good sign.

Author:  syntax_error [ Mon Oct 27, 2008 4:57 pm ]
Post subject:  RE:How to teach nested loops?

This maybe late; however, seeing how we learned it and it worked wonderfully [in our class], tell them to use a tracing table like actually do the table step by step, simple but clean.


: