Resources | Subject Notes | Computer Science
This section focuses on representing algorithms using pseudo-code, specifically utilizing the fundamental constructs of sequence, decision (if/else), and iteration (loops).
Sequence refers to the order in which instructions are executed. Instructions are executed one after the other, in the order they appear.
Decision constructs allow an algorithm to make choices based on conditions. The most common construct is the 'if-else' statement.
If a condition is true, a block of code is executed. Else, if the condition is false, a different block of code is executed.
Pseudo-code | Explanation |
---|---|
IF condition THEN // Code to execute if the condition is true ELSE // Code to execute if the condition is false ENDIF |
The algorithm checks a condition. If the condition is true, the code within the 'THEN' block is executed. Otherwise, the code within the 'ELSE' block is executed. |
Example: Determining if a number is positive, negative, or zero.
Iteration allows a block of code to be executed repeatedly. Common types of loops include 'for' and 'while' loops.
A 'for' loop is used when the number of iterations is known in advance.
Pseudo-code | Explanation |
---|---|
FOR each item IN sequence // Code to execute for each item ENDFOR |
The code within the 'FOR' loop is executed once for each item in the specified sequence. |
Example: Calculating the sum of numbers in a list.
A 'while' loop is used when the number of iterations is not known in advance, and the loop continues as long as a condition is true.
Pseudo-code | Explanation |
---|---|
WHILE condition IS TRUE // Code to execute while the condition is true ENDWHILE |
The code within the 'WHILE' loop is executed repeatedly as long as the specified condition remains true. |
Example: Repeatedly asking for input until a valid value is entered.
Algorithms often combine sequence, decision, and iteration constructs to solve complex problems. For example, an algorithm might use a 'while' loop to repeatedly ask for input until a certain condition is met, and then use an 'if-else' statement to process the input based on its value.
Figure: A diagram illustrating the combination of sequence, decision, and iteration in a simple algorithm (e.g., checking if a number is even or odd).