DEV Community

Discussion on: What is the simplest code to explain a loop?

Collapse
 
joshcheek profile image
Josh Cheek

I was once struggling to teach this to a student, tried several different ideas and the one that finally clicked for him was something like this (Ruby):

puts "hello"
puts "hello"
puts "hello"
puts "hello"
puts "hello"

Is the same as:

5.times do
 puts "hello"
end

Here, I've printed "hello" 5 times. But what if I wanted to print it 100 times? In the top example, I have to copy and paste that line 95 more times, pretty painful. In the bottom example, I just change 5 to 100, much easier.

I think specifically the language 5.times do made sense to him and allowed him to understand that the line of code could be executed more than once. Probably connected a missing idea in his mental model. I suppose, you could also give a model for how computers work, then it would emerge from the model. Eg explain that code is stored as data in memory and there is an instruction pointer keeping track of which one we're on, and then basically break the instructions down to some made up assembly language. I feel like that would work really well for a subset of students but really poorly for most of them 😝

Collapse
 
yaser profile image
Yaser Al-Najjar

Hehe... skip about the pointer cuz that won't work for sure :D

Loved the idea of avoid redundant boring code with a loop -high five- !