Skip to main content

Programming Fundamentals

This document provides comprehensive coverage of programming fundamentals for the DSE ICT examination. Basic programming concepts and SQL are covered in programming-and-databases.md. This document extends those topics with deeper treatment of algorithms, string manipulation, file handling, debugging, and DSE-specific exam techniques.


Variables and Constants

Variable Naming Conventions

RuleDescriptionValidInvalid
Must start with a letterCannot begin with a number or special characterscore2score
No spacesUse camelCase or underscoresmyScoremy score
Case sensitiveScore and score are different variablestotalN/A
Must be descriptiveName should indicate the purposestudentAgex
No reserved wordsCannot use language keywordsmyClassclass
Consistent naming styleUse the same convention throughoutcamelCaseMixed_styles

Data Types in Detail

Data TypeSize (typical)RangePrecision
Integer2--8 bytes231-2^{31} to 23112^{31}-1 (32-bit)Exact
Float/Real4--8 bytes±3.4×1038\pm 3.4 \times 10^{-38} to 3.4×10383.4 \times 10^{38}~7 decimal digits
Double8 bytes±1.7×10308\pm 1.7 \times 10^{-308} to 1.7×103081.7 \times 10^{308}~15 decimal digits
StringVariableDepends on implementationN/A
Boolean1 byteTrue / FalseN/A
Character1 byteSingle character (ASCII/Unicode)N/A

Type coercion and conversion:

Converting between types is a common source of errors. In many languages, mixing types in an expression causes automatic type promotion.

ConversionDescriptionRisk
Integer to FloatAlways safe, no data lossNone
Float to IntegerTruncates the decimal partLoss of precision
String to NumberParses the string; fails if non-numericRuntime error
Number to StringConverts the number to its text representationNone
Worked Example: Type Conversion Issues
x = 7 / 2 # x = 3.5 (float division)
y = 7 // 2 # y = 3 (integer division)
z = int(3.9) # z = 3 (truncation, NOT rounding)

# Common error:
score = input("Enter score: ") # score is a STRING, e.g., "85"
total = score + 10 # ERROR: cannot add string and integer
total = int(score) + 10 # CORRECT: convert string to int first

The input() function always returns a string. Forgetting to convert to the appropriate numeric type before performing arithmetic is one of the most common errors in student programs.


Control Structures in Depth

Nested Selection

Nested IF statements occur when one IF statement is placed inside another. Each level of nesting should be indented for clarity.

Worked Example: Nested IF for Fee Calculation

A cinema charges different ticket prices based on age and day:

  • Children (under 12): 50onweekdays,50 on weekdays, 60 on weekends
  • Adults (12--64): 100onweekdays,100 on weekdays, 120 on weekends
  • Seniors (65+): 60onweekdays,60 on weekdays, 70 on weekends
BEGIN
INPUT age, isWeekend
IF age < 12 THEN
IF isWeekend = TRUE THEN
price = 60
ELSE
price = 50
ENDIF
ELSE IF age <= 64 THEN
IF isWeekend = TRUE THEN
price = 120
ELSE
price = 100
ENDIF
ELSE
IF isWeekend = TRUE THEN
price = 70
ELSE
price = 60
ENDIF
ENDIF
OUTPUT price
END

FOR vs WHILE Loops

AspectFOR LoopWHILE Loop
TypeCount-controlledCondition-controlled
Known iterations?Yes, the number of iterations is knownNo, depends on a condition
CounterAutomatically managedMust be updated manually in the loop
Infinite loop riskLow (counter reaches limit)High (condition may never become false)
Use caseProcessing arrays, fixed repetitionsUser input validation, unknown counts

Choosing between FOR and WHILE:

  • Use FOR when you know exactly how many times the loop should run (e.g., processing every element in an array).
  • Use WHILE when the number of iterations depends on a condition that is evaluated at runtime (e.g., keep asking for input until the user enters a valid value).

Loop Patterns

Sentinel-Controlled Loop

A loop that continues until a special value (sentinel) is entered.

BEGIN
SET total = 0
SET count = 0
INPUT score
WHILE score <> -1
total = total + score
count = count + 1
INPUT score
ENDWHILE
IF count > 0 THEN
OUTPUT total / count
ELSE
OUTPUT "No valid data"
ENDIF
END

Accumulator Pattern

Accumulates a running total.

BEGIN
SET sum = 0
FOR i = 1 TO 100
sum = sum + i
NEXT i
OUTPUT sum
END

Counting Pattern

Counts how many items satisfy a condition.

