Читать книгу Beginning Programming All-in-One For Dummies - Wallace Wang - Страница 36

The three parts of structured programming

Оглавление

To keep programs organized, structured programming teaches programmers that any program can be divided into three distinct parts:

 Sequences:Sequences are simply groups of commands that the computer follows, one after another. Most simple programs consist of a list of commands that the computer follows from start to finish, as shown in Figure 2-2.FIGURE 2-2: Sequences consist of groups of commands that the computer follows, one after another.

 Branches:Branches consist of two or more groups of commands. At any given time, the computer may choose to follow one group of commands or another. Branches allow a program to make a decision based on a certain condition.For example, at the end of most video games, the program asks you, “Do you want to play again (Yes or No)?” If you choose Yes, the program lets you play the video game again. If you choose No, the program stops running, as shown in Figure 2-3.FIGURE 2-3: Branches let the computer choose which group of commands to run at any given time.A branch starts with a command that evaluates a condition (such as determining whether the user chose Yes or No). Then, based on this answer, whether it’s true or false, the branch chooses which group of commands to follow next.

 Loops: Sometimes you may want the computer to run the same commands over and over again. For example, a program may ask the user for a password. If the user types an invalid password, the program displays an error message and asks the user to type the password again.If you wanted your program to ask the user for a password three times, you could write the same group of commands to ask for the password three times, but that would be wasteful. Not only would this force you to type the same commands multiple times, but if you wanted to modify these commands, you’d have to modify them in three different locations as well. Loops are basically a shortcut to writing one or more commands multiple times.A loop consists of two parts:The group of commands that the loop repeatsA command that defines how many times the loop should run

By combining sequences, branches, and loops, you can design any program and understand how the program works at each step.

Dividing a program into sequences, branches, and loops can help you isolate and organize groups of related commands into discrete “chunks” of code. That way, you can yank out a chunk of code, modify it, and plug it back in without affecting the rest of the program.

Beginning Programming All-in-One For Dummies

Подняться наверх