# Tag Info

56

Show then how the loop can be unfolded into a while loop: int i = 0 // Step 1 while (i< 100) { // Step 2 // Do something i++ // Step 3 } Explain that the order is derived from that unfolding. You could start out by only teaching while loops, forcing them to make these while loops with iterators, then showing that for loops are a condensed of ...

28

I think the advantages are huge, overwhelming. They avoid off by one errors - the bane of the novice programmer needing to allocate an explicit iterator - avoiding adding names to the namespace. They enable thinking about iteration at a higher level than just counting compact coding I use them whenever available. The collection knows its members....

26

I know I'm coming late to this party but this is a really good question and I think it deserves a really good treatment. The original for loop, the one with the semicolons in it, is amazingly flexible, powerful, and confusing as all get out. It is seldom taught well, it is a very easy place for bugs to hide, and it is not going away. To master it you must ...

25

I teach for loops using the following pseudocode, which we then translate into actual code: for (initialization; condition; update) { statement; } This logic helps justify why the order goes 1, 2, 4, 3 to start. I explain it as follows: a variable can only be initialized once so it happens first and never again. After that the variable is tested against ...

17

I prefer to teach while loops as part of my unit on if/else statements since the syntax and thought process are virtually identical. I then introduce for loops when teaching lists (in Python) or arrays (in Java). With for loops, language impacts which style you likely use first. With Python, I use the for item in list structure first. In Java, I use the ...

10

I think foreach loops are great, and are almost always preferred over for loops. While for loops are fundamental material and definitely should be covered, they're sort of infrequently used in practice -- when iterating, we almost always iterate over lists and other collective (and it's generally considered bad practice to modify a data structure you're ...

9

