Resources | Subject Notes | Computer Science
Structured programming is a fundamental paradigm in computer science that emphasizes the use of control flow structures to create well-organized and easy-to-understand programs. It avoids the use of unstructured constructs like `GOTO` statements, which can lead to complex and difficult-to-debug code. The core building blocks of structured programming are sequence, selection (conditional statements), and iteration (loops).
Pseudo code is an informal way of describing an algorithm. It uses a combination of natural language and structured programming constructs to outline the steps of a program. Writing efficient pseudo code involves:
Sequence is the simplest control flow structure. Instructions are executed one after the other.
Example:
Step | Description |
---|---|
1 | Start the program. |
2 | Read input. |
3 | Process the input. |
4 | Display the output. |
5 | End the program. |
The `if-else` statement allows the program to execute different blocks of code based on a condition.
Example:
Step | Description |
---|---|
1 | Start the program. |
2 | Read a number. |
3 | IF the number is positive: |
4 | Display "Positive". |
5 | ELSE: |
6 | Display "Non-positive". |
7 | End the program. |
The `for` loop allows a block of code to be executed repeatedly a specified number of times.
Example:
Step | Description |
---|---|
1 | Start the program. |
2 | Initialize a counter variable to 1. |
3 | FOR the counter variable from 1 to 10: |
4 | Display the value of the counter. |
5 | END FOR |
6 | End the program. |
The `while` loop allows a block of code to be executed repeatedly as long as a specified condition is true.
Example:
Step | Description |
---|---|
1 | Start the program. |
2 | Initialize a counter variable to 1. |
3 | WHILE the counter variable is less than or equal to 10: |
4 | Display the value of the counter. |
5 | Increment the counter variable by 1. |
6 | END WHILE |
7 | End the program. |
Let's illustrate with an example of calculating the factorial of a number using pseudo code.
Step | Description |
---|---|
1 | Start the program. |
2 | Read an integer number (n). |
3 | IF n is less than 0: |
4 | Display "Factorial is not defined for negative numbers". |
5 | ELSE: |
6 | Set factorial = 1. |
7 | FOR i from 1 to n: |
8 | Set factorial = factorial * i. |
9 | END FOR |
10 | Display the value of factorial. |
11 | End the program. |