Build reports from records and text files
Choose a record for related fields
A product code is STRING because leading zeroes may matter. Its quantity is INTEGER because it is counted. A record keeps these fields under one identifier; an array stores several products.
Read files without losing the final line
Open for READ, test EOF before reading, process each successful read, then close. Convert a numeric STRING only after validation. An empty file is a legitimate test, not an error in the problem.
OPENFILE "demo.txt" FOR WRITE
WRITEFILE "demo.txt", "4"
WRITEFILE "demo.txt", "7"
CLOSEFILE "demo.txt"
DECLARE Line : STRING
DECLARE Total : INTEGER
Total ← 0
OPENFILE "demo.txt" FOR READ
WHILE NOT EOF("demo.txt") DO
READFILE "demo.txt", Line
Total ← Total + STR_TO_NUM(Line)
ENDWHILE
CLOSEFILE "demo.txt"
OUTPUT Total
This self-contained demonstration creates its own file. In a question where the file already exists, do not open it for WRITE: that would erase the data.
Explain your choices
In the reasoning box, explain why product codes should not be INTEGER, why mixed fields suit a record, and why EOF is checked before READFILE. Then solve the two reports, including their empty/no-match cases.
The checker supplies sales.txt, one numeric integer string or invalid text per line. Output the count of numeric lines, then their total. Ignore invalid lines. Close the file.
Klik Jalankan untuk melihat output di sini.
Read Limit, then three product codes and integer quantities. Define TYPE Product and store an array of records. Output codes whose quantity is BELOW Limit, in input order; if none, output none.
Klik Jalankan untuk melihat output di sini.
Explain your choice of data structure and loop. Identify one boundary case and predict its result. For a subroutine, explain what is returned or changed in the caller.
Saved for this sitting on this browser. Review this yourself or with your teacher; these explanations are not automatically marked.
Review your explanation against these criteria
- My types and data structure match the data and the question.
- I justified the loop and checked its first and last iterations.
- Initial values and rejected operations preserve the intended state.
- My test includes input, purpose and expected result.
- I distinguished returning a value from printing and changing caller state.