? How To Program #5 - Loops ● SmileBASIC Source

Sign In

*Usernames are case-sensitive
Forgot my password
Creep into the Halloween / Horror Programming Contest (Deadline Extended)

How To Program #5 - Loops

In the previous lesson, we learned about conditional logic and how it can change the flow of the program. It does this by selectively executing chunks of code based on a true or false statement (IF/ELSE/ELSEIF), remember? Now we're going to learn about another way to control the flow of code: looping.

Counting Loops (FOR)

Looping in programming is exactly how it sounds: you make a section of code run in a "loop" (or repeat) over and over again. Let's look at a simple example: say you want to print out "HOI" 10 times. With what we know now, we could do this: PRINT "HOI" PRINT "HOI" PRINT "HOI" PRINT "HOI" PRINT "HOI" PRINT "HOI" PRINT "HOI" PRINT "HOI" PRINT "HOI" PRINT "HOI" But that's pretty repetitive. I just copied and pasted the PRINT line 10 times. But what if you don't want to print "HOI" anymore and instead want to print "BOI" or something. You'd have to go through each print statement and change each one individually. This sucks! Instead, let's do this: FOR I%=1 TO 10 PRINT "HOI" NEXT Blam, son. We just DECIMATED our previous code and made it ULTRA SWAG. Or something. Let's see what's going on at a basic level here. This is a type of loop called the FOR loop. It uses a counter to run the code inside the loop a certain number of times. The code between the FOR line and the NEXT line is the code which runs over and over. Here, it's PRINT "HOI". The I=1 TO 10 part of the FOR loop gives us some information on how many times we should run (this runs 10 times). I is the counter variable, and it starts at 1 because that's how we assigned it (remember, = is the assignment operator). The TO 10 part tells us when we should stop counting. A FOR loop will automatically add 1 to the counter variable each iteration (each time the loop repeats). The counter variable can be anything you want; people generally tend to use single letters like I, J, K, etc. You can use whatever you want.

Using the Loop Counter variable

Let's check out a more in-depth example FOR MYCOUNTER%=5 TO 12 PRINT "Loop counter is: ";MYCOUNTER% NEXT If you run this code, you'll see it print out this: Loop counter is: 5 Loop counter is: 6 Loop counter is: 7 Loop counter is: 8 Loop counter is: 9 Loop counter is: 10 Loop counter is: 11 Loop counter is: 12 I changed the loop counter to MYCOUNTER to show you that you can name this variable whatever you want (it is indeed a variable). We use an integer type because we're not running the loop 10.5 times or something (what would that even mean?). You can start wherever you want and finish wherever you want. The most important thing here is that we use the loop counter WITHIN the loop code, because this exposes a bit about how loops really work. A loop isn't a magic structure: it's actually just a sort of wrapper for a construct you could write yourself. The code still runs from top to bottom in a FOR loop, it just jumps back to the top of the loop until the counter variable reaches a certain point. This is actually a bit of conditional logic: before the loop repeats, it performs a check to see if the counter variable is GREATER THAN the ending value, kind of like IF MYCOUNTER% > 12 THEN (STOP)


Cool, so we can run code a certain number of times. We can also use the counter as we saw in the previous example. If we wanted to make a program that counted from 1 to 100, it'd be easy, right? We don't always want to just go up by 1 while counting, though. Lucky for us, FOR loops are true bros, so they give us the ability to change the counter increment with STEP. FOR I%=1 TO 10 STEP 2 PRINT "Counter: ";I% NEXT If you run this code, you'll see it print out 1,3,5,7, and 9. We're now incrementing the counter variable I by 2 each loop iteration. You'll also notice that no 10 is printed, even though we're "supposed" to stop at 10. But remember, the loop only repeats until the counter passes 10. On the last iteration, the loop counter is 9. After adding 2, this becomes 11, and thus the loop needs to stop because the counter passed the end. We can also count backwards: FOR I%=10 TO 1 STEP -1 PRINT "Counter:";I% NEXT Running this, you'll see it go from 10 to 1. The FOR loop detects that the counter is counting in the "other" direction, so instead of checking to see if the counter is GREATER THAN the end before stopping, it checks to see if it's LESS THAN. You really don't need to worry about the specifics too much though. When you see a FOR loop, just knowing the start and end points and how much you increment the counter by is enough.

Conditional Loops (WHILE)