BEGIN
SET count = 0
FOR i = 0 TO N - 1
IF numbers[i] > 50 THEN
count = count + 1
ENDIF
NEXT i
OUTPUT count
END

Finding Maximum/Minimum

BEGIN
SET maximum = numbers[0]
FOR i = 1 TO N - 1
IF numbers[i] > maximum THEN
maximum = numbers[i]
ENDIF
NEXT i
OUTPUT maximum
END
Worked Example: Combined Loop Patterns

Write a program to read N numbers, output the sum, average, maximum, minimum, and count of numbers above the average.

BEGIN
INPUT N
SET numbers = array of size N
FOR i = 0 TO N - 1
INPUT numbers[i]
NEXT i

SET sum = 0
SET maximum = numbers[0]
SET minimum = numbers[0]
FOR i = 0 TO N - 1
sum = sum + numbers[i]
IF numbers[i] > maximum THEN
maximum = numbers[i]
ENDIF
IF numbers[i] < minimum THEN
minimum = numbers[i]
ENDIF
NEXT i

SET average = sum / N
SET aboveAverage = 0
FOR i = 0 TO N - 1
IF numbers[i] > average THEN
aboveAverage = aboveAverage + 1
ENDIF
NEXT i

OUTPUT "Sum: " + sum
OUTPUT "Average: " + average
OUTPUT "Maximum: " + maximum
OUTPUT "Minimum: " + minimum
OUTPUT "Above average: " + aboveAverage
END

Functions and Procedures in Depth

Parameter Passing

MechanismDescriptionEffect on Original Variable
Pass by valueA copy of the argument is passed to the function/procedureOriginal unchanged
Pass by referenceA reference (address) to the original variable is passedOriginal CAN be changed

In many exam-style pseudocode languages, parameters are passed by value by default. To pass by reference (allowing the procedure to modify the original), some notations use BYREF.

Worked Example: Pass by Value vs Reference
PROCEDURE addBonus(BYREF salary, bonus)
salary = salary + bonus
END PROCEDURE

BEGIN
SET pay = 30000
CALL addBonus(pay, 5000)
OUTPUT pay
END

Because salary is passed BYREF, the original variable pay is modified. Output: 35000.

If salary were passed by value (default), pay would remain 30000 because the procedure would modify only a local copy.

Recursion

A recursive function calls itself to solve a problem by breaking it into smaller subproblems.

Worked Example: Recursive Fibonacci
FUNCTION fibonacci(n)
IF n <= 1 THEN
RETURN n
ELSE
RETURN fibonacci(n - 1) + fibonacci(n - 2)
ENDIF
END FUNCTION

Trace for fibonacci(5):

CallResult
fibonacci(5)fibonacci(4) + fibonacci(3)
fibonacci(4)fibonacci(3) + fibonacci(2)
fibonacci(3)fibonacci(2) + fibonacci(1)
fibonacci(2)fibonacci(1) + fibonacci(0)
fibonacci(1)1
fibonacci(0)0

Working back up: fib(2) = 1 + 0 = 1, fib(3) = 1 + 1 = 2, fib(4) = 2 + 1 = 3, fib(5) = 3 + 2 = 5.


String Manipulation

String operations are frequently tested in DSE ICT programming questions.

Common String Operations

OperationDescriptionExample
LengthReturns the number of characters in a stringLEN("Hello") = 5
ConcatenationJoins two strings together"Hello" + " " + "World" = "Hello World"
Substring/ExtractExtracts a portion of a stringMID("Hello", 2, 3) = "ell"
LeftExtracts characters from the leftLEFT("Hello", 3) = "Hel"
RightExtracts characters from the rightRIGHT("Hello", 2) = "lo"
Upper caseConverts all characters to uppercaseUPPER("hello") = "HELLO"
Lower caseConverts all characters to lowercaseLOWER("HELLO") = "hello"
Find/PositionFinds the position of a substringFIND("ll", "Hello") = 3
ReplaceReplaces all occurrences of a substringREPLACE("aab", "a", "x") = "xxb"
CompareCompares two strings alphabetically"Apple" < "Banana" is True

Character Analysis

Worked Example: Count Vowels in a String
FUNCTION countVowels(text)
SET count = 0
SET vowels = "aeiouAEIOU"
FOR i = 0 TO LEN(text) - 1
SET char = MID(text, i + 1, 1)
IF FIND(char, vowels) > 0 THEN
count = count + 1
ENDIF
NEXT i
RETURN count
END FUNCTION

