Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikibooksThe Free Textbook Project
Search

File Handling

From Wikibooks, open books for an open world
<A Level Computer Science Programming Guide
This is theprint version ofA Level Computer Science Programming Guide
You won't see this message or any elements not part of the book's content when you print orpreview this page.


A Level Computer Science Programming Guide

The current, editable version of this book is available in Wikibooks, the open-content textbooks collection, at
https://en.wikibooks.org/wiki/A_Level_Computer_Science_Programming_Guide

Permission is granted to copy, distribute, and/or modify this document under the terms of theCreative Commons Attribution-ShareAlike 3.0 License.

Introduction

This Wikibook is not designed to teach you how to program, but rather to help you to remember and easily translate your code to the different languages.

All Pseudocode in this guide is based on various Cambridge Mark Schemes and Help Guides, so it is as accurate as possible.

When complete, the High-Level languages covered in this guide will be those that are set in the Cambridge syllabus; VB.Net, Python and Pascal/Delphi.


Variables, Constants and Data Types

Data types and their usage

[edit |edit source]
Pseudocode
Data TypeDescriptionUsageExample
INTEGER
A whole numberUses the normal denary system
123, -123, 0
REAL
Any number that has fractional parts/decimalsWritten with at least one digit either side of a decimal point
12.4, 3.0, -17.34
CHAR
A single characterA single character enclosed between single quotation marks
'a', '@', '5'
STRING
A series of zero or more charactersNo, or a series of characters enclosed between double quotation marks
"banana", "Q173hf", "John Doe"
BOOLEAN
A logical ExpressionTrue or False
TRUE, FALSE
DATE
Any valid dateUse the format:
dd/mm/yyyy

If a different format must be used, use a comment to explain your decision.

21/10/2015, 03/07/1985, 12/11/1955

Variable Declarations

[edit |edit source]

Python has no variable declarations.

LanguageGeneral UsageExample Usage
Pseudocode
DECLARE <Identifier> : <Data Type>
DECLARE Weight : INTEGERDECLARE Mass : REALDECLARE Material : STRING
VB.NET
Dim<Identifier>As<DataType>
DimWeightAsIntegerDimMassAsDoubleDimMaterialAsString

Constants

[edit |edit source]

Python has no constants.

LanguageGeneral UsageExample Usage
Pseudocode
CONSTANT <Identifier> = <Value>
CONSTANT Pi = 3.14CONSTANT e = "2.718"CONSTANT Multiplier = 10
VB.NET
Const<Identifier>As<DataType>=<Value>
ConstPiAsDouble=3.14ConsteAsString="2.17"ConstMultiplierasInteger=10

Assignments

[edit |edit source]
LanguageGeneral UsageExample Usage
Pseudocode
<Identifier> ← <Value>
Name ← "Stephen"Age ← 47Weight ← 19.32
VB.NET
<Identifier>=<Value>
Name="Stephen"Age=47Weight=19.32
Python
<Identifier>=<Value>
Name="Stephen"Age=47Weight=19.32


Arrays

Declaring Arrays

[edit |edit source]

In Pseudocode, Arrays all have declarable Upper and Lower bounds.

In VB.NET, Arrays all have declarable Upper Bounds, but Lower Bounds are always 0.

One Dimensional Arrays

[edit |edit source]
LanguageGeneral UsageExample Usage
Pseudocode
DECLARE <Identifier> : ARRAY[<Lower Bound>:<Upper Bound>] OF <Data Type>
DECLARE NameList : ARRAY[1:5] OF STRINGDECLARE YearlyRainfall : ARRAY[1900:2100] OF REALDECLARE AgeList : ARRAY[0:40] OF INTEGER
VB.NET
Dim<Identifier>(<UpperBound>)As<DataType>
DimNameList(4)AsStringDimYearlyRainfall(200)AsDoubleDimAgeList(40)AsInteger
Python
<Identifier>=[]
NameList=[]YearlyRainfall=[]AgeList=[]

Two Dimensional Arrays

