Pseudocode (meaning "fake code") is a method for representing an algorithm using an informal, high-level description of its logic. It's written for humans to read, not for computers to execute. It uses the structural conventions of a programming language, like IF
, FOR
, and WHILE
, but omits the strict syntax rules.
· Advantages: It's quick to write, easy to understand, and simple to modify. It allows the programmer to focus purely on the algorithm's logic without worrying about the specifics of a programming language.
· Disadvantage: It's not standardized. Different programmers might use slightly different styles.
Common Keywords & Constructs
While there are no strict rules, several keywords and constructs are commonly used to represent different actions in pseudocode.
Category |
Keywords |
Purpose |
Input/Output |
|
To get data from the user or show results. |
Processing |
|
To assign values or perform calculations. |
Conditionals |
|
To make decisions and execute different blocks of logic. |
Iteration (Loops) |
|
To repeat a block of instructions. |
Structure |
|
To define the beginning and end of the algorithm. |
Examples in Pseudocode
1. Basic Example (Sequential Logic)
· Problem: Calculate the area and perimeter of a square given one side.
· Logic: The algorithm takes the side length as input, applies the formulas for area (side2) and perimeter (4×side), and prints both results.
START
// Get input from the user
READ side
// Perform calculations
SET area = side * side
SET perimeter = 4 * side
// Display the results
PRINT "Area is:", area
PRINT "Perimeter is:", perimeter
END
2. Moderate Example (Conditional Logic)
· Problem: Check if a number is positive, negative, or zero.
·
Logic: This requires a chain of IF-ELSE IF-ELSE
conditions to check the number against zero.
START
// Get input
READ number
// Check the conditions
IF number > 0 THEN
PRINT "The number is Positive."
ELSE IF number < 0 THEN
PRINT "The number is Negative."
ELSE
PRINT "The number is Zero."
ENDIF
END
3. Advanced Example (Iterative Logic)
· Problem: Check if a given positive number is a prime number.
· Logic: A prime number is only divisible by 1 and itself. The algorithm checks for any divisors from 2 up to the number's square root. A flag variable is used to keep track of whether a divisor is found.
START
READ number
// Assume the number is prime until proven otherwise
SET isPrime = true
// Handle base cases: 0 and 1 are not prime
IF number <= 1 THEN
isPrime = false
ELSE
// Loop from 2 up to the square root of the number
FOR i from 2 to SQRT(number) DO
IF (number % i) == 0 THEN
// A divisor was found, so it's not a prime number
isPrime = false
BREAK // Exit the loop early
ENDIF
ENDFOR
ENDIF
// Print the final result based on the flag
IF isPrime == true THEN
PRINT number, "is a prime number."
ELSE
PRINT number, "is not a prime number."
ENDIF
END