Note: In pseudocode, string indexing often starts at 1 (unlike Python which starts at 0). Check the specific convention used in your exam.

Worked Example: Reverse a String
FUNCTION reverseString(text)
SET result = ""
FOR i = LEN(text) DOWNTO 1
result = result + MID(text, i, 1)
NEXT i
RETURN result
END FUNCTION

For reverseString("Hello"):

Iterationicharresult
15"o""o"
24"l""ol"
33"l""oll"
42"e""olle"
51"H""olleH"
Worked Example: Palindrome Check
FUNCTION isPalindrome(text)
SET length = LEN(text)
FOR i = 1 TO length / 2
IF MID(text, i, 1) <> MID(text, length - i + 1, 1) THEN
RETURN FALSE
ENDIF
NEXT i
RETURN TRUE
END FUNCTION

This compares the first character with the last, the second with the second-to-last, and so on. If any pair does not match, the function returns FALSE immediately.


File Input/Output in Depth

File Operations

OperationDescriptionMode
OpenPrepare a file for reading or writingRead/Write
ReadRead data from an open fileRead
WriteWrite data to an open file (overwrites existing)Write
AppendAdd data to the end of an existing fileAppend
CloseRelease the file and save any buffered dataN/A

Sequential vs Random Access

FeatureSequential AccessRandom Access
Access methodRecords read one after anotherJump directly to any record
Speed for reading allFast (sequential read)Same or slower
Speed for finding specific recordMust read all preceding recordsDirect access, very fast
File typeText filesBinary files, database files
ModificationDifficult (must rewrite entire file)Easy (overwrite specific record)
ExampleCSV, TXTDirect-access binary files
Worked Example: Read and Process File Data

A file students.txt contains student records, one per line, in the format: Name,Class,Score

Chan Tai Man,5A,85
Lee Siu Ming,5B,72
Wong Ka Wai,5A,93

Write a program to read the file and find the student with the highest score.

BEGIN
OPEN FILE "students.txt" FOR READ
SET highestScore = -1
SET topStudent = ""

WHILE NOT end of file
READ line FROM FILE
SET commaPos = FIND(",", line)
SET name = LEFT(line, commaPos - 1)
SET rest = MID(line, commaPos + 1, LEN(line) - commaPos)
SET commaPos2 = FIND(",", rest)
SET class = LEFT(rest, commaPos2 - 1)
SET scoreStr = MID(rest, commaPos2 + 1, LEN(rest) - commaPos2)
SET score = CONVERT_TO_INT(scoreStr)

IF score > highestScore THEN
highestScore = score
topStudent = name
ENDIF
ENDWHILE

CLOSE FILE
OUTPUT "Top student: " + topStudent + " with score: " + highestScore
END

Algorithms -- Search and Sort

Linear search checks each element in sequence until the target is found or all elements have been checked.

AspectValue
Best caseO(1) -- found at first position
Worst caseO(n) -- found at last position or not found
Average caseO(n/2)
Data requirementNone (works on unsorted data)
FUNCTION linearSearch(arr, size, target)
FOR i = 0 TO size - 1
IF arr[i] = target THEN
RETURN i
ENDIF
NEXT i
RETURN -1
END FUNCTION

Binary search works on sorted arrays by repeatedly dividing the search range in half.

AspectValue
Best caseO(1) -- found at middle on first check
Worst caseO(log n)
Data requirementArray MUST be sorted in ascending order
FUNCTION binarySearch(arr, size, target)
SET low = 0
SET high = size - 1
WHILE low <= high
SET mid = (low + high) / 2 (integer division)
IF arr[mid] = target THEN
RETURN mid
ELSE IF arr[mid] < target THEN
low = mid + 1
ELSE
high = mid - 1
ENDIF
ENDWHILE
RETURN -1
END FUNCTION
Worked Example: Binary Search Trace

Search for 23 in the sorted array: [2, 5, 8, 12, 16, 23, 38, 45, 56]

Steplowhighmidarr[mid]ComparisonAction
10841616 < 23low = 5
25863838 > 23high = 5
35552323 = 23Found at index 5

Result: 23 is found at index 5.

Insertion Sort

Insertion sort builds a sorted array one element at a time by inserting each element into its correct position among the previously sorted elements.

AspectValue
Best caseO(n) -- already sorted
Worst caseO(n^2) -- reverse sorted
StableYes
FUNCTION insertionSort(arr, size)
FOR i = 1 TO size - 1
SET key = arr[i]
SET j = i - 1
WHILE j >= 0 AND arr[j] > key
arr[j + 1] = arr[j]
j = j - 1
ENDWHILE
arr[j + 1] = key
NEXT i
END FUNCTION