[edit |edit source]
LanguageGeneral UsageExample Usage
Pseudocode
DECLARE <Identifier> : ARRAY[<Lower Bound>:<Upper Bound>, <Lower Bound>:<Upper Bound>] OF <Data Type>
DECLARE GameArea : ARRAY[1:32, 0:16] OF STRINGDECLARE SudokuGrid : ARRAY[1:9, 1:9] OF INTEGERDECLARE PopulationDensity : ARRAY[1:50, 20:50] OF REAL
VB.NET
Dim<Identifier>(<UpperBound>,<UpperBound>)As<DataType>
DimGameArea(31,16)AsStringDimSudokuGrid(8)AsIntegerDimPopulationDensity(49,30)AsDouble
Python
<Identifier1>=[]<Identifier2>=[]<Identifier1>.append(<Identifier2>)
Game=[]GameArea=[]GameArea.append(Game)SudokuX=[]SudokuGrid=[]SudokuGrid.append(SudokuX)Longitude=[]PopulationDensity=[]PopulationDensity.append(Longitude)

Using Arrays

[edit |edit source]

One Dimensional Arrays

[edit |edit source]
LanguageGeneral UsageExample Usage
Pseudocode
<Identifier>[<Index>] ← <Value>
NameList[1] ← "Stephen"YearlyRainfall[1985] ← 13.73AgeList[39] ← 17
VB.NET
<Identifier>(<Index>)=<Value>
NameList(0)="Stephen"YearlyRainfall(85)=13.73AgeList(38)=17
Python
<Identifier>.append(<Value>)
NameList.append("Stephen")YearlyRainfall.append(13.73)AgeList.append(17)

Two Dimensional Arrays

[edit |edit source]
LanguageGeneral UsageExample Usage
Pseudocode
<Identifier>[<Index>,<Index>] ← <Value>
GameArea[16, 5] ← "Fire"SudokuGrid[9, 3] ← 7PopulationDensity[14, 32] ← 242.023
VB.NET
<Identifier>(<Index>,<Index>)=<Value>
GameArea(15,5)="Fire"SudokuGrid(8,2)=7PopulationDensity(13,12)=242.023
Python
<Identifier1>=[]<Identifier2>=[]<Identifier1>.append(<Identifier2>)
Game.append("Fire")GameArea.append(Game)SudokoX.append(7)SudokuGrid.append(SudokuX)Longitude.append(242.023)PopulationDensity.append(Longitude)


User-Defined Data Types

Warning: Display title "User-Defined Data Types" overrides earlier display title "Variables, Constants and Data Types".

Enumerated Data Types

[edit |edit source]

Declaring Enumerated Data Types

[edit |edit source]
LanguageGeneral UsageExample Usage
Pseudocode
TYPE <Identifier> = (<Value 1>, <Value 2>, <Value 3>, ...)
TYPE Season = (Summer, Autumn, Winter, Spring)TYPE Direction = (North, North_East, East, South_East, South, South_West, West, North_West)TYPE SpiceIntensity = (No_Preference ,None, Mild, Medium, Hot, Extreme)
VB.NET
Enum<Identifier><Value1>=<Reference><Value2>=<Reference><Value3>=<Reference>....EndEnum
EnumSeasonSummer=1Autumn=2Winter=3Spring=4EndEnumEnumSpiceIntensityNone=0Mild=1Medium=2Hot=3Extreme=4EndEnum

Using Enumerated Data Types

[edit |edit source]
LanguageGeneral UsageExample Usage
Pseudocode
DECLARE <Identifier> : <Data Type><Identifier> ← <Value>
DECLARE Seasons : SeasonSeasons ← AutumnDECLARE CompassPointer : DirectionCompassPointer ← NorthDECLARE SpicePreference : SpiceIntensitySpicePreference ← Extreme
VB.NET
Dim<Identifier>As<DataType><Integer Variable>=<Identifier>.<Value>
DimSeasonsAsSeasonSeasonCounter=Seasons.AutumnDimCompassPointerAsDirectionCurrentDirection=CompassPointer.NorthDimSpicePreferenceAsSpiceIntensitySpiceCounter=SpicePreference.Extreme

