Question 127 marks
Question
A program reads data from a text file and stores it in a stack. The stack Stack is stored as a 1D array of up to 20 elements. The pointer TopOfStack stores the index of the last element stored in the stack. (a) Stack is a global array of strings with all elements initialised to "-1" TopOfStack is a global variable initialised to –1 Write program code to declare and initialise Stack and TopOfStack Save your program as Question1_J25. Copy and paste the program code into part 1(a) in the evidence document. [2] (b) The function Push() takes a string parameter and attempts to store it on the stack. The function returns –1 if the stack is full. The function returns 1 if the parameter is successfully pushed onto the stack. Write program code for Push() Save your program. Copy and paste the program code into part 1(b) in the evidence document. [4] (c) The function Pop() returns the next item from the stack. The function returns "–1" if the stack is empty. Write program code for Pop() Save your program. Copy and paste the program code into part 1(c) in the evidence document. [4] (d) The text file StackData.txt stores numbers and mathematical operators. Each number and operator are on a new line in the text file. The mathematical operators used in this program are: mathematical meaning operator + addition – subtraction / division * multiplication ^ power of The procedure ReadData(): • takes a string filename as a parameter • opens the file and reads in each line of data • uses the Push() function to insert each line of data onto the stack • outputs "Stack full" if any data cannot be stored on the stack because the stack is full • uses exception handling when opening and reading from the text file. The procedure needs to work for a file that contains an unknown number of lines. Write program code for ReadData() Save your program. Copy and paste the program code into part 1(d) in the evidence document. [6] (e) The values stored in the stack are used to perform mathematical operations. A total is initialised to the first value in the stack. The first value in the stack will always be a number. The next value will be a mathematical operator and the next value will be the number to apply to the calculation. This is repeated until there are no values left in the stack. There will always be a number following a mathematical operator. For example, the contents of a stack are: 10 TopOfStack + 3 – 2 The total is initialised to the first value in the stack: 10 total = 10 The next two values are: + 3 total = 10 + 3 = 13 The next two values are: – 2 total = 13 – 2 = 11 The final total is 11 and this is returned. Write program code for the function Calculate() to: • take each value from the stack • calculate and return the final total. Save your program. Copy and paste the program code into part 1(e) in the evidence document. [7] (f) (i) Write program code to extend the main program to: • take a filename as input from the user • call ReadData() with the input filename • call Calculate() • output the final total. Save your program. Copy and paste the program code into part 1(f)(i) in the evidence document. [2] (ii) Test your program twice with the file names: StackData.txt SecondStack.txt Take a screenshot of the output(s). Save your program. Copy and paste the screenshot into part 1(f)(ii) in the evidence document. [2]
Mark scheme
1(a) 1 mark each 2 • (Global) Stack as 1D array (of strings) with 20 elements initialised to string "–1" • (Global) TopOfStack initialised to –1 Example program code: Java public static String[] Stack = new String[20]; public static Integer TopOfStack; public static void main(String args[]){ for(Integer X = 0; X < 20; X++){ Stack[X] = "-1"; } TopOfStack = -1; } VB.NET Dim Stack(19) As String Dim TopOfStack As Integer For x = 0 To 19 Stack(x) = "-1" Next TopOfStack = -1 Python Stack = [] TopOfStack = -1 #main for x in range(20): Stack.append("-1") 1(b) 1 mark each 4 • Push function header (and end where appropriate) taking one (string) parameter • Checking if stack is full and returning integer –1 • (Otherwise) Incrementing TopOfStack • Storing parameter in the incremented the stack at TopOfStack and returning integer 1 Example program code: Java public static Integer Push(String Data){ if (TopOfStack == 19){ return -1; }else{ TopOfStack++; Stack[TopOfStack] = Data; return 1; } } VB.NET Function Push(ByVal Data) If TopOfStack = 19 Then Return -1 Else TopOfStack = TopOfStack + 1 Stack(TopOfStack) = Data Return 1 End If End Function Python def Push(Data): global Stack global TopOfStack if TopOfStack == 19: return -1 else: TopOfStack += 1 Stack[TopOfStack] = Data return 1 1(c) 1 mark each 4 • Function header (and end where appropriate) and returning a value in all cases. • Checking if stack is empty and returning string "–1" • (Otherwise) Decrementing TopOfStack • Returning element in stack at TopOfStack before TopOfStack is decremented Example program code: Java public static String Pop(){ if (TopOfStack == -1){ return "-1"; }else{ String ReturnValue = Stack[TopOfStack]; TopOfStack--; return ReturnValue; } } VB.NET Function Pop() If TopOfStack = -1 Then Pop = "-1" Else Pop = Stack(TopOfStack) TopOfStack = TopOfStack - 1 End If End Function Python def Pop(): global Stack global TopOfStack if TopOfStack == -1: return "-1" else: ReturnValue = Stack[TopOfStack] TopOfStack -= 1 return ReturnValue 1(d) 1 mark each 6 • Procedure header (and end where appropriate) taking one (string) parameter • Opening the file with the filename parameter and closing the file in an appropriate place • Looping through to end of file and reading in each line ... • … calling Push() once with each read in value … • … if any return value from Push() is integer –1 outputting "Stack full" • Exception handling for opening and reading from file with appropriate catch and output Example program code: Java public static void ReadData(String FileName){ Integer ReturnValue; try{ FileReader f = new FileReader(FileName); try{ BufferedReader Reader = new BufferedReader(f); String Line= Reader.readLine(); Line = Line.replace("\n",""); while (Line != null){ Line = Line.replace("\n",""); ReturnValue = Push(Line); if (ReturnValue == -1){ System.out.println("Stack full"); } Line = Reader.readLine(); } Reader.close(); }catch(IOException ex){} }catch(FileNotFoundException e){ System.out.println("File not found"); } } VB.NET Sub ReadData(ByVal FileName As String) Dim ReturnValue As String Try Dim FileReader As New System.IO.StreamReader(FileName) While Not FileReader.EndOfStream ReturnValue = Push(FileReader.ReadLine()) If ReturnValue = "-1" Then Console.WriteLine("Stack full") End If End While FileReader.Close() Catch ex As Exception Console.WriteLine("Cannot open file") End Try End Sub Python def ReadData(FileName): global Stack global TopOfStack try: File = open(FileName) for Line in File: ReturnValue = Push(Line.strip()) if ReturnValue == -1: print("Stack full") File.close() except: print("Cannot open file") 1(e) 1 mark for: 7 • Calculate() function header (and end where appropriate) • Looping until the stack is empty • Calling Pop() repeatedly within loop and storing/using return value • … working out if return value from Pop() call is an operator or a number / alternating between operator and number • Select to determine if the operator is +, -, /, * or ^ and attempt the matching calculation • … performing correct calculation using operator, number • … updating total from previous loops and returning this final value Example program code: Java public static Double Calculate(){ Double Total = Double.parseDouble(Pop()); String ReturnValue = ""; String LastOperator = ""; Boolean OperatorFlag = true; Integer TheData = 0; while(ReturnValue != "-1"){ ReturnValue = Pop(); if(OperatorFlag == false){ TheData = Integer.parseInt(ReturnValue); if(LastOperator.compareTo("+")==0){ Total = Total + TheData; }else if(LastOperator.compareTo("-")==0){ Total = Total - TheData; }else if(LastOperator.compareTo("*")==0){ Total = Total * TheData; }else if(LastOperator.compareTo("/")==0){ Total = Total / TheData; }else if(LastOperator.compareTo("^")==0){ Total = Math.pow(Total, TheData); } OperatorFlag = true; }else{ LastOperator = ReturnValue; OperatorFlag = false; } } return Total; } VB.NET Function Calculate() Dim Total As Integer = Pop() Dim ReturnValue As String = "" Dim LastOperator As String = "" Dim OperatorFlag As Boolean = True Dim TheData As Integer = 0 While (ReturnValue <> "-1") ReturnValue = Pop() Select Case OperatorFlag Case False TheData = ReturnValue Select Case LastOperator Case "+" Total = Total + TheData Case "-" Total = Total - TheData Case "*" Total = Total * TheData Case "/" Total = Total / TheData Case "^" Total = Total ^ TheData End Select OperatorFlag = True Case Else LastOperator = ReturnValue OperatorFlag = False End Select End While Return Total End Function Python def Calculate(): global Stack global TopOfStack Total = Pop() Total = int(Total) Return = 0 LastOperator = "" Operator = True while(Return != "-1"): Return = Pop() if Operator == False: Data = int(Return) if LastOperator == "+": Total = Total + Data elif LastOperator == "-": Total = Total - Data elif LastOperator == "*": Total = Total * Data elif LastOperator == "/": Total = Total / Data elif LastOperator == "^": Total = Total ** Data Operator = True else: LastOperator = Return Operator = False return Total 1(f)(i) 1 mark each 2 • Taking a filename as input and calling ReadData() with input • Calling Calculate() and outputting the return value Example program code: Java TopOfStack = -1; System.out.println("Enter the filename"); Scanner scanner = new Scanner(System.in); String FileName = scanner.nextLine(); ReadData(FileName); Double ReturnValue = Calculate(); System.out.println(ReturnValue); VB.NET Console.WriteLine("Enter the filename") Dim FileName As String = Console.ReadLine() ReadData(FileName) Dim ReturnValue As Single ReturnValue = Calculate() Console.WriteLine(ReturnValue) Python FileName = input("Enter the filename: ") ReadData(FileName) ReturnValue = Calculate() print(ReturnValue) 1(f)(ii) 1 mark for screenshot showing input of StackData.txt and output of 131 2 1 mark for screenshot showing input of SecondStack.txt and output of 320 e.g.