FOR loops have a set conditional: repeat until a value reaches a certain point. These are great when you want to run something a certain number of times, but sometimes we don't know how many times we want to loop. Instead, we want something to happen over and over until a condition is reached. For this, we can use a WHILE or REPEAT loop. One of the most (in)famous types of loops is the infinite loop. This is a great way to show how WHILE loops are structured, so let's check it out: WHILE TRUE PRINT "YOOOOO" WEND If you run this, you'll notice that the screen is just dumping tons and tons of "YOOOOO", and that the program doesn't end. You'll have to stop this program manually by pressing SELECT or START. A WHILE loop runs the code within over and over while the condition given is true. The condition is evaluated (calculated to be true or false) before each loop iteration. It's kind of like the loop version of an IF statement. In our example, since the condition is always TRUE, the loop runs forever. Alternatively, if we had given a FALSE, the loop wouldn't have run at all. Unlike the FOR loop, WHILE loops end with a WEND. This is kind of a legacy thing; the original BASIC did this, so SmileBASIC does it too. You'll find that other programming languages have more consistent structures for these things. Here's a better example of a more real-world WHILE loop: DIM ENTRY$ INPUT "Please say PANCAKE";ENTRY$ WHILE ENTRY$!="PANCAKE" PRINT "YOU'RE NOT LISTENING!" INPUT "Say PANCAKE please";ENTRY$ WEND PRINT "Thank you for saying PANCAKE" As silly as this example is, it's actually quite a lot like the loops you'll be writing in your code. Please run it first so you can get an idea of what's going on. We start with a simple request for the word "PANCAKE". We store it into a string variable we created called ENTRY$. Then we enter the WHILE loop. Remember, the condition is always checked BEFORE the loop is run, even the first time. The != operator returns TRUE if the operands (things being operated on) are NOT equal (we use == to check for equality, and != to check for inequality). Here, we're checking to see if what you entered in ENTRY$ is NOT equal to "PANCAKE". You can read this WHILE loop in English like "While entry is not equal to PANCAKE, repeat this code". So, if you correctly typed in PANCAKE, the conditional will return false, and the loop will exit. If you typed in anything else, ENTRY$ will not match "PANCAKE", and the conditional will return true and the loop will run. Let's say you ran this program and typed in "NO". The conditional will be true and the PRINT/INPUT inside the loop is run. Since we're asking for ENTRY$ again inside the loop, we get a new value. Afterwards, the WHILE loop jumps back to the top and checks the conditional again. If you still haven't typed in PANCAKE, the code will be run yet again. This will repeat until you finally enter PANCAKE. Even if the explanation is a bit loopy, the idea is simple. It's best to run the code, see what's happening when you type stuff, then look at the code to get the idea. The code speaks for you; you don't need an explanation about each detail if you know the basics of how a WHILE loop works. Think about what the program does when you run it: it asks for PANCAKE, then it keeps asking for PANCAKE until you enter it correctly. When you lay out the description of the program in words, you can see how the description lines up with the code, and you might start to get a better idea of how to write your own code. Unless of course you can already do this, in which case WOO BIG DEAL YOU'RE A SMERT. just kidding please don't be upset!

Problem Solving: Imitating a FOR Loop

You can imitate a FOR loop with a WHILE loop. This is because a WHILE loop is a more general loop, while the FOR loop is specialized for counting. You have all the tools you need to do this, but I'll walk you through it. I want you to make a WHILE loop which does the same thing as the first FOR loop in this tutorial (the HOI one). I encourage you to write this on your own, so try to do so before expanding this next section. Whenever you're faced with a problem to solve, you should always make sure you understand the problem itself. I mean yeah, everyone always tells you this, but really, understanding parts of the problem is not the same as understanding the problem as a whole. You may have ideas bouncing around in your head about how to solve bits and pieces, but without understanding the WHOLE problem, you won't be able to piece these ideas together into a solution. Luckily it's simple here: "Make a FOR loop". Now the next step: what's a FOR loop? It's not like you need a definition or anything; it's better to understand how it works than to memorize it. So, let's run with our train of thought: >We know a FOR loop runs the code within a certain number of times. ->We know it does this with a counter. -->We know we need to use a WHILE loop to complete this task --->We know a WHILE loop doesn't have a counter ---->We need to add a counter to the WHILE loop OK cool, maybe you came up with a different sequence of thoughts, but hopefully you came to the same conclusion. FOR loops have counters, WHILE loops do not. So let's create a counter. We need to know what the variable should start at though. Looking at the old FOR loop, we see that the counter starts at 1. Here we go: DIM I%=1 Not so hard, right? OK so we at least have the counter variable, but what about the OTHER parts of FOR loop counting? Let's do our logical thought process again: >We know a FOR loop counts from a starting value to an ending value. ->We know the FOR loop performs a conditional check to see if the counter reached the end -->We know WHILE loops also loop based on a conditional check. --->We can use the FOR loop conditional as the WHILE loop conditional In our original FOR loop, we count up until our counter reaches 10. Thus, we loop while the counter is less than or equal to 10. Now we can write our WHILE loop skeleton to match: DIM I%=1 WHILE I%<=10 PRINT "HOI" WEND Remember, <= is the "less than or equal to" comparison operator. It is true if the first operand is less than or equal to the second operand. Now we're almost finished! If you run this though, it loops forever. This is because I% never changes; it's always 1 so it's always less than or equal to 10. If we think about the last part of a FOR loop, we'll remember that it also increments the counter variable by 1 (or whatever the STEP is, which defaults to 1). So, while the loop is running (meaning inside the loop), we'll need to increase I% by one each time. That's easy! DIM I%=1 WHILE I%<=10 PRINT "HOI" INC I%,1 WEND And that's it! If you run this code, it should print HOI 10 times, just like our FOR loop. If you understand how to do this, that's great! That means you have a good understanding of how FOR loops works and how looping works in general. Remember: programming is all about being able to solve problems like this on your own. It's not something you can memorize. If you're still having trouble, that's OK! You might get the hang of it soon; I'll keep going over these problem solving bits and hopefully it'll just click! There's also a dark side to this though: sometimes, people just aren't good at this sort of thing. That doesn't mean you're not smart, it just means that programming probably isn't for you. The ability to naturally put together strict logical constructs through a kind of intuition is a bit niche. Because really, you're just "intuiting" how to solve these things. There's no steps on how to do this; you can't read a manual on how to solve every programming problem ever. It's logical, but the process of getting to the solution kind of... isn't, and it's sometimes a strange thing. Given enough time, I think everyone could wrap their minds around this concept, but you have to decide for yourself if you want to spend the time doing this. However, I'm NOT discouraging you from pursuing this! Even if you're having a hard time just coming up with solutions, it might just be that you need a bit of experience. On the other hand, if this is all just stupidly easy, then you probably don't need to be reading this in the first place! Wait until I come out with the advanced tutorials! Also, it could just be that I'm bad at writing tutorials

