We've explored writing a few statements, and I've already talked about the order of those statements, and of our instructions being important. But when you write more code, dozens, hundreds or thousands of instructions, you won't want to always execute all of your statements exactly the same way in exactly the same order every single time.
You'll want some choice in control and you can have that. However, to understand how to control your code, it's easiest to first understand what happens if you don't even try. How does code run? Let's get it clear. The typical way your code executes can be best explained with a quote from Alice in Wonderland:
Fig 4.1.1: Alice’s quote explains how code runs
This is a pretty good description of the default way your code will execute that unless you say otherwise. When it comes to time to run your program, it will begin with your first statement. Execute that and finish it completely. Move on to the next. Finish that, then move on to the next, one after the other.
This might be a good way to read a story, but it's not good enough for us.
Only in the most trivial programs will you be able to just begin at the beginning, go right onto the end and then stop.
We must control how we move through our source code. While code will still run in general from top to bottom, we need to ask questions because every time the program runs, things can be a little different.
For example, we might want to know at one point if today's actual sales amount greater than today's projected sales amount If it is, we'll make that number display in green. If it's not, make it show in red. If the user just enters their password, does it actually match what we have on record for them? If it does, we'll execute the code to let them access the protected area. If not, we'll show a message telling them to try again.
We often write a lot of statements that we actually hope will never be executed. We write code to deal with incorrect data. We write code to deal with errors like wrong passwords, no internet connection, not enough memory, missing files and so on. So, we need to make sure that this code is only executed when something's gone wrong.
While there's often code we don't really want to execute, we can also have the opposite where we want to take a few statements we have and run those same statements a hundred times or a thousand times.
Fig 4.1.2: A chart showing why a program may not flow straight from top to bottom
For example, if I'm writing a program to calculate payroll for a thousand people, I don't want to copy and paste my instructions a thousand times. I just want to repeat a section of code, whether that's to calculate payroll or animate a bunch of enemy spaceships across the screen.
We'll need to find ways to group our code together to make it easier to say, for example, do these statements but don't do those statements; repeat those statements but don't repeat these statements. All of that is the focus of this chapter.