DEV Community

Yaser Al-Najjar
Yaser Al-Najjar

Posted on

What is the simplest code to explain a loop?

Here is my question for the discussion:

How would you write a code to explain a loop in the simplest possible way? Given that your audience is absolute beginners.

  • PS: use any programming language!

Top comments (40)

Collapse
 
alchermd profile image
John Alcher
for page in book:
    print(page)
Collapse
 
yaser profile image
Yaser Al-Najjar

Wow... looks really simple, printing all the pages in a book !

Collapse
 
alchermd profile image
John Alcher • Edited

Most of the time, you use a for loop when you need to access items (pages) from a collection/array (book). Some languages do this by using indices

// Most C-Style languages
for (int i = 0; i < book.length; i++) {
    print(book[i]);
}

... while some languages hide this behind a simpler syntax (like the example that I give which is Python). Though for loops are also used to generate a set of numbers (i.e 1-10), it's not really an interesting example and is harder to visualize for beginners.

Hopefully that helps!

Thread Thread
 
yaser profile image
Yaser Al-Najjar • Edited

Yep we love teaching Python cuz it's the best language IMHO to teach... simple expressive syntax.

Javascript is also good to start with, but there are tons of crap from the old standard like var and for in, just to "not break old programs" :|

Thread Thread
 
alchermd profile image
John Alcher

Yep we love teaching Python cuz it's the best language IMHO to teach... simple expressive syntax.

I share the same sentiments! I offer tutorials to my fellow CS students and Python is my go-to language for explaining basic programming constructs.

Ideally though, a student should be well-versed on at least one scripting language (Python, PHP, JS, etc.) and a compiled one (Java, C++, C#, etc.) since some concepts are harder to visualize on certain languages. Like, functional programming is better taught in JS than C++ and pointers are better taught in C than PHP.

Thread Thread
 
yaser profile image
Yaser Al-Najjar

Totally agree with you, each lang serves better in explaining some concepts.

A bit regretting that my first lang was C cuz I spent lots of time understanding pointers and arrays instead of going into actual domains problems :D

Same goes to Python, I see many people explaining data structures in Python while in the very beginning they don't solve an actual problem cuz Python has lists already! That's why C is the way to go IMO for data structures.

Thread Thread
 
slavius profile image
Slavius • Edited

In for loops you can empoy this little trick to emphasize decrementing from max to 0:

int max = 10;
for (i = max; i --> 0;) {
  printf(".");
}

It is just pretty-formatted i-- > 0
What it does it decrements i and makes sure it's > 0 in the comparison part of the for leaving out the increment/decrement part.
Works the opposite way (end to start) so it's not suitable for processing lists where ascending order matters.

Thread Thread
 
alchermd profile image
John Alcher

That's a neat trick! But it looks something more of a trick to get the shortest solution to a programming quiz rather than a practical solution, IMO.

Thread Thread
 
slavius profile image
Slavius

Let's call it a syntactic sugar. It makes the code shorter, more visual while still keeping the same functionality; but may make someone puzzled about what it does on first sight as it's not common.

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

Collapse
 
okolbay profile image
andrew

If I would a teacher, I would forbid mentioning “for” and “collection” in one sentence - processing collections should be done with map, foreach, etc(I guess they are called a higher order functions?) and never with loops, where scope is unclear and intention is unclear. Loop can do map, reduce, filter, or all of them at the same time. “for” or “foreach” constructs that accept a code block with the scope of a calling code are just loops in disguise.

just my two opinionated cents on this matter ))

Collapse
 
yaser profile image
Yaser Al-Najjar

I'm actually planning to explain while-loop at first... then going into lists (no other collections), then mention how to iterate through that list using for, I guess it's very intuitive this way IMHO... what do you think?

The way map & foreach works in the functional manner is just JavaScript specific, creates more ambiguity, and actually the new way (ES6) got to be for of which is poorly intuitive :(

Collapse
 
okolbay profile image
andrew

as many other things in CS loops for processing lists are intuitive and not the best choice in the end )

what I wanted to outline is that during education its very important to communicate that “this is not the solution”, but rather an introduction.

PS would be nice to come up with examples for all basic concepts without bringing other basic concepts - like loops without lists, recursion without tree data structure etc )))

Thread Thread
 