Comparison of Sorting Algorithms

AlgorithmBest CaseAverageWorst CaseStableMemory
Bubble SortO(n)O(n^2)O(n^2)YesO(1)
Insertion SortO(n)O(n^2)O(n^2)YesO(1)
Selection SortO(n^2)O(n^2)O(n^2)NoO(1)
Binary SearchO(log n) per lookupN/AN/AN/AN/A

Top-Down Design

Top-down design (stepwise refinement) is a problem-solving approach where a complex problem is broken down into smaller, more manageable sub-problems. Each sub-problem is then further refined until the solutions are simple enough to implement directly.

Process

  1. Identify the main task: State the overall problem in one sentence.
  2. Decompose into sub-tasks: Break the main task into 2--5 major sub-tasks.
  3. Refine each sub-task: Further break down each sub-task until each component is a simple, well-defined operation.
  4. Implement each component: Write code (or pseudocode) for each leaf-level component.
  5. Combine and test: Integrate all components and test the complete solution.
Worked Example: Top-Down Design for a Student Report Generator

Main task: Generate a student report showing each student's scores, average, and grade.

Level 1 decomposition:

  1. Read student data from file
  2. Calculate each student's average and grade
  3. Display the report

Level 2 refinement:

  1. Read student data from file 1.1 Open file for reading 1.2 Read each line and parse name, scores 1.3 Store data in arrays 1.4 Close file

  2. Calculate each student's average and grade 2.1 For each student, sum their scores 2.2 Calculate average 2.3 Assign grade based on average

  3. Display the report 3.1 Print header 3.2 For each student, print name, scores, average, grade 3.3 Print class statistics (class average, highest, lowest)

Each leaf-level component (1.1, 1.2, 1.3, 1.4, 2.1, 2.2, 2.3, 3.1, 3.2, 3.3) can be implemented as a simple function or procedure.

Advantages of Top-Down Design

AdvantageDescription
ManageabilityLarge problems become manageable
ClarityEach component has a clear, single responsibility
ReusabilityWell-defined components can be reused in other programs
TestabilityEach component can be tested independently
TeamworkDifferent team members can work on different components simultaneously
Easier debuggingErrors can be isolated to specific components

Flowcharts and Pseudocode -- DSE Exam Requirements

Flowchart Symbols

SymbolShapeMeaning
Start/EndOvalBeginning or end of the program
Input/OutputParallelogramData input or output
ProcessRectangleA calculation or assignment
DecisionDiamondA conditional branch (Yes/No)
Flow arrowArrowDirection of flow
ConnectorCircleConnects to another part of the flowchart
SubroutineRectangle with double sidesA call to a function/procedure

Pseudocode Conventions for DSE

The DSE ICT examination uses structured pseudocode. Key conventions:

ConstructSyntax
Start/EndBEGIN ... END
AssignmentSET variable = expression
InputINPUT variable
OutputOUTPUT expression
IFIF condition THEN ... ELSE ... ENDIF
FORFOR counter = start TO end ... NEXT counter
WHILEWHILE condition ... ENDWHILE
REPEAT-UNTILREPEAT ... UNTIL condition
FunctionFUNCTION name(parameters) ... RETURN value END FUNCTION
ProcedurePROCEDURE name(parameters) ... END PROCEDURE
Array accessarray[index]
Comment// This is a comment

Converting Between Flowcharts and Pseudocode

Every flowchart symbol maps directly to pseudocode:

Flowchart SymbolPseudocode Equivalent
Oval (Start)BEGIN
Parallelogram (Input)INPUT variable
Rectangle (Process)SET variable = expression
Diamond (Decision)IF condition THEN ... ELSE ... ENDIF
Parallelogram (Output)OUTPUT expression
Oval (End)END
Arrow (loop)FOR ... NEXT or WHILE ... ENDWHILE

Debugging and Testing

Types of Errors

Error TypeDescriptionDetected WhenExample
Syntax errorCode violates the language's grammar rulesCompilationMissing THEN in IF statement
Logic errorProgram runs but produces incorrect resultsDuring testingUsing > instead of >=
Runtime errorProgram crashes during execution due to an invalid operationDuring executionDivision by zero, array out of bounds

Debugging Techniques