Pointer Data Types

[edit |edit source]

There is no VB.Net equivalent for a Pointer Data Type.

LanguageGeneral UsageExample Usage
Pseudocode
TYPE <Pointer> = ^<Type Name>
Type AddPointer = ^INTEGERType NextLocation = ^STRINGType Pass = ^REAL

Record Data Types

[edit |edit source]
LanguageGeneral UsageExample Usage
Pseudocode
TYPE <Identifier> DECLARE <Identifier> : <Data Type> DECLARE <Identifier> : <Data Type> ...END TYPE
TYPE Person DECLARE Name : STRING DECLARE Birthday : DATE DECLARE Weight : REAL DECLARE Address : STRING DECLARE SpicePreference : SpiceIntensityEND TYPE
VB.NET
Structure<Identifier>Dim<Identifier>As<Datatype>Dim<Identifier>As<Datatype>...EndStructure
StructurePersonDimNameAsStringDimBirthdayAsDateDimWeightAsDoubleDimAddressAsStringDimSpicePreferenceAsSpiceIntensityEndStructure


Common Operations

Warning: Display title "Common Operations" overrides earlier display title "User-Defined Data Types".

Input And Output

[edit |edit source]
LanguageGeneral UsageExample Usage
Pseudocode
INPUT <Identifier>
Input AnswerInput AgeInput DistanceTravelled
VB.NET
<Identifier>=Console.Readline()Dim<Identifier>As<DataType>=Console.ReadLine()
Answer=Console.ReadLine()DimAgeAsInteger=Console.ReadLine()DistanceTravelled=Console.ReadLine()

Arithmetic, Relational and Logic Operators

[edit |edit source]
LanguageArithmetic OperatorsInteger DivisionRelational OperatorsLogic Operators
AdditionSubtractionMultiplicationDivisionModulusDivisionGreater ThanLess ThanGreater Than or Equal toLess Than or Equal toEqual ToNot Equal ToANDORNOT
Pseudocode+-*/MODDIV><>=<==<>ANDORNOT
VB.NET+-*/MOD\><>=<==<>ANDORNOT

String Operators

[edit |edit source]
LanguageGeneral UsageExample Usage
Pseudocode
VB.NET

Random Number Generation

[edit |edit source]
LanguageGeneral UsageExample Usage
Pseudocode
RANDOMBETWEEN(<Minimum>, <Maximum>)
Generates a randomINTEGER between the Minimum and Maximum.
RND()
Generates a randomREAL number between0 and1.
DECLARE Random : INTEGERRandom = RANDOMBETWEEN(10, 17)DECLARE Random : REALRandom = RND()
VB.NET
<Variable>=<Minimum>+Rnd()*(<Maximum>-<Minimum>)
Generates a random INTEGER between the Minimum and Maximum.
Rnd()
Generates a randomREAL number between0 and1.
DimRandomAsIntegerRandom=RANDOMBETWEEN(10,17)Random=10+Rnd()*(17-10)DimRandomAsDoubleRandom=Rnd()


Selection

Warning: Display title "Selection" overrides earlier display title "Common Operations".

IF Statements

[edit |edit source]
LanguageGeneral UsageExample Usage
Pseudocode
/ If...Then StatementIF <Condition>    THEN        <Statements>ENDIF/ If...Then...Else StatementIF <Condition>    THEN        <Statements>    ELSE        <Statements>ENDIF/ ElseIf StatementIF <Condition>    THEN        <Statements>ELSEIF <Condition>    THEN        <Statements>    ELSE        <Statements>ENDIF
/ If...Then StatementIF Age < 16    THEN        CanDrive ← FALSEENDIF/ If...Then...Else StatementIF IsGreen    THEN        OUTPUT "Green"    ELSE        OUTPUT "Blue"ENDIF/ ElseIf StatementIF Score > 1000    THEN        Multiplier ← 10ELSEIF Score < 500    THEN        Multiplier ← 0    ELSE        Multiplier ← 5ENDIF
VB.NET
'If...Then StatementIf<Condition>Then<Statements>EndIf'If...Then...Else StatementIf<Condition>Then<Statements>Else<Statements>EndIf'Else If StatementIf<Condition>Then<Statements>ElseIf<Condition>Then<Statements>Else<Statements>EndIF
'If...Then StatementIfAge<16ThenCanDrive=FalseEndIf'If...Then...Else StatementIfIsGreenThenConsole.WriteLine("Green")ElseConsole.WriteLine("Blue")EndIf'Else If StatementIfScore>1000ThenMultiplier=10ElseIfScore<500ThenMultiplier=0ElseMultiplier=5EndIf

