Arrays and Strings Pseudocode
Arrays and Strings in Pseudocode
Array and string questions are common because they test indexing and loop control.
Array basics
Array stores multiple values under one name.
Example:
A = [3, 5, 7, 9]
If 0-indexed:
- A[0] = 3
- A[1] = 5
- A[2] = 7
- A[3] = 9
If 1-indexed:
- A[1] = 3
- A[2] = 5
- A[3] = 7
- A[4] = 9
Always check indexing in the question.
Array sum
SET sum = 0
FOR i = 0 TO n-1
SET sum = sum + A[i]
END FOR
DISPLAY sum
Maximum element
SET max = A[0]
FOR i = 1 TO n-1
IF A[i] > max THEN
SET max = A[i]
END IF
END FOR
DISPLAY max
Count even numbers
SET count = 0
FOR i = 0 TO n-1
IF A[i] % 2 = 0 THEN
SET count = count + 1
END IF
END FOR
DISPLAY count
Reverse array output
FOR i = n-1 DOWNTO 0
DISPLAY A[i]
END FOR
String basics
String is a sequence of characters.
Example:
S = "CODE"
If 0-indexed:
- S[0] = C
- S[1] = O
- S[2] = D
- S[3] = E
Palindrome string
String is palindrome if it reads same forward and backward.
SET i = 0
SET j = length(S) - 1
SET flag = true
WHILE i < j
IF S[i] != S[j] THEN
SET flag = false
BREAK
END IF
SET i = i + 1
SET j = j - 1
END WHILE
DISPLAY flag
Examples:
- MADAM: palindrome
- LEVEL: palindrome
- CODE: not palindrome
Character frequency
Concept:
- Use count array/map.
- Increment count for each character.
Pseudocode:
FOR each character ch in S
count[ch] = count[ch] + 1
END FOR
Common array/string traps
- Accessing
A[n]in 0-indexed array is out of bounds. - Loop
i <= nis wrong for 0-indexed array of size n. - In string comparison, case matters:
Aandaare different. - Space may be counted as character if not explicitly ignored.