There is much discussion here about how a traditional for seems more powerful than a foreach, but a traditional for with sentinel value can only be used to iterate over an indexable collection. Data structure like sets and maps are prevalent, and iterating over them by index would be technically and conceptually absurd. (You've already outlined places where ...

9

It's about setting boundary conditions first. Provide them with a more concrete example, like filling a glass of milk. You kind of need a glass or container (let me know the next time you pour milk right on the counter) and that glass is some amount full. We'll just treat it as empty. Then, you stop filling the glass when it's full (or half full or whatever),...

8

tl;dr– A for loop is just a while loop that has extra slots for a pre-loop statement and a post-loop-run statement. Since they're pretty much the same thing just written differently, a for loop is best understood as syntactic sugar that's useful when it increases the readability of the code. Sometimes new programmers are worried about performance, thinking ...

8

Theoretically, I teach the while loop first. Others have already explained how and why, but I'll go ahead with an example: void showRating( int rating ) { int i = 0; while ( i < rating ) { putchar( '*' ); ++i; } putchar( '\n' ); } Some of the examples will be better expressed as for loops, and that's where I introduce ...

8

Use the for when you know how many times to execute it, such as counting, or iterating over an array. Use while or do .. while if you don't. The choice between while and do .. while is if you need to do the loop one time before the test use do ... while otherwise use while. A full explanation can be found on Stack Overflow in this accepted answer.

8

All of the IF and Loop structures are based on two fundamental operations: Test and Branch. The only difference between an IF-Else and a Loop of any kind is whether you branch downward or back to the top. On a flow chart this just knocks you in the nose: the only difference is the arrowhead on one line. When something so varied and complex can be reduced to ...

7

I teach them while loops, for loops, and for each loops; in that order. What I've found is that while loops tend to make the most sense for students. The idea of while I'm hungry, eat pizza is something they understand. But, forgetting to change the condition is really common so we wind up with a lot of infinite loops. I sell for loops as a loop where is ...

7

I think the way to teach it is not by talking about order of operation, but by teaching the overall concept of a looping. The for header contains the steps that are generally common to looping: initialize iteration variables, test whether the loop should proceed, and update variables between iterations. As others have suggested, you could start by teaching ...

7

The Dutch National Flag problem is linear in running time. Essentially sort an array with only 3 distinct values each of which may appear 0 or more times. (not length 3). You are allowed only one pass over the array, so the solution is a single while loop with some prior initialization. It was probably originally posed by Dijkstra. It is mentioned in David ...

7

A variant on the ENIGMA machine encryption works well in a single loop, and is sufficiently complex to give students a real challenge. The core idea of the ENIGMA machine for this assignment is that (1) a number is given as an initial key, and (2) every prior letter used influences how the next letter will be encrypted. So, use a modular circle of ...

6

If I'm interpreting your question correctly you'd like real life examples that translate to code. Maybe something like the following. You want to drive or ride your bike to the ice-cream shop a few miles away. You don't know how far it is exactly but you will recognize it when you get there (while), VS You want to ride your bike 15 miles out and then ...

6

I used to have a role where I supported college students in CS1. I developed the following exercises to address this exact issue: Counting code executions Text version: How many times do each of the following pieces of code execute? int sum = 0; int i; for(i = 1 /*A*/; i < 5 /*B*/; i = i + 1 /*C*/) { sum = sum + i; /*D*/ } Hint: translate a while ...

6

Your pupils are already be doing nested loops. foreach week { foreach weekday{ wake up clean teeth eat breakfast goto school foreach period{ goto class do lesson } go home do evening stuff } do saterday stuff do sunday stuff } What about some formulaic music. Music has a lot of ...

5

I find that a useful way of teaching the different types of loops is simply giving examples and asking student to express them more concisely. For example, I'd give my students a loops of the format: i = 0 while (i < 100) { # Some code here i++ } Then I'd ask them to simplify it to something more like: for (i=0; i < 100; i++) { # Some code ...

4

To do something like the following with foreach... // Exercise 3: for (int j = 1; j < myDoubles.size(); j++){ if (myDoubles.get(j) < myDoubles.get(j-1)) return false; return true; consider the following, expressed as a static method public static boolean isSorted(ArrayList<Integer> values){ boolean first = true; Integer ...

4

Maybe the for (int i=0; i<10; i++) { ... } loops seems funny when you compare it to the "interval" loop of other languages, like Pascal's for I:=1 to 10 by 1 do but the C for loop was designed as a much more general linguistic mechanism than loops with counters. The objective was to keep all elements of the "control" of the loop ...

4

I introduce loops by showing them loops in the physical world. For example I have a student take 7 steps - counting loop. An other student walks to a specified point - while/until loop. We talk about how these loops work in our minds before we talk about how they work in code. Many daily activities can be discussed in terms of loops and we discuss several. ...

4

I am not an educator, but I hope my answer will be helpful. In B.A.S.I.C, which I learned as a child, there are "for-to-step" loops and their argument order is the same as C style languages. I have to remember them like this in order to keep it right for myself. This is QBASIC FOR counter = start TO end [STEP] [Statement Block] NEXT counter or FOR ...

4

Well, you may want to do this outside. You may want to have a lot of time, and for some, you might want to have medical personnel available. To really do it as an active learning exercise, you need three student monitors, one for each loop, who will keep count and signal each iteration and the end. First suppose that the <doSomething> action is the ...

4

Perhaps you are creating a problem where none exists. You seem to be assuming that looping needs to be covered all at once and all together, rather than distributed over some some longer range interspersed with other topics. The two fundamentally different kinds of looping are definite in which the program knows how many iterations are necessary prior to ...

4

While your ideal order makes sense, you really should try to plan the course based on the limitations of the language that you're working with. In this case, instead of thinking about the different conceptual loops, you should think about the different loop syntaxes that the language provides. In this case, the order in @Bryan R's answer (if/else -> while ->...

4

Note that the following are intended for the instructor, not always directly for the student. If used well they require some analysis, not just coding, from the student. Use the fact that the sum of the first n odd numbers is $n^2$ to compute the integer square root of an integer. Test data should include 63, 64, and 65 to catch edge cases. This can be ...

4

I'm adding in a second answer to look at a few heftier assignments, worthy of a lab. These were created by a truly fantastic colleague of mine. The game Nim is excellent for a loop with no arrays. You can use just three variables to keep track of the state of the game, and a variable and an if statement to deal with the player. (Kids at this level will ...

3

Another way of looking at this is to explore what is missing or lost at various stages: In Java For each: for ( String s : < some iteratable collection > ) foo(); loses the index of the loop. It never has one unless you add it. for (int i = 0; i< n; i++) foo(); loses the index after the loop when completed, while other loops preserve it. ...

Only top voted, non community-wiki answers of a minimum length are eligible