TechniqueDescription
Trace tablesManually trace through the algorithm recording variable values
Print statementsAdd OUTPUT statements at key points to inspect variable values
Dry runExecute the algorithm on paper with sample data
BreakpointsPause execution at specific lines (in an IDE)
Step-throughExecute one line at a time, inspecting variables
Rubber duckingExplain the code line by line to identify the error

Testing Strategies

Testing TypeDescription
Normal dataTest with typical, expected input values
Boundary dataTest with values at the edges of valid ranges (e.g., 0, 100)
Erroneous dataTest with invalid input (e.g., negative age, non-numeric input)
Extreme dataTest with very large or very small values
Absent dataTest with empty or missing input
Worked Example: Testing a Grade Program

Program: Assign grades based on score (A: >= 80, B: >= 60, C: >= 40, F: < 40).

Test CaseInputExpected OutputPurpose
Normal75BTypical input
Normal45CTypical input
Boundary80AEdge of A range
Boundary79BJust below A
Boundary60BEdge of B range
Boundary40CEdge of C range
Boundary39FJust below C
Boundary0FMinimum valid
Boundary100AMaximum valid
Erroneous-5Error messageNegative score
Erroneous105Error messageScore exceeds max
Erroneous"abc"Error messageNon-numeric input

Common Pitfalls

  1. Off-by-one errors in loops: When iterating through an array of size N, the loop should run from 0 to N-1 (inclusive), not 0 to N. Accessing index N causes an out-of-bounds error.

  2. Not initialising variables before use: If a variable used as a maximum or minimum is initialised to 0 instead of the first array element, the algorithm fails when all values are negative.

  3. Confusing assignment (=) and comparison (==): In many languages, = assigns a value and == compares. Using = in a condition assigns the value instead of comparing it.

  4. Forgetting to update the loop counter in WHILE loops: If the loop variable is not modified inside the loop body, the condition never becomes false, causing an infinite loop.

  5. Binary search requires sorted data: Applying binary search to an unsorted array produces incorrect results. Always verify the array is sorted before using binary search.

  6. String indexing: Some pseudocode conventions use 1-based indexing (first character is at position 1), while programming languages like Python use 0-based indexing. Be consistent with the convention specified in the exam.

  7. Infinite recursion without a base case: A recursive function must have a condition that stops the recursion. Without it, the function calls itself indefinitely, eventually causing a stack overflow.

  8. Not closing files: Forgetting to close a file after reading or writing can cause data loss (for writes) or resource leaks (files remaining locked).

  9. Integer division truncation: In many languages, dividing two integers produces an integer result (truncated). 7 / 2 gives 3, not 3.5. Use floating-point division when a decimal result is needed.

  10. Scope of variables: Local variables inside a function are not accessible outside the function. Using a variable name that conflicts with a global variable can lead to unexpected behaviour.


Practice Problems

Question 1: Algorithm Design with Trace Table

Write pseudocode for a program that reads N integers and counts how many are positive, how many are negative, and how many are zero. Trace the algorithm with input: N = 5, values: 3, -2, 0, 7, -1.

Answer:

BEGIN
INPUT N
SET positive = 0
SET negative = 0
SET zero = 0
FOR i = 1 TO N
INPUT num
IF num > 0 THEN
positive = positive + 1
ELSE IF num < 0 THEN
negative = negative + 1
ELSE
zero = zero + 1
ENDIF
NEXT i
OUTPUT positive, negative, zero
END

Trace table:

inumnum > 0num < 0positivenegativezero
13True-100
2-2FalseTrue110
30FalseFalse111
47True-211
5-1FalseTrue221

Output: positive = 2, negative = 2, zero = 1

Question 2: String Processing

Write a function in pseudocode that takes a string and returns the number of words in the string. A word is defined as a sequence of characters separated by spaces.

(a) Write the pseudocode.

(b) Trace the function with the input: "DSE ICT is challenging".

Answer:

(a)

FUNCTION countWords(text)
SET count = 0
SET inWord = FALSE
FOR i = 1 TO LEN(text)
SET char = MID(text, i, 1)
IF char <> " " THEN
IF inWord = FALSE THEN
count = count + 1
inWord = TRUE
ENDIF
ELSE
inWord = FALSE
ENDIF
NEXT i
RETURN count
END FUNCTION

(b) Trace for "DSE ICT is challenging" (LEN = 21):

icharinWord (before)ActioncountinWord (after)
1DFALSENew word1TRUE
2STRUENone1TRUE
3ETRUENone1TRUE
4" "TRUEEnd word1FALSE
5IFALSENew word2TRUE
6CTRUENone2TRUE
7TTRUENone2TRUE
8" "TRUEEnd word2FALSE
9iFALSENew word3TRUE
10sTRUENone3TRUE
11" "TRUEEnd word3FALSE
12cFALSENew word4TRUE
13-21(remaining chars)TRUENone4TRUE

