0% found this document useful (0 votes)
5 views11 pages

Data Types and Programming Techniques

Uploaded by

ashimakhosla11
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
5 views11 pages

Data Types and Programming Techniques

Uploaded by

ashimakhosla11
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 11

Data types and

programming techniques
Data types
Each variable must have a data type. The data type determines what
type of value the variable will hold.
Data typePurpose Example
Integer Whole numbers 27
Float Decimal numbers 27.5
Character A single alphanumeric character A
String One or more alphanumeric charactersABC
Boolean TRUE/FALSE TRUE
Key fact
The string data type holds characters that can be letters and/or numbers.
Different data types have limitations:
 integers and floats cannot be concatenated, ie joined together
 numbers held in strings cannot be subject to mathematical
operations
Casting
Sometimes a programmer needs to change the data type of a variable.
For example, an integer may need to be converted to a string in order to
be displayed as part of a message. This process is known as casting.
The following examples convert a string to an integer and an integer to a
string:
str(68) returns “68”
int(“54”) returns 54

String manipulation
A string is a variable that holds a sequence of one or more alphanumeric
characters. It is usually possible to manipulate a string to provide
information or to alter the contents of a string.
The following examples use strings:
wordOne = "Computer"
wordTwo = "Science"
Length
The length of a string can usually be determined using
the len statement. This gives the length as an integer.
len(wordOne) - would give the answer eight, as there are eight
characters in the word "Computer"
Character position
It is possible to determine which character features at a position within a
string:
wordOne[2] - would give the answer "m", as "m" is the third character in
the word “Computer” (remember computers start counting at zero)
wordOne[0,3] - would give "Com", the first three characters in the string
wordOne[3,3] - would give "put", the three characters starting from
position three
Upper and lowercase
It is possible to change all letters in a string to either lowercase or
uppercase. This can be very useful, for example when checking possible
inputs:
topic = "Computer Science"
topic = topic.lower - would give a value for the topic of "computer
science"
topic = topic.upper - would give a value for the topic of "COMPUTER
SCIENCE"

Concatenation
To concatenate strings means to join them to form another string. For
example:
sentence = wordOne + " " + wordTwo - would give "Computer Science"
Alternatively, a string can be lengthened by adding more characters. For
example:
wordOne = wordOne + " Science23" - would result in the value of
wordOne becoming "Computer Science23"
Basic file handling operations
Programs process and use data. When the program finishes, or is
closed, any data it held is lost. To prevent loss, data can be stored in
a file so that it can be accessed again at a later date.
Files have two modes of operation:
 read from - the file is opened so that data can be read from it
 write to - the file is opened so that data can be written to it
Each item of data written to or from a file is called a record.
Key fact
Files have two modes of operation - read from and write to.
Opening and closing files
A file must be open before a record can be read from or written to it. To
open a file, it must be referred to by its identifier, for example:
file = openRead("scores.txt")
This would open the file scores.txt and allow its contents to be read.
file = openWrite("scores.txt")
This would open the file scores.txt and allow it to have data written to it.
file.close()

Reading from a file


Once a file has been opened, the records are read from it one line at a
time. The data held in this record can be read into a variable, or, more
commonly, an array, for example:
file = openRead("scores.txt")
score = myFile.readLine()
file.close()
An array example is shown below.
file = openWrite("scores.txt")
for x = 0 to 9
scores[x]=myFile.readLine()
next x
file.close()
End of file
When reading a file that has more than one record, the computer needs
to know what to do when there are no more records to read.
The endOfFile() statement checks to see if the last record has already
been read, for example:
file = openRead("scores.txt")
while NOT file.endOfFile()
scores[x]=myFile.readLine()
x=x+1
endwhile
file.close()
The above code would read each record and place it into an
array scores. The operation ceases when there are no more files to
read.
Key fact
Arrays are often used to hold data read from files.

Writing to file
Data is written to a file one line at a time, using the writeLine statement,
for example:
file = openWrite("scores.txt")
for x = 0 to 9
file.writeLine(scores[x])
next x
file.close()
The above code would write the contents of an array scores to the
file scores.txt.
The use of records to store data and SQL
Databases, records and attributes
Data is often stored in a database. A database is a persistent store of
related data. Data in a database is stored as records, which in turn is
stored in files.
An attribute is one item of data. Records usually consist of one or more
attributes. For example, a record holding data about a person might
have these attributes:
 title
 forename
 surname
 email address
Structured query language (SQL)
Databases use their own type of programming language. This language
is known as structured query language, or SQL.
Key fact
SQL is a programming language used for interrogating a database.
Consider this simple personnel table with four records:
Person IDTitleForenameSurnameEmail address
1001 Mr Alan Turing aturing@bitesize.com
1002 Mrs Ada Lovelace alovelace@gcsecompsci.com
Person IDTitleForenameSurnameEmail address

1003 MissGrace Hopper ghopper@bitesizemail.co.uk


1004 Mr George Boole gboole@bbcbitesize.com
Retrieving data
Data can be retrieved using the commands SELECT,
FROM and WHERE, for example:
SELECT * FROM "personnel" WHERE "Title" = "Mr"
Note - * stands for wildcard, which means all records. This would retrieve
the following data:
1001 Mr Alan Turing aturing@bitesize.com
1004 Mr George Boole gboole@bbcbitesize.com
The LIKE command can be used to find matches for an incomplete
word, for example:
SELECT * FROM "personnel" WHERE "email address" LIKE "%com"
This would retrieve:
1001 Mr Alan Turing aturing@bitesize.com
1002 Mrs Ada Lovelace alovelace@gcsecompsci.com
1004 Mr George Boole gboole@bbcbitesize.com
Note - %com is also a wildcard which will return any value that contains
“com”.
Boolean operators AND and OR can also be used to retrieve data.
SELECT * FROM "personnel" WHERE "Surname" = "Turing" OR
"Hopper"
This would retrieve:
1001 Mr Alan Turing aturing@bitesize.com
1003 Miss Grace Hopper ghopper@bitesizemail.co.uk

