What's a good example of a static factory method returning instances of subclasses? One benefit of having a class provide a static factory method rather than public constructors is the method can return an instance of a subclass.
For example, if the class Rectangle had a subclass Square, there could be a static method Rectangle.newInstance(int width, int length) that sometimes returned a Rectangle and sometimes a Square.
What is a compelling example of the benefit of this approach? Students could easily ask in this case why the client didn't call the Square constructor if the width and length are equal. (I can give them an answer to that question, but it would be better to have an example good enough that they wouldn't even ask.)
Edits
For those of you who answered that I shouldn't have a static factory method return an instance of a subclass, not only wasn't that my question but the great Josh Bloch considers that a positive use of static factory methods (Effective Java, Item 1). I recognize no higher Java authority, although you are free too.
For those who told me that a good use of static factory methods is that the programmer can choose their name, which is not the case with constructors, I already knew and teach that. (I'm not sure why you assumed I didn't.) If I wanted people's opinions on the best thing about static factory methods, I would have asked that, on Software Engineering Stack Exchange.
For those who answered the question I asked, thank you.

I don't have a good answer to this. However here are my thoughts.
Named constructors
A good use for static factory, is to implement named constructors: Java, C#, C++, et al do not have named constructors. However named constructors can be useful, as they allow you to document different ways of constructing an object. Therefore use a static factory, to create the object. The static factory will use private un-named constructors.
Problems with the pattern
However other uses of static factory seem to be an anti-pattern.
You now have a super-class depend on the sub-class. The sub-class already depends on the super-class.
The static constructor can also easily break the single responsibility principle: the class is a thing and a factory for a thing.


Explaining why arrays are important for statisticians I am a computer engineer, and I’m teaching computer sciences one hour per week to a student who failed her second-year university degree. She needed some help to have a better understanding of programming, and increase her grade in this field. Computer science is not the main subject of her degree which is based on maths and physics.

I asked her if she wanted to emphasise on a difficult subject for her, or if I should start from scratch and explain programming as if it was totally new for her. She chose the second solution, so I started to explain her the base of programming, binary, variables, functions, conditional statements, loops. And now I emphasis on the most common data structure ever, the array.

I teach her how to use an array, manipulate its element, etc...
As she had to use programming to solve problems of graph theory, physics measurements, and mathematical algorithms which use a lot of matrices and arrays, I spend about six hours to make her be more familiar with it.

I simplified it to make her use one-dimensional arrays with a simple algorithm, and she just told me that she can’t understand how arrays will be of any use for her, for her everyday life. She aims to get job in the field of statistics.

I explained to her, that she uses array everyday without thinking about it. For example when you log in a website, there’s somewhere an array (or an object) which stores your username, password, email, and compares it to what is stored in a database. But she didn’t feel very enthusiastic.

So  I can understand that not everybody enjoys programming, and as I am not a statistician I can’t really tell her about how useful this can be for a statistician.

What can I do to actually make her change her mind about programming or show her the use of it for a statistician ?

EDIT:
I work as Web developper so I am not used to statistics. I can't think about useful example or exercise to show her the usage of arrays in statistics.

EDIT:
She already saw by herself that was I taugh her about arrays is usefull in various situation. She saw that know, as she understood arrays, she can now solve problems she wasn't able to solve before.

If you are tutoring her, it is wonderful that you are trying to motivate the material in a practical way, but don't beat yourself up too much if you aren't that successful at persuading her. Some people just get themselves into a sort of myopic headspace where the only things that they need to learn are the exact operations that they will perform later on in their life.

However, it has been my experience that there is often something else going on in these situations. People aren't creating these excuses because of what will be practical in the future. They have no idea what the future holds. They actually create these utilitarian excuses simply because they don't find the topic intrinsically fun yet.

This also explains why you make no headway when you show her the utilitarian benefits; they aren't truly what is preventing her from diving in. Your best bet, then, is to show her why you think this whole field is amazing.

And if all else fails, go back to a utilitarian approach, but stick to the most direct reason: she needs this so that she will pass her class next semester.  That was a strong enough motivation for her to meet with you in the first place, so it should work out well enough to at least get you through the lessons.

Good luck!


Physical analogy to introduce a Delegate in .Net programming Delegates are strange beasts (think Pointers with aspirations) and I was planning to introduce them using a physical metaphor: a power strip. The power strip connects to an 'event' (wall socket) and has a 'signature' (the interface of the plug shape and parameters) and provides connectivity to multiple event-handlers (the sockets in the strip), but it doesn't actually "do anything". Other examples would be a USB Hub and a Network Switch (different 'signatures' / plug and socket interface). Delegates can be used for any sort of event situation, not only the Windows GUI, so they are a fairly open-ended idea. ("Can you say 'abstract'? I knew you could.")

This gives something that students can visualize for the terms of a Delegate: what it connects to, how it can provide for multi-cast events, and how methods connect to it. Does this seem like it will work, or is there a better way to introduce this highly abstract yet necessary programming concept?

I know that you are looking for a physical analogy, but I'd say I agree with @ctrl-alt-delor about the 'link to what they already know' part.

I usually start by introducing a simple algorithm, then show how that algorithm can be parameterized. Then we move on to OO, where I discuss how an algorithm can be parameterized with not just a value, but with a piece of code (i.e. creating an interface, and passing an implementation of that interface to a method). For the interface, I always use an analogy like USB.

Then we move on to the delegates, where I introduce delegates as if they were an interface with one method, Invoke(), and whatever you pass to the delegate gets called in that Invoke() method. Then we move on to delegate internals (how they are immutable, and multicast etc.) I also have examples and practices that we do to show them that every solution that uses a delegate can be translated into a more OO version using interfaces (again, referring back to interfaces).


How to introduce problem solving to primary school pupils? I'm interested into knowing your experiences about introducing problem solving to primary school pupils.