One more loop (REPEAT)

There's one more type of loop we need to talk about, but it works about the same as the WHILE loop. It's called the REPEAT loop, and the main difference is that it checks the conditional at the END of the loop rather than the beginning. This ensures that the loop is run at LEAST once, since the code runs from top to bottom THEN checks to see if it'll repeat before looping. Oh and one more thing: instead of looping while a conditional is true, it loops until a condition is true. Basically this means it'll keep running while the conditional is FALSE, and will stop when it becomes TRUE (until true, while true... you'll see). Here's an example of using the REPEAT loop: DIM SECRET% REPEAT INPUT "Enter secret code";SECRET% UNTIL SECRET%==8675309 PRINT "You've entered the secret code." Try it out. Notice the program asks for the secret code inside the loop and that it runs at least once, even if you enter it correctly on the first try. It helps that the loop conditional must be put at the bottom, as it makes it clear that the loop won't check for repeating until the end. Also notice that the syntax is basically completely different than a WHILE loop. It's unfortunate that it's like this (and many programming languages don't have this inconsistency), but if you want to use this kind of loop, you'll just have to memorize it (blegh). Remember that this runs UNTIL the conditional is true, which means that UNTIL we enter the matching secret, the loop will repeat.


We can run code over and over again using loops. FOR loops run code a certain number of times by using a counter. WHILE loops are more generic and run code while a condition is true.
3 votes
  • programming
  • tutorial
  • basic
  • concept
  • fundamental
  • randomouscrap
  • loop
  • while
  • for
  • repeat
7 Comment(s) swimgaming swimgaming Pokemon Is Awesome! I love Pokemon! Express Yourself Video Games I like to play video games! Hobbies thanks! I didn't figure out using inc for the while code at first then felt dumb after I read how to do it. I also added a thing saying whether or not the number should be lower or higher in the repeat part. randomouscrap randomouscrap Robot Hidden Easter Eggs osu! Is Awesome! I love osu! Express Yourself Drawing I like to draw! Hobbies Cool! I'm glad people are doing the challenges! swimgaming swimgaming Pokemon Is Awesome! I love Pokemon! Express Yourself Video Games I like to play video games! Hobbies I also made a random number game out of it. which kind of is just the higher and lower thing. digDug digDug Ran through these tutorials to check them out. Really liking them. I like the flow, and the challenge near the end of this one. Can't wait to see more and more till I get confused!! randomouscrap randomouscrap Robot Hidden Easter Eggs osu! Is Awesome! I love osu! Express Yourself Drawing I like to draw! Hobbies Thank you! Now that there's a contest running, maybe I'll start working on these again. digDug digDug Definitely! Patiently awaiting. :) Minxrod Minxrod Summer 2016 Contest Participant I participated in the SmileBASIC Source Summer 2016 Contest! Programming Contest Expert Programmer Programming no longer gives me any trouble. Come to me for help, if you like! Programming Strength Pokemon Is Awesome! I love Pokemon! Express Yourself you're a smert! Also, in the conclusion you didn't mention repeat loops! 0/10 just kidding I love these tutorials that's why I am reading them over again :P