Introduction: Programming with Structure and Logic
Welcome to the chapter on Structured Programming! Don't worry if the name sounds complicated; it’s simply a set of rules and best practices that help us write code that is clear, easy to read, and simple to fix (debug).
Think of structured programming like building with LEGO bricks. Instead of just throwing pieces together randomly, you use instructions (the structure) to ensure your final creation is stable and makes sense.
By mastering these concepts, you will learn how to organize your code into powerful, logical steps. This is absolutely essential for every computer scientist!
1. The Building Blocks of Structured Programming
Structured programming relies entirely on three fundamental control structures. Every single program you will ever write, no matter how complex, uses only these three techniques.
1.1 Sequence (Step-by-Step)
Sequence is the most basic control structure. It means the instructions in the program are executed one after the other, in the exact order they are written.
Analogy: Following a recipe or tying your shoes. You must complete Step 1 before moving to Step 2, and so on.
- Instruction A is executed.
- Then Instruction B is executed.
- Then Instruction C is executed.
Key Takeaway: Sequence dictates the linear, top-to-bottom flow of execution.
1.2 Selection (Decision Making)
Selection (or Conditionals) allows the program to make a decision based on whether a certain condition is true or false. This determines which path of instructions the program will follow.
We use constructs like IF, ELSE IF (sometimes written as ELIF), and ELSE.
How Selection Works:
- The program checks a condition (e.g., Is the temperature above 20 degrees?).
- If the condition is TRUE, one block of code is executed.
- If the condition is FALSE, a different block of code may be executed (the ELSE part).
Example:
IF (User_is_18_or_older) THEN
DISPLAY "Welcome, you can enter."
ELSE
DISPLAY "Access Denied."
END IF
Important Point: Use ELSE IF (ELIF) when you have multiple conditions to check, and ELSE catches everything that didn't meet the previous conditions.
Quick Review: Selection allows your program to choose one path out of two or more possibilities.
1.3 Iteration (Repetition/Loops)
Iteration means repeating a block of code multiple times. This is incredibly useful for saving time and making programs efficient (imagine having to write "print 'Hello'" 100 times!).
There are two main types of iteration structures you need to know:
1.3.1 Definite (Fixed) Iteration: FOR Loops
Used when you know exactly how many times the code needs to repeat beforehand. This is a count-controlled loop.
Analogy: Counting reps at the gym. You decide beforehand that you will do 10 push-ups (the loop repeats exactly 10 times).
FOR Count FROM 1 TO 10 DO
// Code block will run 10 times
END FOR
1.3.2 Indefinite (Conditional) Iteration: WHILE and REPEAT Loops
Used when you do not know beforehand how many times the code needs to repeat. The loop depends on a condition:
1. Start-Condition Loop (WHILE...DO...END WHILE): Checks the condition before running the code block. If the condition is false at the start, the loop body may never execute.
WHILE (Score_is_less_than_100) DO
Add_Points()
END WHILE
2. Post-Condition Loop (REPEAT...UNTIL): Executes the code block first, then tests the condition at the end. Because the check happens at the bottom, the code inside runs at least once.
REPEAT
Enter_Password()
UNTIL (Password_is_valid)
Common Mistake to Avoid: The Infinite Loop!
If the condition in a loop can never be satisfied or changed (e.g., WHILE 5 > 2 DO...), the loop will run forever and hang your program. Always ensure that the loop body updates the variable tested in the condition!
2. Modular Programming: Procedures, Functions, and Scope
As programs get larger, they become harder to manage. Modular Programming (or top-down design) solves this problem by breaking down a large program into smaller, self-contained mini-programs called modules or sub-programs.
2.1 Why Use Modules (Sub-programs)?
Using procedures and functions is essential because it promotes:
- Readability: The main program looks cleaner and easier to understand.
- Maintainability: If there is an error (a bug), you only have to look in the small module, not the whole massive program.
- Reusability: You can use the same module (e.g., calculating tax) multiple times in different parts of your code, or even in different programs, without rewriting it.
2.2 Procedures
A Procedure is a named sequence of instructions designed to carry out a specific task.
- They are used to perform an action (e.g., displaying a message, saving a file).
- Procedures execute their instructions and then return control back to the main program.
- Crucially, they do not necessarily return a value.
Example: A procedure might be called DisplayWelcomeMessage(). It performs its action (printing the message) and finishes. It doesn't calculate or give back a result.
2.3 Functions
A Function is similar to a procedure, but it has one key difference:
- Functions are designed to calculate a value.
- Functions must return a value to the main program (or the section of code that called it).
- They act like mini-calculators.
Example: A function might be called CalculateArea(). You give it the width and height, it performs the calculation, and it returns the resulting area value.
Memory Aid: A Function always returns a Final answer (value). A Procedure just follows instructions.
2.4 Parameters (Passing Data)
How do we get data into our procedures and functions so they can do their job? We use Parameters (sometimes called Arguments).
A Parameter is a variable used to pass data or information into a sub-program when it is called.
Analogy: If your function is a blender, the parameters are the ingredients (fruits, milk) you put into the blender so it can make the smoothie.
When you define a function or procedure, you specify the parameters it expects:
FUNCTION CalculateArea (Width, Height)
Area = Width * Height
RETURN Area
END FUNCTION
When the main program calls this function, it supplies the actual data:
My_Space = CalculateArea(10, 5) // 10 and 5 are the values passed in
In this example: Width and Height are the parameters defined in the function, and 10 and 5 are the values passed to those parameters when the function is used.
2.5 Variable Scope: Local vs Global Variables
Scope refers to the visibility and accessibility of a variable across different parts of a program:
- Local Variables: Declared inside a specific subroutine (function or procedure). They are created when the subroutine runs and destroyed when it finishes. They cannot be accessed or modified from outside that subroutine.
- Global Variables: Declared in the main program and accessible from anywhere throughout the entire program.
Why Local Variables Are Preferred:
Local variables prevent accidental side-effects (unintended changes to data in other parts of the program), make subroutines self-contained and easier to reuse, and free up memory once the subroutine finishes executing.
Did You Know? Modular programming was a revolutionary idea in the 1960s! Before that, code was often written as one long, confusing block, making debugging an absolute nightmare. Structured programming made complex software possible!
Quick Review Box: Structured Programming Essentials
The Three Control Structures:
1. Sequence: Do A, then B, then C in sequential order.
2. Selection: Check conditions using IF, ELSE IF (ELIF), and ELSE.
3. Iteration: Repeat code using definite (FOR) or indefinite (WHILE, REPEAT...UNTIL) loops.
Modular Programming and Scope:
• Procedure: Performs a task; does not need to return a value.
• Function: Calculates a value; MUST return a value.
• Parameter: Data passed into a sub-program when called.
• Local Scope: Variables confined to a subroutine, avoiding unintended global side-effects.