yaser profile image
Yaser Al-Najjar

"this is not the solution"

I really hate when I watch a "this is a demo" course, cuz most of them are like that, and I'm like: "So where the is the actual solution?". Ends with me inspecting github repos to see how it's actually implemented :D

Ah yeah... I totally agree about mentioning one concept totally alone.

We try to follow a strict manner in showing one thing at a time, while trying to mix things after the user gets the knack of that one principle alone.

Thread Thread
 
okolbay profile image
andrew

what I ment is that you should outline that even with simplest building blocks like loops, beginner developer should question if its a good fit for their problem and seek for better )
I agree, with entry-level courses it might be tough to combine with keeping interest for the subject, so good luck!)

Collapse
 
0xyasser profile image
Yasser A
time = 00:00:00
SunIsSet = true
while (sunIsSet):
    print("it's night time!")
    time += 1
    if(time > 05:00:00 < 18:30:00):
       SunIsSet =false
       print("it's day time!")
Collapse
 
yaser profile image
Yaser Al-Najjar

love the idea, but it doesn't run actually

Traceback (most recent call last):
  File "python", line 1
    time = 00:00:00
             ^
SyntaxError: invalid syntax
Collapse
 
0xyasser profile image
Yasser A

Oh I was't expecting it to run, it meant to explain the idea of loops but here is one that works.

import datetime
time =datetime.datetime(100,1,1,0,0,0) # arbitrary day
sunIsSet = True
while (sunIsSet):
    if(time.hour > 5 and time.hour < 18):
       sunIsSet = False
       print("time is:",time.time().isoformat(), " it's day time!")
    else:
       print("time is:",time.time().isoformat()," it's night time!")
    time = time + datetime.timedelta(0,1)
Thread Thread
 
yaser profile image
Yaser Al-Najjar

oops... the imports killed the simplicity :(

Collapse
 
alexmacniven profile image
Alex Macniven

At absolute beginner level, I wish I knew about enumeration (Python)

# in
my_list = ['apple', 'orange']
for index, item in enumerate(my_list):
    print(index, item)

# out
0 apple
1 orange
Collapse
 
karloabapo profile image
Karlo Abapo

enumerate and list comprehensions are the stuff after you get past the basic looping and collections. :)

Collapse
 
kepta profile image
Kushan Joshi • Edited

Counting is the most fundamental thing most humans understand.

counter = 0
while (counter < 10) {
   counter = counter + 1
   print('count', counter)
}
Collapse
 
yaser profile image
Yaser Al-Najjar

Yep, I realized all programming tutorials use this way to explain a loop.

But simple people would say, hmm what's the point of showing 1 to 10 in the screen :D

Collapse
 
kepta profile image
Kushan Joshi • Edited

Well, when they ask, tell them it is similar to a kid is learning to count till 10.

My point is — these weird real world examples donot translate well to computers. Sure it sounds fancy to talk about Gas or book pages, but it doesn’t really communicate that computers are dry, dumb and boring.

In my humble opinion certain aspects of computers are best learnt without real life examples and thinking in terms of just computer-y stuff.

Thread Thread
 
yaser profile image
Yaser Al-Najjar

You've got a point

But after I watched courses on both Treehouse and Pluralsight, oh man Treehouse makes the points drill into your brain cuz they illustrate first with real examples with animations / motion graphic, and then they go in the tech nerdy way.

For example, they explain containers in a very interesting way: teamtreehouse.com/library/what-is-...

Collapse
 
ibraback profile image
Ala Douagi
for (const page of book) {
  console.log(page);
}
Collapse
 
devmazee2057282 profile image
dewbiez • Edited
foreach ($person as $individual) {
    print $individual;
}
Collapse
 
yaser profile image
Yaser Al-Najjar

Another guy came up with this:

speedometer = 0
while (speedometer <= 220):
    print("car speed is", speedometer)
    speedometer += 1

And then we can go into and operator with:

speedometer = 0
hold_in_gas = True
while (speedometer <= 220 and hold_in_gas):
    print("car speed is", speedometer)
    speedometer += 1
Collapse
 
nektro profile image
Meghan (she/her) • Edited

Do go off the book example:

class Book
  read() {
    for (const p of this.pages) {
      p.read();
    }
  }
}