Result: 4 words

Question 3: Binary Search

(a) Explain why binary search requires the data to be sorted.

(b) Trace a binary search for the value 7 in the sorted array: [1, 3, 5, 7, 9, 11, 13, 15, 17].

(c) State the maximum number of comparisons needed to search an array of 1000 elements using binary search.

Answer:

(a) Binary search works by comparing the target with the middle element and discarding half of the remaining elements each time. This strategy only works correctly if the elements are in a known order (sorted ascending). If the array is unsorted, discarding half the elements based on a comparison with the middle element could eliminate the target, making the algorithm fail.

(b) Array: [1, 3, 5, 7, 9, 11, 13, 15, 17], target = 7

Steplowhighmidarr[mid]ComparisonAction
108499 > 7high = 3
203133 < 7low = 2
323255 < 7low = 3
433377 = 7Found

Result: Found at index 3.

(c) Binary search has O(log n) complexity. For n = 1000: log2(1000)9.97\log_2(1000) \approx 9.97. The maximum number of comparisons is log2(1000)=10\lceil \log_2(1000) \rceil = 10. (The array needs at most 10 comparisons because 210=1024>10002^{10} = 1024 > 1000.)

Question 4: Top-Down Design and Implementation

A teacher needs a program to process student attendance data. The program should:

  1. Read attendance records from a file (one record per student: name followed by P/A for each day).
  2. Calculate each student's attendance percentage.
  3. Output a list of students whose attendance is below 80%.

(a) Apply top-down design to decompose this problem into sub-tasks.

(b) Write pseudocode for the complete solution.

Answer:

(a)

Level 1: Process attendance data

Level 2:

  1. Read attendance data 1.1 Open file 1.2 Read each student's attendance record 1.3 Parse name and attendance marks 1.4 Store in arrays 1.5 Close file
  2. Calculate attendance percentages 2.1 For each student, count P marks 2.2 Calculate percentage: (P count / total days) * 100
  3. Identify students below 80% 3.1 Check each student's percentage 3.2 Output those below 80%

(b)

BEGIN
OPEN FILE "attendance.txt" FOR READ
SET names = empty array
SET percentages = empty array
SET studentCount = 0

WHILE NOT end of file
READ line FROM FILE
SET spacePos = FIND(" ", line)
SET name = LEFT(line, spacePos - 1)
SET attendance = MID(line, spacePos + 1, LEN(line) - spacePos)

SET totalDays = LEN(attendance)
SET presentDays = 0
FOR i = 1 TO totalDays
IF MID(attendance, i, 1) = "P" THEN
presentDays = presentDays + 1
ENDIF
NEXT i

SET percentage = (presentDays / totalDays) * 100
APPEND name TO names
APPEND percentage TO percentages
studentCount = studentCount + 1
ENDWHILE
CLOSE FILE

OUTPUT "Students with attendance below 80%:"
FOR i = 0 TO studentCount - 1
IF percentages[i] < 80 THEN
OUTPUT names[i] + " - " + percentages[i] + "%"
ENDIF
NEXT i
END
Question 5: Comprehensive Programming Question

A shop sells items with prices stored in an array. A discount is applied based on the total purchase amount:

  • Total < 100: no discount
  • 100 <= Total < 500: 5% discount
  • 500 <= Total < 1000: 10% discount
  • Total >= 1000: 15% discount

Write a program that:

(a) Reads N item prices into an array.

(b) Calculates the total before discount.

(c) Determines the discount percentage.

(d) Calculates the final amount after discount.

(e) Outputs the total, discount percentage, and final amount.

Answer:

BEGIN
INPUT N
SET prices = array of size N
SET total = 0

FOR i = 0 TO N - 1
INPUT prices[i]
total = total + prices[i]
NEXT i

OUTPUT "Total before discount: " + total

IF total >= 1000 THEN
discountRate = 15
ELSE IF total >= 500 THEN
discountRate = 10
ELSE IF total >= 100 THEN
discountRate = 5
ELSE
discountRate = 0
ENDIF

SET discountAmount = total * discountRate / 100
SET finalAmount = total - discountAmount

OUTPUT "Discount: " + discountRate + "%"
OUTPUT "Discount amount: " + discountAmount
OUTPUT "Final amount: " + finalAmount
END