Nested IF Statements

[edit |edit source]
LanguageGeneral UsageExample Usage
Pseudocode
IF <Condition>    THEN        IF <Condition>            THEN                <Statements>        ENDIFENDIF
IF Found = False    THEN        IF Searching = false            THEN                CALL Search()        ENDIFENDIFIF Age >= 16    THEN        IF PassedLicenceTest = True            THEN                CALL GenerateLicence()                        ELSEIF TakenTest = False            THEN                OUTPUT "You need to take the test to get your licence"            ELSE                OUTPUT "You Failed Your Test"                OUTPUT "You need to pass the test to get your licence"        ENDIF    ELSE        OUTPUT "Ineligible for Licence"ENDIF
VB.NET
If<Condition>ThenIf<Condition>Then<Statements>EndIfEndIf
IfFound=FalseThenIfSearching=falseThenSearch()EndIfEndIfIfAge>=16ThenIfPassedLicenceTest=TrueThenGenerateLicence()ElseIfTakenTest=FalseThenConsole.WriteLine("You need to take the test to get your licence")ElseConsole.WriteLine("You Failed Your Test")Console.WriteLine("You need to pass the test to get your licence")EndIfElseConsole.WriteLine("Ineligible for Licence")EndIf

CASE Statements

[edit |edit source]
LanguageGeneral UsageExample Usage
Pseudocode
CASE OF <identifier>    <value 1> : <statement>    <value 2> : <statement>    ...ENDCASECASE OF <identifier>    <value 1> : <statement>    <value 2> : <statement>    ...    OTHERWISE <statement>ENDCASE
/ If...Then StatementIF Age < 16    THEN        CanDrive ← FALSEENDIF/ If...Then...Else StatementIF IsGreen    THEN        OUTPUT "Green"    ELSE        OUTPUT "Blue"ENDIF/ ElseIf StatementIF Score > 1000    THEN        Multiplier ← 10ELSEIF Score < 500    THEN        Multiplier ← 0    ELSE        Multiplier ← 5ENDIF
VB.NET
'If...Then StatementIf<Condition>Then<Statements>EndIf'If...Then...Else StatementIf<Condition>Then<Statements>Else<Statements>EndIf'Else If StatementIf<Condition>Then<Statements>ElseIf<Condition>Then<Statements>Else<Statements>EndIF
'If...Then StatementIfAge<16ThenCanDrive=FalseEndIf'If...Then...Else StatementIfIsGreenThenConsole.WriteLine("Green")ElseConsole.WriteLine("Blue")EndIf'Else If StatementIfScore>1000ThenMultiplier=10ElseIfScore<500ThenMultiplier=0ElseMultiplier=5EndIf


File Handling

Warning: Display title "File Handling" overrides earlier display title "Selection".

Note for VB.NET users:

[edit |edit source]

While the methods used here are still valid, they are generally not used. They have been included in this guide as they are more similar to the Pseudocode file management, hopefully making them easier to understand. Even though it is not practice to use them, they should still be acceptable in an exam.

Handling Text Files

[edit |edit source]

Opening Text Files

