Hot answers tagged

52

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 those ...


26

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....


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 ...


16

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 ...


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, ...


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.


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

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 the for ...


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

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

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 ...


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

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

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

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

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 together on one ...


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

Part 1 When I introduce the foreach loop, I do it the context of a lecture on ArrayLists and wrapper classes. I first just kinda slip it in unannounced: double total = 0.0; for (double currentValue : myDoubles) total += currentValue; System.out.println(total); Then we turn to it and begin to break it apart a little. I first compare it to for (int j ...


3

You should definitely teach foreach loops. Why? Foreach loops are the main type of loop in Python. Python is the awesomest. Therefore foreach loops are important. All "joking" aside, foreach loops are super useful - I use them all the time. They're the difference between x = 0 while x < len(list): print(list[x]) x+=1 and for i in list: ...


3

However, don't neglect the fact that the first and last of the three sections between the parentheses can have (in C, anyway) multiple statements separated by commas (comma is an operator in C). int i, j; for(i = 0, j = 100; i < 100; i++, j = 2 * j + i){ //do something strange }; You can write quite a lot of a program in a single for ...


3

I love thesecretmaster's answer of showing the mapping between the two loops (and I will almost certainly do that in the future). However, as an AP Computer Science A teacher, I teach in Java, and there is a subtle trap in saying that for (int i = 0; i < 100; i++){ // do something } is equal to int i = 0; while (i< 100) { // do something i+...


3

You could use introduce elementary (one-dimensional) cellular automata. Basically, you represent a single row of cells as a simple array. Then you write a function that takes an array and applies the rules of the cellular automata to each cell (usually based on the old value of the cell and its two neighbors) to return a new array representing the next ...


3

This is a really good place to introduce boolean variables (or just to use them, if they've already been introduced. It also introduces the idea of descriptive variable names. user_wishes_to_continue = True while user_wishes_to_continue: answer = raw_input("Do you wish to continue?") if answer != "yes": user_wishes_to_continue = False ...


2

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. Many of ...


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