Arrays
Sometimes a programmer needs to store a lot of related data. For
example, a game might record the scores achieved by players.
One way to do this would be to declare a variable for each score. So for
ten scores, the game program would require ten variables:
score1
score2
score3
And so on, up to score10
While certainly possible, this is not a practical method of recording this
data. Suppose the program needed to record 100 scores? 100 variables
would be required!
A better method is to use an array. An array is a data structure that holds
similar, related data. An array is like a collection of boxes, each of which
is called an element. Each element has a position in the array, and can
hold a value. The data in an array must all be of the same data type.
Key fact
An array is a data structure that holds similar, related data.
This way, all data is stored under one identifier. For example, the array
called “score” could contain the following ten scores for a player:

0 1 2 3 4 5 6 7 8 9

100 110 85 80 92 72 66 98 100 120

Declaring an array
Before an array can be used, it must be declared. To declare an array it
must be given at least two properties:
 an identifier
 a size (the number of elements it will hold)
For example:
array score[9] - would declare an array with ten elements (zero to nine)
Note - some programming languages also require the array's data type
to be declared.
Once declared, the name and structure of an array cannot be changed.
Assigning values to an array
Values are assigned to an element in an array by referring to the
element's position. For example:
score[0] = 100 - would assign the value 100 to the first element in the
array
Values in elements can be overwritten at any point, simply by assigning
another value to that element.
Retrieving values from an array
Values are retrieved from an element in the array by again referring to
the element's position. For example:
print(score[7]) - would display the eighth value held in the array. In the
above example, the value would be 98
Two-dimensional arrays
A two-dimensional array can hold more than one set of data. This type of
array is like a table, with data held in rows and columns.
The following array would hold ten scores for two players. The first
player (0) has data stored in the first row. The second player (1) has data
stored in the second row.
0 1 2 3 4 5 6 7 8 9
0 100 110 85 80 92 72 66 98 100 120
1 90 99 102 88 78 100 67 120 88 105
A two-dimensional array is declared using two values - the number of
rows and the number of columns. For example:
array score = [1,9] - would give an array with two rows and ten columns
Data is assigned or retrieved by referring to an element's row and
column number. For example:
score[0,1] = 110
print(score[1,4]) - would display the score 78
Using subprograms to produce structured code
Subprograms are small programs that are written within a larger, main
program. The purpose of a subprogram is to perform a specific task.
This task may need to be done more than once at various points in the
main program.
There are two types of subprogram:
 procedures
 functions
Benefits of using subprograms
 Subprograms are usually small in size, meaning they are much
easier to write, test and debug. They are also easy for someone
else to understand.
 Subprograms can be saved separately as modules and used again
in other programs. This saves time because the programmer can
use code that has already been written, tested and debugged.
 A subprogram may be used repeatedly at various points in the
main program. However, the code only has to be written once,
resulting in shorter programs.
Procedures
A procedure is a subprogram that performs a specific task. When the
task is complete, the subprogram ends and the main program continues
from where it left off. For example, a procedure may be written to reset
all the values of an array to zero, or to clear a screen.
A procedure is created using the following syntax:
procedure identifier (value to be passed)
procedure code
endprocedure
This procedure would clear the screen by printing x blank lines:
procedure clear_screen(x)
for i = 1 to x:
print(" ")
endprocedure
A procedure is run by calling it. To call it, a programmer uses the
procedure name and includes any values that the procedure needs, for
example:
clear_screen(5)
This would print five blank lines on the screen.
Functions
A function works in the same way as a procedure, except that it
manipulates data and returns a result back to the main program.
For example, a function might be written to turn Fahrenheit into Celsius:
function f_to_c(temperature_in_f)
temperature_in_c= (temperature_in_f –32) * 5/9
return temperature_in_c
endfunction
A function is run by calling it. To call it, a programmer uses the
function's identifier, the value to be passed into the function, and a
variable for the function to return a value into, for example:
celsius = f_to_c(32)
This would result in the value of Celsius being zero.
Key fact
Procedures perform a specific task. Functions manipulate data and
return a value to the main program.
Built-in functions
Many languages include built-in, ready-made functions:
 int - converts strings or floats into integers
 str - converts a number into a string
 asc - finds the ASCII number of a character
Additionally, some languages allow functions to be added in from
external files called libraries. Libraries contain pre-written, tested
functions that extend the functionality of a language.
Random number generation
Sometimes a programmer needs the program to generate a number or
letter within a specific range. This requires the program to create a
random number. Programming games that involve chance, such as dice,
require random numbers as do many types of program that need to be
unpredictable.

dice ← RANDOM_INT(1,6)
OUTPUT “you rolled a ” + INT_TO_STRING(dice) + “!”
Random numbers are not just used for rolling dice and games of chance.
When sending data across a network, a wireless router waits for a
random amount of time before transmitting the data to avoid collisions.
Random numbers are often used to generate secure passwords that are
difficult to crack.

You might also like