Resources | Subject Notes | Computer Science
An algorithm is a finite sequence of well-defined, ordered steps that, when executed, solves a specific problem or achieves a particular task. Algorithms are fundamental to computer science and are used in everything from simple calculations to complex artificial intelligence.
Key characteristics of an algorithm:
Pseudo-code is an informal way of describing an algorithm. It uses a combination of natural language and mathematical-like notation to outline the steps involved. It's easier to understand than actual program code but more structured than plain English.
Common Pseudo-code constructs:
IF (condition) THEN [statements] ELSE [statements] ENDIF
WHILE (condition) DO [statements] ENDWHILE
, FOR i = start TO end DO [statements] STEP increment ENDFOR
FUNCTION function_name(parameters) [statements] RETURN value ENDFUNCTION
Flowcharts are visual representations of algorithms, using standardized symbols to illustrate the flow of control. They provide a clear and easy-to-understand overview of the algorithm's logic.
Common flowchart symbols:
Symbol | Description |
---|---|
Represents the start and end of the algorithm. | |
Represents a process or operation. | |
Represents a decision point (e.g., a condition). | |
Represents input or output operations. | |
Represents the direction of flow. |
START INPUT number1 INPUT number2 IF number1 > number2 THEN maximum = number1 ELSE maximum = number2 ENDIF OUTPUT maximum END
def find_maximum(num1, num2): if num1 > num2: return num1 else: return num2 number1 = float(input("Enter the first number: ")) number2 = float(input("Enter the second number: ")) maximum_number = find_maximum(number1, number2) print("The maximum number is:", maximum_number)
Amending an algorithm involves modifying it to correct errors, improve efficiency, or add new features. This often requires careful analysis of the original algorithm and a systematic approach to making changes.
Common amendment techniques:
Example: Consider the previous maximum-finding algorithm. We could amend it to handle negative numbers more robustly.
START INPUT number1 INPUT number2 IF number1 > number2 THEN maximum = number1 ELSE maximum = number2 ENDIF OUTPUT maximum END
In this case, the original algorithm already handles negative numbers correctly, so no amendment is needed. However, if we wanted to add a check for invalid input (e.g., non-numeric input), we would add a conditional statement to handle that.
Algorithm complexity describes how the execution time or memory usage of an algorithm grows as the input size increases. Common notations include Big O notation.
Examples:
Consider the following problem: Write an algorithm to calculate the area of a triangle, given its base and height.
Try to: