Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
A long scenario question. A teacher has the names of 5 students in the file Names.txt, one name a line. Write a program that:
Passed.txt;Use constants for the number of students and the pass mark. Then dry-run it for the names Ola, Ben, Chen, Dev and Eva and the typed marks 64, 105, 48, 50, 91 and 37.
OPENFILE <name> FOR READ or FOR WRITE (WRITE makes a new file and loses the old data), then READFILE <name>, <variable> to read the next line, or WRITEFILE <name>, <value> to write one, then CLOSEFILE <name>. Files keep data after the program stops.
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, go through the solution one step at a time, and check each step against your own.
A model answer in pseudocode.
CONSTANT Students ← 5
CONSTANT PassMark ← 50
DECLARE Names : ARRAY[1:5] OF STRING
DECLARE Marks : ARRAY[1:5] OF INTEGER
DECLARE Index : INTEGER
DECLARE Mark : INTEGER
DECLARE Best : INTEGER
DECLARE Passed : INTEGER
// Read the five names from a file, one a line
OPENFILE "Names.txt" FOR READ
FOR Index ← 1 TO Students
READFILE "Names.txt", Names[Index]
NEXT Index
CLOSEFILE "Names.txt"
// Input each mark, in range 0 to 100
FOR Index ← 1 TO Students
REPEAT
OUTPUT "Mark for ", Names[Index]
INPUT Mark
IF Mark < 0 OR Mark > 100
THEN
OUTPUT "Mark out of range"
ENDIF
UNTIL Mark >= 0 AND Mark <= 100
Marks[Index] ← Mark
NEXT Index
// The position of the highest mark
Best ← 1
FOR Index ← 2 TO Students
IF Marks[Index] > Marks[Best]
THEN
Best ← Index
ENDIF
NEXT Index
// Write the names of those who passed, and count them
Passed ← 0
OPENFILE "Passed.txt" FOR WRITE
FOR Index ← 1 TO Students
IF Marks[Index] >= PassMark
THEN
WRITEFILE "Passed.txt", Names[Index]
Passed ← Passed + 1
ENDIF
NEXT Index
CLOSEFILE "Passed.txt"
OUTPUT "Highest mark ", Marks[Best], " by ", Names[Best]
OUTPUT "Number who passed ", PassedThe dry run. 105 is rejected, so Ben is asked again and gets 48. The marks are Ola 64, Ben 48, Chen 50, Dev 91 and Eva 37. The highest is 91, by Dev. Ola, Chen and Dev have 50 or more, so Passed.txt holds those three names and the count is 3. Chen's 50 counts, because the test is >=.
How such an answer is marked. One mark for each point, up to 15:
Watch out. Opening Passed.txt inside the loop would make a new file each time, and only the last name would be left.
Log in to join the discussion.
Loading…