[edit |edit source]
LanguageGeneral UsageExample Usage
Pseudocode
OPENFILE <File Identifier> FOR <File Mode>
OPENFILE Beans.txt FOR APPENDOPENFILE Styles.css FOR READOPENFILE Names.tmp FOR WRITE
VB.NET
FileOpen(<FileNumber>],<FileIdentifier>,OpenMode.<FileMode>)
FileOpen(17,Beans.txt,OpenMode.Append)FileOpen(FileNumber,Styles.css,OpenMode.Input)FileOpen(NamesFile,Names.tmp,OpenMode.Output)

InVB.NET you can use theFreeFile() function to automatically obtain an unused file number, avoiding any problems that could occur if accidentally using the same number for two files.

DimFileNumberAsInteger=FreeFile()

It is good practice toalways keep track of your file numbers, as it will help reduce bugs (aka forgetting or using the wrong file number), remove anyMagic Numbers and make the code easier to read and understand.

File Mode Usage
File Mode IdentifiersDescription
PseudocodeVB.NET
APPEND
OpenMode.Append
Used whenWriting data to the file.

If the file already exists, the new data will beadded to the file after any existing data.

READ
OpenMode.Input
Used whenReading data from the file.
Write
OpenMode.Output
Used whenWriting data to the file.

If the file already exists, the file will bedeleted and anew file will be created with the new data.

Reading From Text Files

[edit |edit source]

Once a file is opened in 'Read' mode, you can use the following commands to read the data from the files.

LanguageGeneral UsageExample Usage
Pseudocode
READFILE <File Identifier>, <Identifier>
/Datatypes declared as stringsREADFILE Styles.css, NextLineREADFILE TransactionHistory.txt, TransactionREADFILE Address.db, CurrentAddressWRITEFILE <File identifier>, <Variable>
VB.NET
<Identifier>=LineInput(<FileIdentifier>)
TheFile Identifer is the file number used identify the file when it was opened.
NextLine = LineInput(StylesFileNumber)Transaction = LineInput(TransactionHistoryFileNumber)CurrentAddress = LineInput(AddressFileNumber)

The Variable should be of data typeSTRING. This command reads the text file line by line.

TheEOF() function can be used inPseudocode andVB.NET to determine whether the file pointer is at the end of the file. It returns aBoolean Value, and can be useful when implementing loops.

EOF(<File Identifier>)
PseudocodeVB.NET
EOF(file.txt)
EOF(FileNumber)

Writing To Text Files

[edit |edit source]

Once a file is opened in 'Write' or 'Append' mode, you can use the following commands to write the data to the files.

LanguageGeneral UsageExample Usage
Pseudocode
READFILE <File Identifier>, <Identifier>
WRITEFILE Beans.txt, BeanDataWRITEFILE Names.tmp, CurrentUserWRITEFILE Recipes.db, NewRecipe
VB.NET
PrintLine(<FileIdentifier>,<Identifier>)
TheFile Identifer is the file number used identify the file when it was opened.
PrintLine("Beans.txt", BeanData)PrintLine("Name.tmp", CurrentUser)PrintLine("Recipes.db" NewRecipe)

The Variable should be of data typeSTRING.

Closing Text Files

[edit |edit source]
LanguageGeneral UsageExample Usage
Pseudocode
CLOSEFILE <File identifier>
CLOSEFILE Beans.txtCLOSEFILE Styles.cssCLOSEFILE Names.tmp
VB.NET
FileClose(<FileIdentifier>)
TheFile Identifer is the file number used identify the file when it was opened.
FileClose(17)FileClose(FileNumber)FileClose(NamesFile)

You shouldalways remember to close your files. Failure to do so can result in major problems later on when any program tries to open the file, or the program tries to open or edit a different file with the same identifier.


Algorithms

Sorting

  • Bubble Sort
  • Insertion Sort

Searching

  • Binary Sort

Listing

  • Stacks
  • Queues
  • Linked Lists
  • Binary Trees
  • Hash Tables


Retrieved from "https://en.wikibooks.org/w/index.php?title=A_Level_Computer_Science_Programming_Guide/Printable_version&oldid=3991372"
Categories:

[8]ページ先頭

©2009-2025 Movatter.jp