I'm a PhD candidate in Operations Research and, together with my University or my public library, I have organized some laboratories dedicated to problem solving for kids, trying both to entertain children and to make them learn different aspects of mathematics and computer science like they usually see.
Up to now, we have used some puzzles and games (like the 15 puzzle), labyrinths, exercises taken from some local competitions (logical, reasoning, counting, etc.). We have shown them a wide range of topics: sorting algorithms, recursion, very simple automa, trees and family relationships, countings, combinatorial examples, cryptography methods (like Caesar's cipher), etc. The primary goal is to let pupils being fascinated by maths, informatics and their several fields and applications. We would like to increase their creativity, reasoning and modeling abilities.

I have attended some university course about teaching and didactic methods, and now I would like to develop a more structured course, probably focused on one subject than on multiple ones. Beyond the topics, anyway, I kindly ask you to share your experiences, what worked and specially what didn't, speaking in terms of didactics methods.

Thank you in advance.

I have taught problem solving to older learners who studied a range of diagnostic, design and contingency problems. I'm not sure what age group you are talking about which would be handy to know in answering this question.

This is a diagnostic group activity solvable using informal constraint satisfaction.
https://sites.lsa.umich.edu/inclusive-teaching/2017/08/16/who-owns-the-zebra/

Planning activities also work well, surely there will be an end of term party to plan?


Teaching in class and online cohorts CS I am looking for advice for September with a new format for our daily schedules for high school CS.
As part of my board's grade 9-12 return to school plan, students will be in one of 3 cohorts of a class.  They will take two courses at a time over 10 weeks.  Daily class time is greater than normal, whether in school or online.

cohort A & cohort B alternate coming to school and working synchronously online
cohort A & B also alternate which course (of their 2) that they attend when they are at school.  A cohort only attends one course per day at school
cohort C is online only
when one cohort is in class, the other two are designated to be online doing synchronous learning.
cohorts are all in the same class/section
over a 4 week sample, a student in cohort A would have a day focused on their CS class for 5 days in class, and for 5 days online. The other 10 school days would be for another class.  They are spaced out in what seems like a sporadic way

Looking for advice on program delivery from any angle.  Course format, assessment, student communication, and related tools.
I am having a hard time visualizing anything other than treating it like an online course where some days some of the students happen to be in the same room as me.

I am in an almost identical situation to you, and I suspect that many, many CS teachers around the world are in similar boats right now.
I think you're right about the fundamental truth of it; you cannot keep different students coordinated if they do different things, and you cannot have them do the same thing unless the online-only cohort can also participate.  This leaves us with the sole (unappealing) option to treat everything like distance learning.
That doesn't mean that there are no advantages to the new arrangement!

The kids who will be with you in person will be able to easily and directly ask you questions.
The kids in front of you will also be easier for you to informally poll if you want to check in and make sure that what you're saying isn't losing the majority of the people.  (When I say informally poll I also mean to just scan your eyes around the room, and use your teacher-instinct to see whether many kids seem lost.  This was very hard to do during purely online education.)
Some kids were getting lost during purely virtual instruction, and having them in person some of the time will give you a chance to talk to them face to face, and hopefully to reel those students back in.  I suspect that coming in to school at least some of the time will make the entire thing seem more real, both for you and for the students.

If your in-class kids each have an electronic device, you should make sure that they have headphones to avoid audio feedback issues.  If they don't all have devices at school, you may need to do some photocopying, or "play" your materials at them from the front of the room.
Here's to hoping that this whole mess is very temporary.


How to explain lambda expressions This year I will teach students about lambda expressions (in java). I am trying to explain how they are interpreted by the JVM and what they unfold into.

For example:

String firstString = "this is a lambda example!";
String secondString = "and we compare to this, as well";
Function<String, Double> comparison = (String third) ->
        (third.compareTo(firstString) + third.compareTo(secondString)) / 2.0;

would create a function that gives the average of the comparison between a given string and firstString and secondString. I've tried to explain to a selection of students (as a Proof of Concept of my planned lesson, so only 4-5 students) that lambda expressions just make things look better but they think that it's a new way to do this. I am trying to explain that lambda expressions are simply a shortened way to write something a bit bigger.

So my question is, how do I explain what lambda expressions exactly are, in such a way that shows the students how these expressions are interpreted by Java?

A lambda is an anonymous function.  Java handles lambdas via a feat of type inference.  What you have done is to assign a lambda to a variable of interface type. You may only do this if the interface is a functional interface, i.e., it is an interface that specifies exactly one [non-defaullt] method.

When you do this assignment, the compiler assumes that the lambda is the method specified by the interface that is they type of the variable.  It is here that type inference occurs.  An object of unnamed type implementing the interface is crated and your variable now points at it.  The compiler will reject your code if the argument list or return type of the lambda is incompatible with the interface.

You will find lambdas to be splendid if you are doing event-driven programming.  In fact the JavaFX framework takes big advantage of this feature.


Where can I find high-quality editable slides for teaching git? I would like to teach my software engineering students git and to introduce key ideas in a presentation. Creating slides from scratch does not seem like a good use of time, since there are probably better ones already out there that I could use. I have found PDFs of presentations, but they are not editable, and I do not know their license. I am not interested in materials specific to a given site, such as GitHub or GitLab. I would like to find high-quality slides (in PowerPoint, Google Slides, or some other standard format) that I can freely edit and use.

I know of no freely/commercially available presentations, but I do know of a site that feels a lot like a presentation as you use it: Learn Git Branching. It's interactive and gives a hands-on intro to the most basic git features as it explains them. Plus, everything is visualized in real-time, so you and your students get instant feedback on what the command did to the pretend repo.
My thought is that you could either use that site in front of your students (or perhaps just use git itself and some sample files), or you could have your students use the site and follow along with you.
Honestly, from my own experience, that site (along with using git on small practice projects) was exponentially more educational/memorable than any presentation I've seen so far at my university, or found online. I don't just agree that making your own presentation would be a waste of your time, but I think you should consider a different format all together. Git, just like programming, is better learned through doing.


Looking for a blog article on the UI/UX design of an interactive coding interface like Khan Academy's I'm not sure if someone can help or if this is even the right place to ask, but I've been looking for a while for a marvelous essay / blog post / article from an author whose name I don't recall, that I had stumbled upon a few years ago.
From what I recall, the author had been credited as an inspiration for Khan Academy's "Intro to Computer Programming" interface. The author says in that article that much better than this interface can be done.
The essay is then a point-by-point lesson on UX design in general, going over possible improvements to Khan Academy's UI/UX interface for learning code, as a detailed example of each of the points he is making.
Thank you very much to anyone that might know what I am referring to, and link me to it.

I found it !! Boy, I'm so glad. Had a bolt of insight in how I should use Google's advanced search features, and I found it.
Here is the article:
http://worrydream.com/LearnableProgramming/
An article by Bret Victor, from 2012. A great read, for those curious.


How can I make database normalization more clear? Database normalization is needlessly clouded by over-explanation. I reviewed a wide array of web articles and several textbooks before starting to teach it. After I became thoroughly familiar with the point of it in my own terms and then understood the rules, I reduced the rules down to this list:

1NF eliminate repeating values and columns.
Assign a Primary Key.
2NF all attributes depend on all parts of a Composite PK.
3NF each attribute depends only on the PK.

In lecture, I literally scribble this on the whiteboard then work through examples. I assign a couple problems from a textbook and ask them to explain every step that they use, in a simple text document. Some get it fairly well, which is good enough for me. Others seem to get no traction at all and hand in a long, wandering story which repeats the statement of the rules in various ways, but not effectively.

Besides stating the rules this tersely, walking through examples and pointing to the vital sentences in the textbook, are there other ways to convey this kind of material? (This could be similar to other technical topics which have a simple 'core' but are abstract and hard to learn.)

There are some things you can only "get" by having repetition wear it into your brain.

This seems to me like a clear use case for first making them do it the hard way. So, construct a non-normalized schema and make them walk, painfully, through keeping everything in synch. Done right, they will be thoroughly sick of it after just a few updates.

Then, step by step introduce the normal forms, and look at how much easier updates are at each step.


What autograding software do folks use for Java code? Grading currently either takes me a huge amount of time, or gets done in an extremely cursory way.  It occurs to me that, if my students were able to submit code into some sort of autotester, they would find many of their errors before I review their code.  This would mean that I would only have to look for clarity issues, not logic bugs.

I am interested in software that (a) isn't too hard to set up, (b) will allow my students to test whether their code is (at least) to spec, and (c) allows me to quickly cycle through the code from all of the students in a section to look for style issues.

I have looked far and wide, and have not yet found a reasonable system that accomplishes these three goals.  Many universities seem to have robust systems, but they all appear to be home-grown, and unavailable to outsiders.  Is anyone aware of such a system?  I honestly don't even care if it costs money - I just need a solution that makes this task more reasonable.

For simple stuff I've used CodingBat. They've got an authoring system buried on the site. It's not terribly difficult to create your own questions, although the instructions are pretty wordy.

When you create a problem there are a set of fields to fill in. I'd attach a screenshot, but the network I'm on blocks imgur. I'll try to come back and add an image later.

doc

This is the instructions that your students will read.

hint

If you want your students to have the hint button, add some text

cases

List as many test cases as you want. Separate each parameter that you want to send into the method you're testing with a comma. The expected answer comes at the end.

It looks like this for the method below. 123 goes into sumEvenDigits as n and then 2 is the expected answer.

123,2
2006,8

code
Starter code for your students.

public int sumEvenDigits(int n) {

}

tags
Let's you put questions into categories, specify language, and set a difficulty.


How to START an Objects-First Course In light of this question (and many others on this site), I have been noodling around with the idea of reversing my AP Computer Science A course and taking an Objects-Early approach.

I'm having a bit of trouble conceptualizing the whole thing, however.  How would a class like this begin?  What is a first activity that the students can actually do in an objects paradigm?

I'll try not to write a book as an answer here, but my experience with this is long and deep.

The first thing you need to know is that you don't start with just the programming language itself. If you try to teach integer variables and 'if' and 'while' statements before you get to objects you may fail. I'm going to assume that your intention is to teach a first course that is also objects first. The students in a course like that might have no prior computing experience, though some will have.

The key to a successful course is to teach object-oriented problem solving, and not an object oriented language. In fact teaching problem solving via programming should be the objective of any first course no matter the paradigm. You want the students to learn to use objects and you want them to learn to create objects and you want them to be able to define new kinds of objects. But you don't need to do those all at once. You can spread it out over a short period of time - days, not weeks.

The key is proper scaffolding, written (or found) by you. The students work within a defined framework that can be quite complete (even Turing Complete). Another big idea that you want to believe yourself and teach your students is that an object is a "bundle of behavior."  Never mind instance variables (fields) at the beginning and never mind getters and setters. Define for the students one or more kinds of objects and their behaviors. I've done this with most OO languages and all of them can be introduced the same way. I'll focus on Java for the rest of this, as it is the language of APCSA. It is also a good, though not perfect, OO language widely used in industry.

I have a lot of experience with Karel J Robot (KJR) so let me describe how it can be used as an introduction, that might take half of the first course in computing and teach students how to program. It is not, however, specifically tied to APCSA, nor does it cover every topic needed by your students. But in about half the first course, students will be able to write serious programs that require deep thought. At the end, I'll try to list many of the things not covered.

The KJR world is a simulation in which one or more robots can be created and which have a few behaviors. The "world" of the robots is a rectangular grid and one or more robots can occupy an intersection. An intersection can also contain one or more movable "beepers" that robots might pick up or put down. Infinitely many beepers (effectively a beeper making machine) is also possible at an intersection. A robot always faces in one of the cardinal directions North, South, East, or West. A robot can perform one of five primitive actions: move, turnLeft, pickBeeper, putBeeper, and turnOff. Those are your primitive behaviors and when the student begins programming, nothing else is known, though some additional things are revealed later in the course. In particular, a robot doesn't "know" where it is in the world. The world can also contain walls between intersections that will block forward movement and cause an error if a robot attempts to move through them.

So, what kinds of programs can you write (using only main and the primitives? Well, to a programmer they are pretty boring: Move forward three blocks, pick up the beeper that is there and return to the initial position and direction. The solution is just a sequence of primitive actions, of course: move(); move();...

Students see a bit of syntax in the language and think in terms of the behaviors and nothing else. The learn about statement sequences, the most primitive control structure of  programming (arguable, I guess).

Next they get a much more complex problem (first day's homework), which if solved with only sequences of primitives is unwieldy. It is obvious that something better must exist. But if you choose that program correctly you can notice that there are patterns in the solution. Even in the first assignment the robot had to turn around twice and had to move three blocks twice.

On the second day you discuss the homework and find the repeated sequences of instructions. Now you introduce a new class (their first view of a class) in which you get newly defined behaviors. This class is a subclass of the most primitive class. You are introducing inheritance (too early perhaps, but essential in KJR). The new class has a few additional methods: turnAround(), moveMile()... Note that it is too early to introduce parameters. All of the methods so far, and for a long way in KJR, are mutators, the state of the robot is changed in some way. But the notion of a mutator is in no way linked to any idea of a "setter."

Now you have the basic framework of problem solving. Define a new class. Within it define new behaviors. Create robots with new... and exercise the new behaviors to satisfy some programming task.

Note what is NOT done. There is never any speculative class writing. All classes are purpose built to solve some small part of a larger problem. The book talks about the decomposition process in detail.

You are now in the third day of class and have covered three chapters of the book. The fourth chapter is much deeper and discusses polymorphism, largely by showing how the Strategy design pattern can be used to modify the behavior of a given robot without writing a new robot class. Instead Strategy classes (and Decorators) are used to build a much more sophisticated model of computing. This chapter requires several days. It introduces object-valued variables which up to now have only referred to robots.

The fifth chapter introduces selection and there the student learns about booleans as well as the fact that robots also have some self knowledge. However, there are no methods returning information about the current location or explicit direction. A robot can respond true or false whether its front is clear (no wall) or if it is facing North, or if there is a beeper on the current intersection, etc. All of these accessor methods return booleans, so the student can now write conditional statements, which opens the door to more sophisticated exercises. These accessors are not "getters" either in concept or in fact.

The sixth chapter is repetition, but note that the student already has a good knowledge of the nature of computer programming and they haven't seen any of the primitive data of Java other than boolean. For loops are introduced here, so integers are used, but only in simple ways - step counting, for example.

Later chapters (they are all pretty short) cover recursion and even concurrency.

The key to all of this, however, was a well thought out scaffolding structure in which the students can learn deep lessons in a way that you can control and in which it is harder to go astray in the minute details that you find with integer operators, float/double, ... The point isn't to teach Java as a language, but how to think like a programmer - specifically as an OO programmer.

The BIG idea

Java defines a logically consistent virtual world in which students can program without reference to lower level (machine level constructs) and can create consistent mental models without having to mentally compile their code to bits. A well designed simulation defines a yet higher level virtual world that if (Turing) complete can be used without reference to lower level constructs to solve any problem. That is very powerful. Robots can sort (piles of beepers) for example.

A slightly smaller idea is that you, the instructor, should think about what not to teach, especially at the beginning, as you do about what to teach. Teaching a complete subset intensely can be more powerful than teaching "the whole enchilada" at a shallower level.

Caveats

If the instructor skips the polymorphism chapter, students will come away with the unfortunate view that OO programming is all about inheritance as all of the robot classes must derive from a simpler such class. In fact, OO is really all about building "bespoke" or "tailor made" objects out of parts that are also objects. Skipping polymorphism also gives the impression that selection and repetition are all you need in order to know "how to program", that they are the real thing, an impoverished view IMO.

KRJ is not the only way that you can implement this general course framework. The Greenfoot system is a simulation rich world in which you can build similar (or not so similar) things and use the same general plan. There is an associated instructor site, the Greenroom, to which teachers have contributed many simulations. The general idea there is a World in which Actors can move, turn, interact, etc.

What is missing

The big one is counting with integer variables (other than simple for loops). One issue with teaching int and counting early is that from then on every problem becomes a counting problem, so students wind up with a poor mental tool kit. If you teach counting later, rather than earlier, students need to think harder about problems. You can "count" with decorators and encapsulate the actions themselves, rather than just the count in a (strategy) variable. You also can teach recursion without having to justify it as an alternative to counting.

There is no discussion in KJR of many of the things we love, arrays, for example, collections, iterators, and such. There is a companion book that covers most of what would normally appear in a first course but it assumes the students can already write sophisticated programs.

APCSA

In the past Karel was used a lot by AP teachers, but the course has changed as has the exam. I've never tried to use it to teach APCSA. I'm sure there are many things missing that the instructor would need to add to a complete course.


Blockchain cipher suitable for preschoolers Is there a cryptographic hash function that well suited for preschool-aged children to work out on pencil and paper, to learn concepts of block chains?
It must have the following requirements:

Able to be easily verified
Able to be easily calculated with pencil and paper
Able to link to previous result, to create blockchain

The function may be low-complexity. It does not matter if the function is easily broken.

If all you want is a simple hash function you could do something like this.
First take your original message and apply something like ROT 13 to it. This gives a reversible cipher, of course. Then give each letter a number, say N = 1, O = 2, etc, wrapping after Z. Next, just add up all of those values. It is no longer a reversible cipher, but a hash. To get it to be fixed length, simply pad or truncate it to, say, five digits.

Pretty bad cryptography, of course, but simple enough if the students can count and add.

The use in a blockchain is up to you.

This hash has the features described here: https://en.wikipedia.org/wiki/Cryptographic_hash_function, but they aren't very strong, of course.

Fixed Length
Deterministic
Easy to Compute
Infeasible to Reverse
Change in the Message changes the Hash (not a lot, though)
Infeasible to Generate a false message with the same Hash (maybe).

Call it the puppy-1 hash function if you like.

And of course ROT-13, like the Caesar Cipher, has some historical interest.

In the first part, ignore case, punctuation, spaces, etc., which isn't sufficient in general, but should be for this use.


Advantages of teaching basic javascript through typescript At my school the students learn some very basic javascript, and a while ago it was decided to expand on that (by teaching nodejs).

by "basic", I mean that we only teach html manipulation through JS.

We have two options for going about it:

Just teach javascript (es6 modules included)
introduce TypeScript and all that comes with it.

This decision is important because of the students familiarity with java. TypeScript offers more similarity to Java (what with it having, em, types, and all), but it is more complicated to teach than just sticking to javascript.

This decision is influenced greatly by the fact that the students are familiar with Java, which means it has to be a big factor in the choice we make.

Naturally, no method is "better" than another, but some methods would teach the students valuable skills.

So, which skills (and how significant are those skills) would the students learn, should we teach with typescript, instead of just javascript?

You mention that you are already using ES6, which suggests that package management and complication are not really barrier, though I would expect that many reading this problem are not setup to ensure node and npm are installed and/or may have access to git/ssh protocols for fetching dependencies or projects. So, the first thing I'd point out is that for some readers, compiling TypeScript could be a barrier that reduces is teaching value.

The second and more relevant point is that JavaScript is dynamically typed language. There is value in tools like Flow and TypeScript, especially in production systems, but there is also a great amount of value learning how to program in a dynamic type system. If you're already teaching Java, there are few better choices to teach strategies, advantages and disadvantages to dynamically typed systems. Some students will prefer that type of programming over strictly typed languages.


Explaining the Value of Knowledge of Digital Logic I am a college teacher developing an introduction to digital logic for grades 8-12.  This is a special topic that will be presented in three 50-minute periods with in-class exercises.  It won't go beyond basic combinational logic.  Provisionally, module 1 starts with gates and truth tables and ends with a half-adder; module 2 extends to a four-bit ripple-carry adder, and module 3 extends the ripple-carry adder to make a two's complement adder/subtractor.  These are not set in stone, but will be rather soon.

I am struggling with how to explain the importance of a knowledge of digital logic to high school and upper middle school students.  I want something better than, "To help you understand that computers are not magic."  Ideally, the explanation would be only a short paragraph, and memorable.

So, how can I explain the importance of comprehension of simple digital logic to pre-college students?  That is, how do I explain why students should care about this topic?

Edit:  Well, I'm teaching this to eighth-graders beginning Wednesday!  Day one is about what I planned last fall.  Day 2 has a ripple-carry adder and something else.  I'm still dithering between adder-subtractor and S-R latch which becomes a D-latch.  (I'm not sure the kids have enough grounding in binary arithmetic for the adder-subtractor.)

Day 3 now introduces a little bit of Boolean algebra.  The kids are introduced to Kat, who is heading for Hogwarts, and must design Kat's cat checker.  There are five inputs and three possible "OK" results from among the combinations.

For the explanation that everything computers do comes from a few simple circuits, as suggested by Ben I. below, I'm going to show this video at the beginning of day 1: https://www.youtube.com/watch?v=ZoqMiFKspAA

Your best bet of how to answer why students should care is to stop and ask yourself what good reasons there are to care about it (or any topic). Do that before reading on?

OK, so my answer is: because science. The word means knowledge. If you want to know something instead of just have opinions (possibly wrong) or worse, then you will want to be finding out. But why bother to know anything, is really the question. Caring is your issue. Caring means that one can influence things, and not caring means that one will be pushed around helplessly by circumstances.

Is it effective to care, is the obvious question? Can we actually learn enough to have any effect? When things seem perplexing and obscenely complicated, then it appears hopeless. Science brings hope because it is able to render the complex simple enough to manage. When I found out that all matter is composed of just 3 elementary particles, and that there are basically only 2 forces that affect us, only one of which we have any control over, it was revolutionary. If more people knew these things, they might wish to learn more. When you ponder the 88 keys on a piano, able to make basically all (western) music, or the 92 naturally occurring elements making basically all things, it is astonishing. The organization of atoms (predicted 2500 years ago) in to the stunning wonder of the Periodic Table is a great story!

All computers are made of transistors, and built up in to a few simple circuits replicated millions of times, like the cells of the body or brain. If that is not inspiring and provoking of interest, I would release the students from school, as they are unreachable: they don't care to have an influence on their own future.


Coding bootcamp vs. computer science I was a college student majoring in computer engineering, but dropped out because of several issues (social situation, interest, etc). I always wanted to study computer science, but didn't do it because i thought that my parents won't let me (because they were so proud when i got to one of the most prestigious college in my country). When I dropped out, I got some talk with my parents and they gave me permission to do whatever I want.

At that time I talk to them and I said that I will go to coding bootcamp, but after some research I found that coding bootcamp won't make you a real software engineer and it's pretty hard to find a job compared to computer science graduates.

What are the differences between coding bootcamp and a computer science degree? Especially in terms of the advantages and disadvantages of each.

First, be aware that Computer Programming and Computer Science are not the same thing. The term Computer Engineering might, in practice, be the same as Computer Science, but it can also be much different (software vs hardware focus).

Coding bootcamps and other, similar, programs, such as online courses almost certainly lack both the depth and breadth of education and skill building that you should expect from a reputable Computer Science program.

On the other hand, businesses need computer programmers, but the  jobs they offer are not very exciting and are at a pretty low level, lacking an obvious path to a long term career. "Coders" work at the direction of others and have little say in what they build or much in the design process.

Still, computer science graduates often work initially as "coders" but, with more knowledge, can be given more responsibility.

Think of programming as nothing more than a tool that helps you explore deep ideas (database, ai, machine learning, ...), but it is those ideas, not programming that is the important thing. You may need to be adept in using the tool, but it remains just a tool. It is fun, but it isn't the essence of a computer science degree.

Programming can get you a job, but it won't assure a career. Of course, once you are in a company, there may be opportunities for you to learn the rest of it, but a degree provides a (hopefully) well thought out curriculum that meets both the modern needs of employers and the intellectual rigor that lets you build a career either in industry or academia.

To get a sense of it, look at the curriculum of any reputable university. Both the required courses and the electives. That will give you a sense of the breadth required.


How can I explain lambda calculus to my class? My students are pretty confused by lambda calculus. I'm looking for a way to start them off. Is there some image or analogy for lambda calculus that I can use to help them understand in the beginning?

My kids are college sophomores, and I would just like to give them a clear way to start thinking about it.

One totally intuitive way to introduce the concept is with Excel formulas.  So, imagine in A1, we have the value 10.  In B1, we have the formula =power(A1,2), and in B2, we have the formula =(A1+A1)/A1.  So, at this point, our sheet looks like this:

        A   B   C
    1   10  100
    2       2

In actuality, we have now created a literal, and two lambda expressions: $10$, $(\lambda x.(power\, x\, 2))$ and $(\lambda x.(/\, (+\, x\, x)\, x))$.

Now, let's add a formula into C1.  That formula will be: =B1+1.  This is a third $\lambda$ expression: $(\lambda x.(+\, x\, 1))$.  Our sheet now looks like this:

        A   B   C
    1   10  100 101
    2       2

Since we are pointing C1 to B1, which itself points to A1, we have now created $(\lambda x.(+\, x\, 1))\, (\lambda x.(power\, x\, 2))\, 10$, which resolves now in exactly the way you would expect from the Excel formulas:

$(\lambda x.(+\, x\, 1))\, (\lambda x.(power\, x\, 2))\, 10$

$(\lambda x.(+\, x\, 1))\, (power\, 10\, 2)$

$(+\, (power\, 10\, 2)\, 1))$

$(+\, 100\, 1))$

$101$

Simply re-pointing C1 to B2 gives us a new lambda expression:

$(\lambda x.(+\, x\, 1))\, (\lambda x.(/\, (+\, x\, x)\, x))\, 10$

Which again, resolves to 3 as you would expect.

What's nice here is that if you get rid of the 10 in A1 (you must replace it with a non-number so that Excel does not convert it to 0), you will get #VALUE, because you have created a $lambda$ expression, but not fed in the rightmost value.


Short foundational lessons for 7-8 year olds I have an opportunity to run four classes of about half an hour, with 7 to 8 year olds (my sons age).  This is part of a program called STEM professionals in schools. All I am there to do really is help kids see themselves as potential scientists or mathematicians, and to see the subject as fun and interesting (with kids this young, just being a visitor in the classroom is already fun and interesting). I bring along a set of little cards I made up of my (very diverse in background) colleagues and talk about them in an introduction lesson.

These are my Computer Science lesson ideas:

Word unscrambling. This is already a familiar exercise from homework. Each child gets a worksheet with a words 3-12 characters long to quickly unscramble.  We talk about why it was easy to unscramble 3-letter words and hard to unscramble 12-letter words. Then get ideas from the kids about instructions to solve the problem without knowing what the word is.  [Algorithms, algorithmic complexity, optimisation tricks that work for computers and people alike (common letter sequences like '-ion').]  This one is pretty well worked out, but happy to hear of anything I can do to make it cooler.
Substitution coding. Starts out as how to pass a secret message like a spy. My aim is to end up with something like a compiler or maybe zipf encoding - substitution rules that make the encoded message denser than the final form. Here, I'm a bit stuck for a solid example. Maybe a cipher system with a limited vocab?  The principal concept is [substitution / naming / functions].
Logo.  Basically a demo lesson using function definition in Logo to draw something recognizable (Captain America's shield, say), comparing how easy it is if I create my own substitution rules (functions).  Also demo recursion, substitution inside the substitution rule with the Koch snowflake, maybe some other fractals. This is a demo of Logo, concept is mainly [functions].
Handwriting recognition deep learning.  Set up a recognizer (this is easy enough, right?) and give the kids a chance to test their own handwriting (this will be hardest on my son, I reckon).  Discuss how it works as lots of layers of functions which had to learn to work together. [machine learning]

If you are merely looking for feedback on this, let me point out, first, that according to Piaget's work, your students seem a bit young for this. They have only just entered the third stage of Piaget's Model. Moreover, since not all people advance in sync, some may still be in the second stage. In particular they are still very concrete thinkers. Anything that depends on abstract thinking won't be very comprehensible to them for a few more years.

For a small exercise, however, the above might not matter too much as you aren't expecting them to do much but think "WOW".

But there has actually been a lot of thought given to "computational thinking", through Jeannette Wing's work. This has mostly been directed at slightly older students, however, say secondary school.

There is a well developed effort to bring computational thinking down to this age level. CS Unplugged, provides a fairly comprehensive set of activities that are targeted at 5-10 year olds.

While there are a lot of things you can do, don't expect the kids to retain a lot of it, and certainly don't expect that they can then (or soon) abstract from it to actual computing. I find that Spiral education, in which ideas are introduced in a simple way early and then returned to (often), works well. So, for a first cycle, you give them a hint of things that might be and later reinforce that more formally.

I find that something as simple as the song There was an old lady that swallowed a fly is interesting and fun. It is also an introduction to recursion, but at that age, don't talk about base cases, etc.

A few more words about logo. While it is a fine language, you need to use it carefully for youngsters, so that what you do matches their cognitive level. Since they can't do much abstraction yet, there are a couple of possibilities. Since it is visual it matches their "concrete view" of the world, of course. One is to use only the language primitives. But another is to build a virtual world in logo with a set of its own "primitives" that they just use instead. These can be of a higher level than the built in commands, but are opaque to the students. Karel J Robot is like that actually. Robots obey five simple commands (move, turnLeft, etc) and students begin with only those. The robot language hides the underlying Java primitives completely.


Online Platform for practicing Object Oriented Programming in Python Is there any recommendation on an online platform which teaches and allows practicing object oriented programming (OOP) in Python?
I am familiar with Hackerrank and Hackerearth, however, they do not have practice problems related to Object Oriented Programming in Python but they do have problems related to other concepts.

replit.com allows you to code online and you can also set up tests for the repl, as well as embed the code into a blog or lms.
I've an example here based on a tutorial here. You'd need an account to "collaborate" but the images are below.
The code runs the main.py file when the "Run" button is activated.
I made a Point class in point.py and this is called from the main in main.

There are other features such as version control, sharing for collab, database, forking etc.

Repl introduced classroom some time ago- the demo video shows some of the capabilities for assignments.  Last year this was replaced by Teams for Education.
While better, it is not free, but there is a 4 month free trial- you can see a demo of this "update" here.
Each student "gets their own copy" of an assignment, and the interface is quite pleasant- they can see due dates, status etc, and you can build in unit tests that they should pass before submitting an assignment.

Github classroom (demo here) is another option but may not be the easiest to start with.  Using repl you could at least share code and have the class make their own repls and write code to pass tests, or code a class given a class diagram or problem statement.
Hope this helps.  Not exactly OOP Codingbat but might give you some ideas.


Is there a good book for combinatorics for programmers? The book should be easy to read, or at least average. The level for reading such a book is the MATH and CS school curriculum. It should also be expanded on topics related to CS, and also be narrated in a light manner. It should be kind of in a intro tutorial before starting a middle combinatorics.

[From your comment] P.S need such combinatorics after which I can understand the course of data structures and algorithms.

Combinatorics doesn't factor into data structures and algorithms in this way. If your goal is to understand data structures and algorithms, combinatorics is an irrelevant topic.
Combinatorics is also quite vague, as this can effectively include the integer number sequence, which is effectively "knowing how to count".
While software development will generally expect you to count numbers from time to time, there's a vast difference between counting and the subjects that a book on combinatorics will delve into. Again, the latter is irrelevant to get a basic understanding of data structures and algorithms.

Is there a good book for combinatorics for programmers?

As far as I'm aware and my research could uncover, there is no such book tailored to software engineers. The field of combinatorics is not part of the field of software engineering. Combinatorics is a part of maths, not CS, and therefore is explained in a mathematical context.
Note that it is true that early examples in CS training courses often use simple maths. However, this is done purely because students will generally understand the simple maths and therefore are able to fully focus on the programming challenge without being distracted by the mathematical operations in the example.
If you are able to count and perform elementary operations (+,-,*,/) then you have enough knowledge to learn to program. Additional mathematical operations may be a nice-to-have for more advanced examples, but they don't require in-depth mathematical skills. If you passed high school maths (based on my experience, you don't need anything above the math 14-year-olds are taught in school), then you are as prepared as you need to be.
Obvious caveat: Unless your intention is to delve into programming specifically to tackle more advanced mathematical calculations. But that's not what a learner should be focusing on.


Why would mutation be considered by some as a difficult concept to grasp? Why do some instructors delay teaching mutation due to considering it to be a more difficult concept? (than functional or recursive concepts, etc.)

It is very likely that, back in the 8-bit PC days, many thousands of 8 to 12 year olds learned to code in Tiny Basic or other "street" BASIC implementations (where there weren't even local variables or other easy recursion or functional semantic support).  How could these kids do so if variable mutation was a difficult concept?

Or is the spaghetti code they often produce a result of not really understanding the concept itself?  (rather than just the software engineering downsides)

I personally teach mutation almost immediately.  However, I agree with Buffy that more difficult is not really the metric people are using to decide to teach mutation later.  It is about giving certain key habits a chance to grow and develop before you get there.

Most people find recursion naturally more difficult than a loop.  There is no reason why this must be, and folks who learned recursion first will often find the difficult one to be the standard imperative loop.  If you begin a student in a programming world without mutability, what habits will grow?

Certainly recursion will come quite naturally.  So will linked lists and trees.  And certain sloppy habits will be naturally avoided, such as this balderdash:

System.out.println("You found " + hotdogs + "hotdogs!");
System.out.println("How many glasses of water will you drink?");
hotdogs = myScan.nextInt();

Ultimately, there is a deeper philosophical statement being made by the instructor about which habits they would like to inculcate and foster at the very root of their students' thinking.  These patterns of thought, it is presumed, will modify the initial ways that the students approach problems even later in life.

I do not know of any research that backs this up, but, of course, much of what we try to impart to our students is not from research, but from intuition. And, who knows?  They might be right about this one.


What physical examples can I use for public key/asymmetric encryption? I'm going to be teaching a lesson about asymmetric cryptography to US high school students who have no background in Computer Science, specifically the way that public key cryptography is used while browsing the web. The typical example that you'd see when reading a book about public key crypto is a padlock. In this classic example, one person has a lock and gives out keys to the lock. Then, anyone with a key can unlock/verify it, but only the person who has the locks can lock/sign document.

However, this doesn't work for a hands-on example, because someone can use the key to close the lock again, and lock/sign different information. Is there some similar tool I can use for a hands-on, physical (not on a computer) example of public key/asymmetric encryption?

Since cryptography is a bit elaborate, this will be too.

Basic encryption is like the following:

Take the "information" you want to transmit and put it into a locked room. A guard sits at the room with an actual key.

Take a piece of paper and rip it in half, the more jagged the rip the better. Give half to the guard and the other half to the person you want to "communicate" with.

To access the information, the person presents his/her half of the paper and the guard matches it with the guard's own half. If they match up the guard will unlock the door and give access to the "information".

Depending on the protocol the guard might re-lock the door or destroy the "information".

Locking the "information" in the room is encryption. The receiver and sender "keys" are the two halves of the piece of paper. Presenting a torn piece of paper to the guard is the attempt to decrypt.

Note that neither half of the "key" is shared with anyone but the sender and receiver of the message, so duplication isn't an issue. This is fine for a one time message or even repeated messages between the same to entities.

But this isn't sufficient for the public-private asymmetry that you seek. In that scheme you want to publish one half of the "key". So modify the scheme as follows.

If someone wants to communicate with you, you control the "keys" and the room. As before, you rip a piece of paper and keep one part, though it shouldn't be a standardized size of paper. The piece torn off, which will be made public, shouldn't  be enough to reveal the overall shape of the paper, perhaps a hole torn out of it or a corner torn off. One piece (the public key) is duplicated and published. Anyone who gets a copy of the public key can communicate with the you, key owner. You keep the other "private piece" without revealing the true overall shape of the original paper.

Anyone with a copy of the (other person's) public key can put something in the key owner's room, guarded by the key owner's guard. Only the key owner can remove things from the room as controlled by the guard.

To communicate with you, the key owner, the person presents their information and a copy of the public key (piece of paper) that you published, to the guard who locks up the information and keeps the key (public key half) that you presented. The room is re-locked. When you, the key owner, wants access to the information you present the private key to the guard who will then unlock the room for you after matching the two pieces of paper and verifying that the overall shape is correct.

Only the key owner can remove things from the room, since the overall shape of the "key" is unknown and "can't" (we hope) be duplicated. Anyone can put things in the room but it will be readable only if the public key held by the guard matches the overall key.

A related key pair can be created by taking a private drawing (that you produce yourself) and using a part of it as the public key. This might be easier to reproduce than the torn paper. However, it must not be easy to deduce the entire drawing from the fragment. Infeasible, if not impossible.


What are effective ways to prepare students for the AP CS Principles Exam? First offered in 2016-17 (previously in pilot), the AP CS Principles assessment includes two open-ended through-course performance tasks and a timed paper exam containing multiple choice and multiple response questions. This question is about preparing students for the timed paper exam.

What strategies are effective ways to prepare for this exam?
What resources are available? How much if any class time should teachers plan on for going over practice questions along the way and in a spring review?

Calibration:

Obviously it depends on student skills and knowledge coming in, on school environment, and on pass rate expectations. I'm trying to ask for advice useful to a typical teacher, but I also want answers aligned to the CS-4-All inclusive philosophy. So for the purpose of this question, please assume

A school unremarkable in academic skills (not a magnet school, just average)
All students in the school take the course as 10th graders with previous exploratory exposure to CS
All students take the exam (e.g. district pays all costs)
The teacher wants a higher percentage of students to score 4 or 5 than the percentage of 4s and 5s awarded to examinees overall. (36% in 2017)

Personal disclaimer: the best preparation for the exam is first to ensure that students master course content. If you have an AP CSP-aligned curriculum, then every day is a day of exam preparation. This touches on the biggest struggle I felt as a first-year AP teacher: am I teaching them computer science, or am I preparing them for a computer science exam? The ideal situation for me -- and the personal resolution I reached -- is that quality instruction, assessment and feedback, and student engagement with a rigorous curriculum (CS50 AP in my case) are the key elements to focus on for ensuring student success on the AP Exam.

That said, I did utilize a number of resources throughout the year:

The full-length sample exam provided through AP Course Audit (a secure document)
The 22 sample questions from the course description
The prep book Fast Track to a 5
The online paid resource Albert.io

I'll enumerate how I used each of them and for simplicity refer to them by the number listed above.

I pulled questions from #1 throughout the year. The first unit covered a basic intro to binary, so as a short formative assessment, I gave students the four sample questions they could answer having studied the basics of base systems. This was within the first two weeks, so right away we could talk about exam-style questions, specifically the ones that required selecting two right answers. I used sample questions a few more times during the first semester, but I didn't make it a priority (see disclaimer above). However, on the last day of class in the fall, I gave students a modified exam. We had studied three of the six Big Ideas tested on the multiple-choice exam in depth, so I selected questions equivalent to half the exam (enough for the allotted time and perfect for matching the pace of the real exam) and surprised them with this practice exam. There was no warning; students just had to trust what they had learned up to that point. We started the second semester going over this exam. I did an item analysis over break, so I could hone in on strengths and weaknesses and address them in the spring.

In the second semester, I started to use #3 at certain sporadic moments. Since The Internet is arguably the most fact-driven of the Big Ideas, I used it as a resource for designing an exam on my Internet unit. Students were encouraged to buy it, but it was not a requirement. So much time in the second semester is taken up by Explore and Create that the multiple choice test is a lower priority until after spring break. Based on this year's Easter timing and AP schedule, I had two weeks of classes to devote strictly to exam preparation. This amount of time was more than adequate to build students' confidence and familiarity with the exam format.

During these final two weeks of prep, I went through each question from #2, discussing how each Big Idea could be assessed. As a class we went through each Big Idea on the exam and connected the learning objectives to potential exam questions. The sample questions were great talking points for reviewing course content. I also gave an in-class exam using all the questions from #1 that didn't make it on the first practice exam. I paced it such that students had the same time/question that they would have on the exam. I wanted to make sure students had seen every official practice question and had the opportunity to ask about each one, especially the ones from the secure document that they couldn't take out of the classroom.

The last big exam review I did was an optional exam review the Saturday before the exam. I had >50% attendance, and by the end the students felt more than prepared for the exam, and I felt confident I had done enough to get them ready for it. That day (and the following week) I made heavy use from #3 and #4. We basically went Big Idea by Big Idea, gaining more practice and focusing on particular tips and tricks for each. In particular, we went through a number of the robot questions and those questions that required analyzing segments of code.

At the end of the course, I asked students how prepared the felt for the multiple choice. To a person they said that we had done ample review and that they felt confident in how they had done. (Now I will know more about specific students later this week when the scores come out for teachers, but I do value this piece of student feedback.)

Bottom line: trust the quality of your instruction and your curriculum. Extra resources are nice, but the College Board's official practice is sufficient for getting students ready. A little exposure in the first semester and a week or two of focused multiple-choice review is plenty. Given that students will also prepare for the exam in the work they do for Explore and Create, they will be plenty prepared by course end. Also, the more students read, write, and understand code on whatever language you use, the stronger they will be come exam time; there is no substitute for this.


When mentoring individuals, teach clean coding and simple/effective thinking or let them do it their way? I have a background of 20+ years professional coding, but my heart is really in teaching. About three years ago, I started tutoring ages grade 6 through adult in coding topics.

introduction to coding in Python or Java
AP CS A help
for independent students, long-term projects like an role-playing game
competitions (CodeWars, US Computing Olypiad)

I like my code to be simple and comprehensible, with the feeling of confidence that it works... a simple thought process by which I can understand (and anyone can understand) what my code does.
So I teach that. I teach breaking things into encapsulated sections, I teach testing and debugging techniques.
I also teach how to make use of your brain better and work smart, not hard.
Several of my students have been with me for three years, and they've all grown a lot, and they're a pleasure to work with because they picked up this clean thought style.
But... is this the only approach to teaching? Is it the best approach?
Keep in mind that most of my students aren't going to be professional coders. Keep in mind that I'm a bit obsessive and probably could stand to lighten up a little and let my students work in whatever way they would like.
Recently a student came to me, interested in doing US Computing Olympiad problems. The thing is, he had barely learned anything about coding. He had a little Java knowledge, but was weak on creating classes and really didn't even understand how to use functions. I suggested that we work on fundamentals and he balked - from his point of view, you didn't need functions to solve these problems, and he had searched the web for other solutions and none of them used functions. (All the code is in main())
At first I figured he was in for a disappointment when he realized these problems were over his head. Well, shiver me timbers, he has solved about 10 problems so far using this technique. I can't even figure out what his code is doing or why it should work.
He doesn't do testing even! He just submits his code and keeps tweaking it until it passes the online judge test cases.
So I finally said that consider it a limitation on my part, I'm only really able to work in my normal method and that if he really doesn't want to do things my way, he has to find a tutor who can work with him like this.
Finally there came a reason why he's interested in me and my methods - he did see that it would be useful to test and debug, and he did find a few USACO solution online that used functions and classes, so now he has a mild interest in learning that from me.
I guess what I'm asking then, is when you are mentoring someone, how do you negotiate this balance between "teaching them clean work" and "let them work in the method most natural to them"?

As someone who has now taught CS for many years, let me first reassure you that teaching clear, clean coding is entirely worthwhile. I think this is especially true for those who will not go off into software professionally, because editing, and being able to express ideas in a clean, clear manner is a skill that serves people well in any field.  (I've written a bit about my approach to teaching good coding style before on this site.
Now, USACO is something a bit different. These competitive programming situations are designed for coding speed, program speed, and correct output.  You get no points for maintainable code, clear thinking, or reasonable variable names.  These contests can be great learning experience as long as the student understands that they are getting intense (and good!) practice on only one small piece of a larger puzzle.  I would definitely try to contextualize this for the student, though I caution you that you may never win over this particular student. He may have already become somewhat set in his thinking.
Here's something silly you can do to attempt to demonstrate the value of clean code to the student: take some nice, clean code for a USACO-style problem and introduce an obvious edge-case bug that crashes the program (an array out of bounds or somesuch).  Refactor it to give it USACO-style names, like m and pf. Shove everything into main.  Make sure that there are no strings to make obvious what the program is supposed to do.  Reverse loop styles to make them less appropriate (i.e. switch for and while).  Screw up the indentation. Generally make a mess of it.  Have fun!
Print out your spaghetti onto physical paper and ask the kid to find the bug. You can even tell him the type of bug. Tell him he had 10 minutes.  At the end, ask him what the whole thing does.
Then give him the original version, with clean names, good use of functions, comments to explain what the functions do, and generally clean design. Ask him to find the bug again, and ask him what the code does.
Now tell him that he's just been hired to maintain hundreds of thousands of lines of buggy code that someone else made.  If the code all looked like the first example, how long would he give it before he quit that job?


First project in my second year data structures intro I am currently teaching the pretty much normal second year Data Structures and Algorithms course. In this course there are four programming projects, with the first project completed the automated testing and grading yesterday. However, out of the 200+ students taking the course, only 72 managed to complete this project so that they passed my automated tester for the pseudorandom seed that I used. As my first question to this forum, I would like to get some second and third opinions about this issue before I decide how deep I dig my heels into the ground about it.

This project (full specification) asked them to create a Java class named IntervalUnion whose objects represent unions of integer intervals, such as [1-5,9-12] or [4-8,11-15], with an arbitrary number of individual intervals allowed inside each such object. This class should then have the public methods union and intersection to create new objects, with the union of these two objects being [1-15] and intersection being [4-5,11-12], along with toString, equals and hashCode as usual.

I simply cannot believe that this project would have been unreasonably difficult for second year computer science majors who have already taken the standard two first year courses of introduction to programming and computer science using Java. And yet for some reason it seemed to be, especially using my automated tester that, based on the given pseudorandom seed, generates random test cases and computes a checksum of the results returned by the implemented methods, this checksum then being expected to be equal to the checksum produced from my private model solution.

For a test run that generated one million objects, easily automated with a Bash shell script, the passing projects took between one and three seconds to finish, whereas some solutions had to be terminated after minutes of waiting and thus rejected. The project spec specified a thirty second time limit that I would have assumed to be more than enough for them even to dilly dally.

Of course I might be completely mistaken in my view about this, so I would like to hear some opinions of other teachers who have taught this same second year intro to algorithms, before I make any announcements to the students.

Since my course uses the three best projects out of four in determining the total course grade, I am currently of the opinion that I am going to just tell the students to wake the hell up, realize that this is serious, and do better in the three remaining projects. The second programming project consists of writing method to remove all nodes with given key from the given linked list, and to sort the given linked list, using the sorting algorithm of their choice. (As with all these projects, the grading is 5 points for passing the automated tester, and 5 points for comparative running time rankings among all submissions.) There is just no way that that task could be considered too hard for second year CS majors.

The last two programming projects ("Packing words in bins" and "Word filling") due at the end of the course should be easy to at least pass in that within the simple rules of both word search puzzles, there are really no wrong answers, but the difficulty of both projects is in quickly finding a good solution that scores well.

(As an aside, I am actually pretty proud of that Word filling problem, as its idea came to me last summer during a nice mellow walk, and the solution sketch the next day during a ride home followed by about an hour to implement after dinner, and I wonder if I could be the inventor of such a simple but tricksy puzzle that I simply can't recall ever seeing anywhere before this. Another more interesting variation might be to maximize the scrabble score of the words, since that doesn't actually change the solution algorithm.)

Sorry, but digging in your heels or telling the students to wake the hell up is going to get you exactly nowhere. When a small percentage of your students fail to successfully complete a project it is likely their own lack of background or application. But when only about a third are able to successfully complete it, it is a problem with the course, not with them.

Some possible reasons for the problem. Perhaps they started late on it and weren't able to do a good job as user Adam asked? If so, why was that? Are they overworked generally in your course and elsewhere? I doubt that so many are just late starters. Was it a problem of insufficient testing? Was it too many tried a brute force approach that doesn't scale? How much does the course stress that early on - both testing and scaling? It seems like they weren't able to ask questions (of the TAs at least) as the project progressed. If they get stuck, how do they get unstuck? Just on their own?

I think you have a problem and I can't diagnose it, but you can. You can, for example, have your TAs do a postmortem with small groups. I hope you have more than one or two for 200+ students. The first question I would want the failed students to answer was "Were you surprised by the failure?" That can lead to a lot of discussion about the nature of it. I would ask about how much testing they did, especially on large sets. Were they able to use the tester effectively, providing appropriate inputs, or were they misled by it. Another question I'd want an answer to is how many students now actually know why they failed. What was it in the code or its creation that led them to failure. If they don't know that you have a serious problem going forward. I think that for these and similar questions your TAs are better able to get you usable answers. The students are less likely to feel intimidated by the questions than if you ask them directly.

On another level, I'd ask how many independent runs did you do with each student's work? Just one? The data was random, remember. Maybe naive inputs to the tester gave them poor feedback while doing their own testing.

Maybe a five week project with little guidance or feedback is sub-optimal. Especially if you treat it as an exam. It seems like a lot of time, until it isn't. Why not shorter projects? Why not more feedback? Why not, to be honest, continuous feedback?

I wonder how many students who failed did so only for run time and how many weren't even able to put together an algorithm at all. Has anyone given them feedback on their code and approach other than "failed"?

Are your expectations about what they "should have learned" in the earlier courses realistic? Are you making assumptions not warranted by the facts?

Don't just stamp your feet. Find out why this happened and change your teaching structure accordingly. Treat it like a scientific problem with an engineering solution.


Textbook or video lectures to develope intuition for solving any unseen Graph Theory problems Background
Hello, I am a third year undergraduate in CS. I am eager to pursue higher education from one of the best institutes in out country. For that I need to write a competitive exam, named GATE which had this syllabus for this year 2021. The syllabus remains more or less the same each and every year.
The pattern is as follows, 65 questions , time 3 hours.
So for each question, I can afford at most 2.76 mins, which is quite a constrained amount of time, considering the level of the questions.
This is to give an idea about the level of the questions

Problem
As per the given syllabus, the exam asks quite involving questions on Graph Theory, with questions based on properties of graph algorithms, tree formed by traversals, or coloring or other important but at times unseen (by the candidates) properties or concepts. Mostly they tend to ask questions from unseen topics, which probably one has not handled previously unless he is quite lucky. In such cases they definite the topics and then asks on them.
Usually questions are like select the most appropriate options or marking the true statements.
Now it is quite difficult (for me at least) to understand in 2.76 mins the new concept (defined in the question), read the statements, find counter examples for them to prove them wrong. At worse for some statements it might happen, that I am unable to find the counter example in that 2.76 mins of time, but it might happen that a more difficult counter example might exist.
One can have a look at the type of question in graph theory here and here and here.

Situation/Request
I have gone through CLRS and I am acquainted with the terminologies or graph theory algorithms and properties of tree produced by traversals etc. But the thing is that all these I have learnt, by going through the text many times and I have been quite slow at grasping those concepts given in CLRS.I have even gone to Kenneth Rosen's Discrete Mathematics texts.
As per the recommendations given in few coaching institutes (note that I do not go to any one of them, I do self study, got to know from my classmate), I have picked up Narsingh Deo's Graph Theory text and I am going through it now.
[I have solved most of the exercise questions of CLRS (except for the $\star$ questions) mostly on my own but only for once, long a ago, while reading the text for the first time. Some questions even took a single day to think (too slow indeed). Rosen has a huge no of questions at the end of each text, that too I have solved not all but selectively as I found few problems repetitive there, and that too I have done only once. But I have read the text many more times (that too selectively), so that I do not forget the things which I have learnt...]
Could anyone recommend me some good text or detailed video lecture series (not a very advanced one) that would help me to build intuition behind graph theory properties or statements unknown to me. The texts which I have already read are classic and fine, but I find it difficult at times to answer questions in the GATE, (might be due to the short time or might be that I am not that sharp) but still I want to sharpen my skills in dealing with these problems of graph theory. Even the weightage of this subject is quite high every year.
Thank you.

I'm writing only a partial answer, because I currently lack time. That means that I'm not properly sourcing everything, and largely working from my own memory.  I don't believe that anything I say below will be wrong, though it is definitely possible that I might be forgetting a few things.  In any case, hopefully this will be enough to get you started / unstuck.
The test does look quite difficult!  I teach several of the topics, and they were largely what I would expect from the end of an undergraduate university degree, but with the added pressure of timing and high stakes.  Ouch!
When attempting to gain fluency (in any topic), you are looking to make a few kinds of connections:

"This is just like..." -- these connections allow you to utilize systems that your brain already understands well.

"These ideas group together" -- this is called "chunking", and it is how we group small ideas into larger and larger pictures.  When you "chunk" ideas together, you are able to manipulate the chunk in your mind instead of all of the small details.

"This system looks like" -- much like #1, this allows you to "see" how systems work in your mind's eye.  Then you can manipulate your visuals.

In essence, you are trying to group and simplify ideas.
To gain fluency, additionally, don't be afraid of memorization (though don't focus on it exclusively, either.)  The purpose of memorization should not be to be able to regurgitate everything, but rather to give you quick enough recall that you can use the idea in a larger system.
Think about it this way: there is a cognitive tax to using any idea that we know.  If the cognitive tax is very high, then using the idea takes nearly all of our focus.  This limits what we can learn, because to really understand larger ideas, we need space in the active, working parts of our brain to encompass all of the smaller ideas that the larger idea needs.  If the smaller ideas are taking up all of our active resources, that becomes impossible.
Thus, the goal of memorization is to reduce cognitive tax.  If you are working hard to memorize beyond that, then you are wasting your efforts - you are not going to gain further fluency through memorization.  You need to instead focus on chunking, visualizing, and relating ideas to one another so that you can see bigger pictures and larger groups.
Also, it is useful to practice on a mix of simple and hard problems.  The first group reinforce and strengthen the patterned connections that you have already made.  The second group force you to stretch those patterns out in new directions, and can help you spot new uses and simplifications.
I have always found that teaching others helps me to gain fluency, as it forces me to make explanations that distill systems for other people.
Good luck!


Boolean Logic: How to Explain + as OR? In a previous question, I asked about the appropriate notation when teaching Boolean logic to students ages about 11–14.  I selected the notation of engineering and computer science in part because I believe (without any real research) that's what the students are most likely to encounter later.

I'm still not sure how to explain + as OR other than by saying that the same symbol is used for different, but similar, things. Is there a better way to explain that?

Aside: I am going to use center-dot for AND because most of these students have not had an algebra course and implicit multiplication confuses them.  They won't encounter the inner product concept until college.

Since your students are getting the beginning of Boolean from you, you have the advantage of being able to lay the proper groundwork to work within. To begin with, hopefully, you will be stressing the point that Boolean logic is two-state. You can use the word binary if you choose, as long as they are not predisposed to think binary = computer, since while Boolean logic is handy for computers to deal with, it is not just for computers.

To connect the symbols, meanings and math together, make it explicit, and demonstrate. Start with the concept that FALSE is the same as nothing and TRUE is the same as something. "I have an apple in my hand" is FALSE if you have no apples in your hand, even if you have an orange, or a pencil. The same statement is TRUE if you do have an apple in your hand. It is not, however, more TRUE if you have two apples, or twenty apples, in your hand, however, it is still just TRUE.

Zero, as a number, represents nothing as well - zero apples is no apples. Therefore, it makes sense (dare I say it is logical?) to use the number 0 to represent FALSE. Using the previous demonstrative phrase, it only takes one apple to make the statement TRUE, and at least one is something. Five is also something, but that would leave out everything from one to four as maybe, and Boolean logic has no MAYBE, so that creates a problem. If some starts at one then there is not need for a MAYBE. Using 1 for something, and therefore TRUE, gives two symbols to use instead of the words TRUE and FALSE, which can get quite long to write in a very short while.

The next step is to introduce the symbols for OR and AND. Here I will, marginally, disagree with how and why your are using center dot • for AND. I am not opposed to that usage, only the reasoning behind the choice. The students have not had algebra yet, so it seems a safer choice than ✖. You can tell the students you have chosen • for AND because it is what they are most likely to encounter later. They should also be told that it can also be written as ✖, and that both can also be used for multiplication ins algebra. The same way that 0 means FALSE for this class, and will mean zero in mathematics (and origin in rectangular coordinates). Likewise using ✚ for OR in your class, while it will mean addition in mathematics. Rather than shelter them now, only to create confusion later, deal with the reality that we only have so many different symbols we can use, and many times they will have different meanings in different places, and knowing when, and when not, to use ✚ as AND is part of learning about Boolean logic.

We need to toss in one more symbol here as well. Replacing the word is with the symbol = (or symbol of your choice) also comes in real handy.

Since the students have not had algebra the next step might be difficult. Connecting the Boolean operators with the mathematical functions. Connecting the addition to OR first, because it is easier to apprehend, you can give the samples FALSE OR FALSE is FALSE, TRUE OR FALSE is TRUE, and TRUE OR TRUE is TRUE. Rewrite them in symbols as 0 ✚ 0 = 0, 1 ✚ 0 = 1 and 1 ✚ 1 = 1. The first two will be obvious, make sense, and get no questions. The third will start them thinking and should get some questions about "why not 1 ✚ 1 = 2?" Return to the apples: zero apples made the statement false while any apples, one, two, or a dozen, made the statement true. So, any number other than zero is true. You can call it part of being a two-state system - either it is zero, or it is other than zero. Therefore, the last of the three samples can be expanded to:

1 ✚ 1 = 2
        2 ≝ some (it isn't "none", our only other choice in Boolean algebra)
1 ✚ 1 = some
        some ≝ TRUE (the apple demonstration)
1 ✚ 1 = TRUE
        TRUE ≝ 1 (our definition of the symbols to use in Boolean algebra)
1 ✚ 1 = 1 (Final answer)

Doing the same thing with multiplication for AND is easier, if they understand that anything multiplied by zero is zero. If they do not have that concept mastered, then it can become more difficult. Finding a demonstration for that can be dicey, but it is possible. One option could be to use unit pricing. Say it costs 8 dollars (or your local currency) for a pizza. if you get one pizza, that's 8 ✖ 1 = 8. If you get four pizzas, that's 8 ✖ 4 = 32. Now, if you get no pizzas, that's the same as zero pizzas, so 8 ✖ 0 = ? The answer, of course, is nothing. What if the price of pizza goes up to 12 dollars, how much for no pizzas? 12 ✖ 0 = 0; still. No matter how much pizza costs, the total price for zero pizzas is zero dollars. Anything else could be used instead, such as speed and time for distance, or wage rate and hours for pay checks, etc.

With the multiplication by zero concept under control, it's time to connect AND with multiplication. Using the same three setups from above gets three samples of the conversion. FALSE AND FALSE is FALSE, TRUE AND FALSE is FALSE. Converting to symbols gives us 0 ✖ 0 = 0, 1 ✖ 0 = 0, and 1 ✖ 1 = 1.

You can expand that into the distributive property, if you wish. [Again, the rule of only two values comes into play with the OR operator.]

TRUE  AND (FALSE OR FALSE) ⇒ (TRUE  AND FALSE) OR (TRUE  AND FALSE) ⇒ FALSE OR FALSE  = FALSE
 1     ✖  ( 0    ✚    0  ) ⇒ (  1    ✖   0   ) ✚  (  1    ✖   0   ) ⇒   0    ✚   0    =  0
TRUE  AND (TRUE  OR FALSE) ⇒ (TRUE  AND TRUE ) OR (TRUE  AND FALSE) ⇒ TRUE  OR FALSE  = TRUE
 1     ✖  ( 1    ✚    0  ) ⇒ (  1    ✖   1   ) ✚  (  1    ✖   0   ) ⇒   1    ✚   0    =  1
TRUE  AND (TRUE  OR TRUE ) ⇒ (TRUE  AND TRUE ) OR (TRUE  AND TRUE ) ⇒ TRUE  OR TRUE   = TRUE
 1     ✖  ( 1    ✚    1  ) ⇒ (  1    ✖   1   ) ✚  (  1    ✖   1   ) ⇒   1    ✚   1    =  2 ≝ 1
FALSE AND (FALSE OR FALSE) ⇒ (FALSE AND FALSE) OR (FALSE AND FALSE) ⇒ FALSE OR FALSE  = FALSE
 0     ✖  ( 0    ✚    0  ) ⇒ (  0    ✖   0   ) ✚  (  0    ✖   0   ) ⇒   0    ✚   0    =  0
FALSE AND (TRUE  OR FALSE) ⇒ (FALSE AND TRUE ) OR (FALSE AND FALSE) ⇒ TRUE  OR FALSE  = TRUE
 0     ✖  ( 1    ✚    0  ) ⇒ (  0    ✖   1   ) ✚  (  0    ✖   0   ) ⇒   1    ✚   0    =  1
FALSE AND (TRUE  OR TRUE ) ⇒ (FALSE AND TRUE ) OR (FALSE AND TRUE ) ⇒ TRUE  OR TRUE   = TRUE
 0     ✖  ( 1    ✚    1  ) ⇒ (  0    ✖   1   ) ✚  (  0    ✖   1   ) ⇒   1    ✚   1    =  2 ≝ 1

TRUE  OR (FALSE AND FALSE) ⇒ (TRUE  OR FALSE) AND (TRUE  OR FALSE ) ⇒ FALSE AND TRUE  = FALSE
 1    ✚  (  0    ✖    0  ) ⇒ (  1   ✚    0  )  ✖  (  1   ✚    0   ) ⇒   0    ✖   1    =  0
TRUE  OR (TRUE  AND FALSE) ⇒ (TRUE  OR TRUE ) AND (TRUE  OR FALSE ) ⇒ TRUE  AND TRUE  = TRUE
 1    ✚  (  1    ✖    0  ) ⇒ (  1   ✚    1  )  ✖  (  1   ✚    0   ) ⇒   1    ✖   1    =  1
TRUE  OR (TRUE  AND TRUE ) ⇒ (TRUE  OR TRUE ) AND (TRUE  OR TRUE  ) ⇒ TRUE  AND TRUE  = TRUE
 1    ✚  (  1    ✖    1  ) ⇒ (  1   ✚    1  )  ✖  (  1   ✚    1   ) ⇒   1    ✖   1    =  1
FALSE OR (FALSE AND FALSE) ⇒ (FALSE OR FALSE) AND (FALSE OR FALSE ) ⇒ FALSE AND FALSE = FALSE
 0    ✚  (  0    ✖    0  ) ⇒ (  0   ✚    0  )  ✖  (  0   ✚    0   ) ⇒   0    ✖   0    =  0
FALSE OR (TRUE  AND FALSE) ⇒ (FALSE OR TRUE ) AND (FALSE OR FALSE ) ⇒ TRUE  AND FALSE = FALSE
 0    ✚  (  1    ✖    0  ) ⇒ (  0   ✚    1  )  ✖  (  0   ✚    0   ) ⇒   1    ✖   0    =  0
FALSE OR (TRUE  AND TRUE ) ⇒ (FALSE OR TRUE ) AND (FALSE OR TRUE  ) ⇒ TRUE  AND TRUE  = TRUE
 0    ✚  (  1    ✖    1  ) ⇒ (  0   ✚    1  )  ✖  (  1   ✚    1   ) ⇒   1    ✖   1    =  1


I know C++ 2003 How to start learning C++ 2017? Tl;dr - the subject is enough. For background, read below.
I am a professional, freelance, embedded software developer. I first learned about C++ in the 90s and taught myself from a book C++ for C programmers.
The beauty of that was that it assumed that I knew C and didn't have to spend chapter after chapter explaining how to declare a variable/what a variable is, function/passing parameters/returning a result, loops, etc, etc, etc.
So, it cut quickly to the chase and I started learning from page 1, rather than skipping forward.

Fast (?) forward a few decades, and I no longer code (much) assembler.  Work seems to be split between C, Ada (mostly for defence) and C++.
It has been four years since my last C++ gig, and, industry being conservative does not adopt new version of languages for some time, until they can be seen to be widely accepted as stable (if any of you non-industry guys what to know why, then we generally want to wait until "they get the bugs out of the new compiler". Given that a lot of embedded can be life-critical, you can understand why).
So, now I am seeing ads requiring C++ 2014 and 2017 (and my latest experience is 2003). The delicious irony of this is that I know, from bitter experience, that coding standards will forbid me from using the new features intruded in those versions.
All of my life, I have taught myself new languages & concepts from books. Earlier this year, I took a leap of faith & taught myself Flutter/Dart (for personal, non-professional use) from a Udemy course. That was an eye-opener, and I won't be responsible for the death of any more trees in future.
But, I digress (this entire screed has been a digression, if you ask me). I have now purchased another Udemy course to learn C++.
And, finally, after all of that, my question is still the same as its title - "I know C++ 2003 How to start learning C++ 2017 ?".
Do I watch the start of each chapter, and skip if I yawn? Do I read the table of contents and take a stab at where to jump in?
Given that you are a group of educators, I imagine that this is not a new situation to you, but am not sure that it has an answer which does not involve the length of pieces of string.

I had a similar problem 8/9 years ago, but with C++11.
The trick is that there is no trick. You simply sit and use the feature you want to use. Besides that it is also beneficial to know C++14 before getting into C++17 and know C++11 before getting familiar with C++14 features. (Obviously prerequisite for C++11 is C++03/98, but that's already covered by OP).
If getting up-to-date with C++17 (C++20 actually was vote in 2020) I would start with feature list grouped here. The problem is that there are so many of them that one may have problems in how to approach them, thus I've provided an ordered list that shows how I would teach it to people:
C++11 warm-up

nullptr - you won't be using NULL of 0 for null pointers anymore
static assertions - allows you to enforce some assertions at compile time
scoped enums - no more enums collisions!
type alias

Basic C++11 stuff

move semantics (overview + SO question) - move semantics and rvalue references are the corner stone of modern C++, what follows is the rule of 5 (or 3/5/0 if being precise)

rvalue references
move semantics in a class
rule of 3/5/0

auto
lambda expressions
ranged for loops - because for(auto const& e: {1, 2, 3}) { std::cout <<e <<'\n'; } is so cool :)
classes related stuff:

default functions/methods
deleted functions/methods
final keyword

constexpr specifier
initializers lists - it is used mainly in std::vector<...> so it's important to know how it works and what are problems involved with them (it is not my favourite C++11 feature)

Extra C++11 stuff

std::tuple

But avoid std::tie, prefer structured bindings from C++17 (you can break the rule here and look them up ahead)

std::thread - no more pthreads!

std::ref - useful when you want to pass references to other threads

variadic templates
forwarding references - useful when want to preserve move semantics when dealing with templates

C++14 & C++17

After these basics I would read about the other C++11 related features or moved to C++14 features listed here (and consult C++11 features list when necessary). Note that C++14 was a nice little amendment to C++11 so there aren't many new (and cool) stuff.
C++17 features worth mentioning (very subjective opinion, at this point you should already know what you want/need to know):

inline variables
structured bindings
if constexpr
fold expressions 1 and fold expressions 2
lambda this capture changes/updates
std::variant + std::optional

C++20

Concepts are the new big thing
immediate functions
IMHO modules will be a dead end as long as C++ will be split into header and implementation fiels (besides Rust have better package/modules concept). But that's just an opinion bouncing in my head.
Remaining C++20 and previous version stuff (obviously only a fraction was covered in this post :)).


Scheme - Which implementation to use for teaching A few days ago, I asked a question if I should use F sharp to learn functional programming and the discussion eventually suggested that I take up Scheme. So, I visited the scheme site (which did not say much) and then I ended up at the MIT site. and I also read on the wikipedia that there are several implementations of scheme.

So, the question is which implementation ( I have given a reference of MIT implementation above) should I use for my beginner class on Scheme.

Racket is a variant of Scheme that is both very good and very popular. The DrRacket system is probably all you need.

DrRacket is widely used and there  is quite a bit of information about it online. It provides a very simple interface.

There are also Scheme plugins for NetBeans and Eclipse if you want a more complete IDE.


What are healthy, productive ways to encourage students to progress to more advanced constructs as opposed to staying with the familiar? In my experience, there are always students who are resistant to moving to more advanced constructs. They want to stay with what they already know. For example, when they are taught arrays, they continue to use individual variables when they are able. When introduced to the foreach loop, they continue to use bounded for loops. When they learn about functions, they resist modularizing their code. After working extensively with arrays, they don’t want to move to using built-in collection types that offer more flexibility and behavior.

It is sometimes difficult to impress upon beginning programmers the usefulness of “new” constructs, because the exercises and programs they are capable of undertaking do not sufficiently demonstrate the power and usefulness of those constructs.

What are ways to encourage beginning programmers to embrace more advanced constructs without penalizing them? I am looking for more "carrot-y" answers than "stick-y".

I'm afraid that there is no single silver bullet.  The problem you've pointed to is very real, and isn't limited to students.  All of us tend to stick to our own familiar toolsets because, well, it's easier.  We know how to use them already.

Enter the Motivating Example.  This mythical thing makes a new topic so useful that the new topic is practically a requirement.  Want to motivate recursion?  Try having kids determine the file-size of a folder (including its sub-folders).  Want to motivate methods?  Try giving a main method that calls them, and ask the kids to create the code that will make everything work.

Finding a great, motivating example feels like a search for hidden treasure; it is painful and slow.  You're seeking something of great value, and it's hard to know where to look.  To make matters worse, a good motivator for one teacher may not work for another, because what makes a motivating example work is intricately tied into both the broader curriculum and what sorts of things the teacher emphasizes within the classroom.

And once found, they are indeed treasures!  Clean, motivating examples make the value of a topic immediately apparent to students.  Resistance melts away, and is replaced by enthusiasm for the new tool that is now making their life easy.

Sometimes I spend weeks trying to find a good motivator.  I've found that teacher communities (such as this very one!) can be great sources of inspiration for them, as can algorithms books.  Or, as Kevin pointed out in a comment (before it was deleted):

  As far as finding motivation is concerned, it may be helpful to look into the history of the construct. For example, foreach used to be called "the iterator pattern," and even appears in the GoF book under that name, before there even was a foreach loop. So foreach isn't about simplifying the code so much as it is about abstracting away the implementation details of "get the size of the container" and "get the nth element" into a single opaque accessor. That suggests that a motivating example might begin by introducing trees, showing traversal code, and then contrasting it with an array.

Even with all of these tools, there are no easy guarantees. I sometimes have to simply wait for my "Eureka!" moment, and teach the best I can in the meantime.