Structured programming notes
3. Nested Control Structures
3.3. Combining selection and iteration
1. Structured Programming Recap
Structured programming emphasizes three main constructs:
-
Sequence: Execute statements one after another.
-
Selection: Make decisions (
if,if-else,switch). -
Iteration: Repeat actions (
for,while,do-while).
Combining selection and iteration means using loops with conditional decisions inside them, while keeping the code clear, modular, and easy to follow.
2. Combining Selection and Iteration
Concept:
-
Iteration repeats a block of code.
-
Selection chooses which statements to execute inside that block.
-
Together, they let a program repeat actions conditionally.
Flow:
3. Example 1: Print only even numbers (structured style)
Problem: Print all even numbers from 1 to 10.
Pseudocode (Structured Programming Style):
Explanation:
-
Iteration:
FOR i = 1 TO 10repeats for each number. -
Selection:
IF i MOD 2 = 0checks if the number is even. -
Only even numbers are printed.
4. Example 2: Sum positive numbers from a list
Problem: Sum all positive numbers in an array.
Pseudocode:
Explanation:
-
Iteration goes through all numbers in the array.
-
Selection filters only positive numbers to add.
-
Combines repetition and decision-making clearly.
Key Points in Structured Programming
-
Keep loops and conditional blocks nested neatly.
-
Avoid goto statements; use structured loops and if-else.
-
Combine selection and iteration to filter, validate, or process data repeatedly.