TextbookIBCurrent
TextbookIBCurrent
IBComputerScience - Textbook
2
IBComputerScience - Textbook
3
IBComputerScience - Textbook
4
IBComputerScience - Textbook
CONVENTIONS 168
PRACTICAL ONLY – FILE INPUT AND OUTPUT 169
SIMPLE FILE I/O 169
FILE I/O USING BYTES 170
FILE I/0 - RANDOM ACCESS FILES 172
FILE I/O – USING FILES WITH ADT’S 175
EXTENSION – GRAPHICAL USER INTERFACES 178
ADDITIONAL PROJECTS – HL 181
PROJECT ONE – PENGUINS WITH PROBLEMS 181
PROJECT TWO – BINARY CONVERTER 183
PROJECT THREE – DISTANCE CALCULATOR 183
PROJECT FOUR – PIG LATIN 183
PROJECT FIVE – VOWEL COUNTER 183
PROJECT SIX – PALINDROME CHECKER 184
PROJECT SEVEN – FORTUNE TELLER 184
PROJECT EIGHT – RANDOM GIFT SUGGESTOR 184
PROJECT NINE – RECIPE MANAGER 184
PROJECT TEN – VENDING MACHINE 184
PROJECT ELEVEN – JOSEPHUS PROBLEM 185
PROJECT TWELVE – FAMILY TREE CREATOR 185
PROJECT THIRTEEN – DOCTOR SCHEDULER 185
PROJECT FOURTEEN – THE PASSWORD SAFE 185
PROJECT FIFTEEN – QUIZ MAKER 186
PROJECT SIXTEEN – THE COLLECTOR 186
PROJECT SEVENTEEN – HANGMAN 186
PROJECT EIGHTEEN – PLAY YOUR CARDS RIGHT 186
PROJECT NINETEEN – MAGIC EIGHT BALL 187
PROJECT TWENTY – BATTLE SHIPS 187
PROJECT TWENTY ONE – GRAND NATIONAL 187
PROJECT TWENTY TWO – POKER 188
CHAPTER SEVEN / EIGHT - REVIEW QUESTIONS 189
5
IBComputerScience - Textbook
6
IBComputerScience - Textbook
The purpose of this unit is to investigate why systems are needed. We no longer live in a
world where many processes are carried out on paper but new systems are still being
created all the time. Why if most things are computerized anyway do we need new
systems? We will also look at how systems analysts get data from clients, how systems are
implemented and how we train staff to use these systems. This unit will also deal with the
legal and ethical issues surrounding computer systems.
When changing a system there are many factors that need to be managed both
technologically and with people. Firstly, technology systems have to be implemented to a
timetable. This means the designers, the coders, the testing and the implementation need
to be kept on schedule. The manager needs to ensure that each phase sticks to the schedule
as far as possible and if there are any unforeseen circumstances these need to be managed.
Employees during this time will naturally be nervous, people are always wary of change.
People maybe fearing the loss of their job or how lost they will feel when the new system is
in place. It is the job of the manager to reassure people that there will be adequate training
7
IBComputerScience - Textbook
for use with the new system and also that if there are redundancies as a result of the new
system they will be handled fairly.
Compatibility Issues
Compatibility in this context means the ability of one system to communicate with another
system and is especially important when thinking about systems that are global. To be able
to communicate with others is one of the fundamental requirements of global businesses.
Therefore you need to ensure that the relevant stakeholders can read documents and files
produced by the system you create. Whenever possible standard file formats should be
used and when coding a character set that is capable of representing many different
languages. Another compatibility issue to consider is the differences in international
standards for example 2.4.16 in Europe is the 2nd April 2016 however in American this would
be the 4th February 2016. If you are transferring between systems it is important to consider
the issues that can occur with this.
Software – as – a Service
When planning systems it is necessary to consider whether you will pay for the software and
use your own machines to run the system or whether you will use service software.
Software-as-a-Service is usually subscription based software and is hosted on the providers
servers not the companies. It can be described as “renting” software as you only have the
software while you pay or are subscribed to it. Some examples of software as a service are:
oneDrive, Microsoft Office online, the Adobe suite online, Google Drive, Box.com.
- No additional hardware costs, all the cost associated with running the program are
contained on the host server.
- No initial set up costs, only the subscription
- You pay for what you use, therefore if only certain people need certain applications
they only pay for them applications.
- Updates are automatic, the company hosting the software rolls out the updates, and
therefore the software is always up to date.
- There is cross device compatibility, often people bring in devices running different
O/S’s with SAAS companies don’t need to be as concerned about this
- Access can be from anywhere, for example a company using Dropbox can allow
employees access anywhere in the world.
- Some SAAS has interactive editing (e.g. Google Drive) this means that members of
the same team can work collaboratively on a project they don’t necessary need to
be together, which saves the company money.
Drawbacks of SAAS:
- The data stored by the program is often held on the host server, which does lead to
data security issues.
- Some business that require integration with customer systems may have trouble as
this may large volumes of sensitive data being stored externally.
- If the data is all stored in the cloud limited access or slow access to web services
becomes an issue.
8
IBComputerScience - Textbook
- The laws governing the data are in host’s country not necessarily the same country
as the company. This is especially a problem when using American companies from
Europe, as the laws in America are not a stringent as European laws when governing
what can be done with our data.
- If the host company goes out of business then the company may lose the data being
stored on the host servers.
- If the updates are out of control of the company then training issues may arise if
there is a big change without notice.
Installing Systems
After a system has been planned it needs to be installed, this is a delicate process, as it
requires the company to put the trust of all their data into the system for the first time.
There are several different options for transferring the data each comes with their own
associated benefits and risks.
Parallel Running
In this installation procedure the old system and the new system are running alongside each
other.
Advantages Disadvantages
Pilot Running
In this installation procedure a small group of users begin using the systems (a select group
of employees). This group then reports back to the development team highlighting any
issues or items, which need changing before the system is rolled out to the whole company.
Advantages Disadvantages
9
IBComputerScience - Textbook
Direct Changeover
In the direct changeover process the new system is put in place and the old system removed
immediately.
Advantages Disadvantages
Phased Conversion
The phased conversion strategy allows one section of the system to be changed over at a
time. For example one department might start using the new system and become
comfortable with it before moving onto the next department.
Advantages Disadvantages
Installation problems: as discussed in the tables above things can and do go wrong when
installing a new system. One example of this would be when they changed systems in
Terminal 5 at Heathrow Airport (see the case study box). Some of the things that could go
wrong include:
- Incompatible file formats: one example of this is Apple Pages and Microsoft Word, if
a company uses these file formats, they do not talk to each other which renders files
unreadable. To ensure this does not happen when changing a system standard file
formats should be used whenever possible.
- Incompatible data structures: Data is stored in data structures when in use by the
computer, if the system is trying to use a data structure it is not used to then it is
unlikely to be able to read and write from the structure.
10
IBComputerScience - Textbook
- Incomplete data transfer: Often when transferring a lot of data the data becomes
lost. Whether this is technical error or human error it is often not found for a long
time by which point the data is irretrievable.
- Different international conventions with formats, currencies and character sets:
05/06/2013 is either the 5th of June or 6th of May depending on where in the world
you are from. If you try to import dates from a system that does not use the same
system as you then it is likely that you will get errors in your data. The same as if the
currencies are different or you have not encoded text in the same way.
Heathrow Terminal Five was set to be the flagship terminal for Heathrow airport, British Airways
were going to solely fly from this terminal. It was state of the art with new baggage systems and
hailed as a triumph of airport design. However, on the day of opening 28th March 2008, it
became apparent very quickly the baggage was not working and at least 28000 bags were lost in
March and April. The cause of the failure? Not enough user testing, not enough time to check
the installation process had worked and too many passengers on the first day. This was one of
the most embarrassing events for BAA (airport owners) and British Airways. It was so flawed
and so embarrassing they had to run national adverts to ensure people knew that Heathrow was
safe to fly through once they had sorted out the problems.
Testing A System
As can be seen from the Heathrow case study it is essential to fully test a system. Although
it is impossible to test every eventuality it is possible to thoroughly test systems to try and
ensure system installation and transfers are as smooth as possible. If a system does not
work as expected it can lead to the system being unreliable, companies could lose clients
due to incorrect data, and the users of the system may lose trust in the system and become
dissatisfied. The main types of testing are as follows.
Alpha Testing / Debugging: Alpha testing is the first stage of testing it is the stage that
happens while programming. The programmers complete this stage of testing to check
there are no syntax or logic errors in the code and that it is functionally correctly. Some of
this testing can be automated.
Beta Testing: Beta testing is when the software is released to a select group of users, they
either use the program as intended or are given tasks to complete by the programming
team. It is their job to the report any errors to the developers. Many people do this for
games companies (see case study).
User Acceptance Testing: This is the final stage of testing. Once the company has the
software and it is in place they “sign off” on the project effectively saying that now it is in the
company and has been rolled out to all employees they are happy with it and have adopted
it as their system.
Sounds like a dream job – getting paid to play games that have not yet been released to the public.
However often developers want to find out if there are any hidden flaws in the game. Sometimes Beta
testers for games have to get to a certain point in a game and then jump off a building 100 times, just to
11
check the game environment functions properly. They also get paid a small amount for a lot of time and
effort but at least they get one of the first copies of the game.
IBComputerScience - Textbook
Data Migration
One of the reasons that testing is so important is because migrating data from one system to
another can lead to problems. Testing can help to foresee and eliminate problems before
they become a big issue.
Possible causes of data migration problems are detailed in the following table:
12
IBComputerScience - Textbook
space they have used to most memory. If you do not rather that
economical way to store the getting characters that make sense you
data. will get symbols.
User Development
The processes described above are discussing the logistics of creating or adapting a system.
In general how do the systems development team create and implement the system and the
issues that arise as a result of this? However, many systems are designed to be used by
people who are good at their job and not necessarily brilliant using computers. How are
they prepared for the change? How can the development team best support them?
The first way in which the team can help with the change in the system and get people to
use the system is through user training. User training as the name suggests is educating the
employees of a company about how to use the system. It is essential that the management
provides high quality, in depth and professional training otherwise the system
implementation will be delayed or could fail. There are several ways to deliver training
these are described below:
13
IBComputerScience - Textbook
User Documentation
User Documentation is also a very important aspect in helping people to adapt to the new
system. High quality and helpful user documentation should be provided in order to help
the staff with the new system. Nobody can remember everything they have been told, they
need references until it becomes routine. Having the right documentation available to the
people using the system can help the new system become second nature to people quickly,
poor documentation can hinder this process.
System Backup
Once you have a system in place and it is integral to the company, a large volume of
irreplaceable data will be produced and stored on a daily basis. It is important to the
company that this data is not lost as losing data or data falling into the wrong hands can
cause people to lose faith in the company.
There are many causes of data loss for each there are ways to prevent it happening. These
are detailed below:
14
IBComputerScience - Textbook
Natural Disasters: Natural disasters can happen, this includes flooding and fire. If the
building in which the data is held is affected by one of these disasters then the data can be
lost. One way to prevent this would be to have a full back up of the company’s data once
per week and then back up the changed files once per day. These files should be stored on
removable devices that can be stored in a location away from the original data. Another
way to prevent this happening would be to back up the data to cloud storage facilities.
Failover systems could also be put into place, these are systems that are put into place when
the primary systems fail. They are often used in critical systems.
Intruders: It is possible that if an intruder enters a building then they can damage servers
that store the data or they can attempt to steal the data. As well as having physical security
such as locks and alarms on the buildings, all employees should be encouraged to have
strong passwords so access to machines is not easily granted.
Employees of the Company (Malicious): Employees that are upset or angry at the company
often try to sabotage data before they leave. This can be prevented by escorting staff from
the premises if they have been dismissed. Data should also be stored by access rights, with
only the highest level of staff having full access to all areas of the system.
We have discussed in abstract the consequences of data loss but what happens to companies
when it does happen. In May 2014 ebay.com was hacked and hackers stole information and
encrypted passwords of 148 million users. What does this mean? Firstly people can have there
identity cloned, people can purchase items using their account and linked payment data. Given
that most people have one or two passwords, it would not take long for other accounts of the
user to be hacked. The consequences for eBay were the lack of consumer confidence in their
product and the cost of fixing the problem.
15
IBComputerScience - Textbook
Patch Tuesdays
Patch Tuesday is the term given to the Tuesdays when Microsoft update their products. On the second
(and sometimes fourth) Tuesday of the month, Microsoft sends updates to its operating systems. The
reason for this is to fix “glitches” that have been reported back to the development team or to fix
security flaws that have been found in the system. Therefore it is always a good idea to restart a
Microsoft device after these days.
Hardware – The parts of the computer you can see and touch for example: the monitor, the
hard drive, the RAM
Software – the programs on the machine for example the operating system, the web
browser, the word processing package
Peripheral - additional items that allow the computer to be functional (it used to be
everything connected using a wire) for example the keyboard, the mouse, the printer
Network – computers and servers that are connected together in order to share information
and resources.
Human Resources - The department in a company that is usually responsible for the hiring
of people, the training of people and the administration associated with employees. They
would be involved in helping people to do their job correctly.
There are many different roles a computer can perform in a networked world. These include
the roles outlined below. We will look at these in more detail within the networks unit.
Client: A computer connected to the server, that gets information from the server.
Server: A computer that stores information and resources. Such as files, programs etc.
16
IBComputerScience - Textbook
Email Server: An email server is responsible for receiving and distributing emails to people
on that email server.
DNS Server: A Domain Name Server decodes the web address given and helps us to connect
to the websites we require.
Router: A router gathers data packets and redirects them to the correct machine on the
network.
Firewall: A firewall helps to protect the network machine against malicious attacks.
Now that most machines are networked it means that many people can access all information both
within and out with the work environment. What are the social benefits and social drawbacks of this?
How have working patterns changed as a result? Do you think education and your responsibilities as a
student have changed as a result?
Things have changed as a result of networking people have different opinions about how and whether
this change is good or not. You should consider the questions above as an aid to form your own
conclusions
17
IBComputerScience - Textbook
Stakeholders are the people involved with the system. They are the people who will be
affected by the change in the system. One of the first jobs that needs to be completed when
starting the systems analysis of a system is to identify who the stakeholders are. An example
could be choosing a new reporting system for the school:
Reporting
System
However not every teacher, every parent and every member of administration could be
asked for their opinion selective people are chosen and their opinions are used. In an ideal
world we would be able to ask everyone but we can’t.
Not being able to consult everyone leads us to one of the key TOK questions in Computer Science.
“What ethical limitations, if any, should be placed on research conducted in Computer Science?”
Should we be able to ask everyone what we like? Or is it ok to have limitations placed on our research?
18
IBComputerScience - Textbook
Once we have identified the stakeholders we enter the systems design process.
Traditionally the systems design process went from one stage to the next meaning that no
feedback was involved. This led to uninformed and poor end products a the end user was
not involved. It is now accepted that we need to use iteration. The iterative cycle allows
the feedback of the end user to order to inform each stage of our process, by constantly
seeking feedback and using that feedback to revisit and reevaluate each stage we end up
with a product tailored towards the end user.
Analysis
Evaluate Design
Test Develop
The first stage of the systems design process is analysis during the analysis stage we need to
decide which people we are going to interview in order to get the information from them.
There are several ways to do this each with their own advantages and disadvantages. The
key skill that is required in order to gather the information is effective communication and
collaboration. Stakeholders, especially employees, often find it difficult to express their true
feelings in an environments when they think they are being judged or they think there will
be consequences, one of the key jobs of the systems analysts is to encourage to talk even if
they have these feelings. When analyzing a system a mix of the following methods will be
used.
The systems analyst meets with the stakeholders, individually or as part of a group.
Advantages:
- Can ask follow up questions.
- Can judge the feeling in the room.
- Can encourage responses.
19
IBComputerScience - Textbook
Disadvantages:
- People often give what they think is the right answer rather than their answer.
- People fear being judged.
- It is time consuming.
The systems analyst conducts surveys in which people write down their opinion. This can
include a mixture of open and closed questions.
Advantages:
- Less time consuming than interviews to conduct the research.
- More people can respond.
- Questions can be used to gain general understanding of the company.
Disadvantages:
- No follow up questions can be asked.
- Could be difficult to make conclusions from the information.
Once you have gathered the data from the stakeholders you then need to get information
about the system and how it could be improved. This could be done using the following
methods:
One thing that the system analyst should be aware of when gathering information in this
way about the system is that Intellectual property rights need to be observed.
Intellectual property rights include trademarks, copyright, patents and industrial design rights. They
cover the right of the person/company who made the content the rights to the use of the content and
the right to stop others using their content without their express permission. It means that if people use
your content without your permission then you have the legal right to seek compensation.
20
IBComputerScience - Textbook
Design Stage
The next stage is the design process during this process the analyst team will produce
several charts that are used to inform the development team how the system should
function.
The first of these will be the systems flow chart. The systems flow chart shows how
information flows through the system when a certain process occurs. The standard symbols
are shown below:
Source:
https://sdd-hsc-online.wikispaces.com/Modelling+Tools+-
As you can see from the symbols involved the systems flow charts shows where the data is
gathered, stored and processed when an action takes place.
21
IBComputerScience - Textbook
For Example:
A shop stores information on its database, each time an item is scanned the database is
queried for the price and this is added to the bill. If the person pays by card the bank is
contacted to approve the transaction. Once payment is received a receipt is printed and
handed to the customer. Show this in a system flow diagram.
Item
Prices
scanned
Database
Bill
Calculated
Card
Cash Appro
or val
Card
Approved
Receipt
22
IBComputerScience - Textbook
Another diagram that may be produced is a data flow diagram. It is similar to the system
flow diagram however rather than showing the physical items that need to be involved in
the decision making it shows the objects, methods and outputs. An example below is taken
from the teach-ict.com website:
This diagram show the objects involved in each transaction and then how they all fit
together.
The customer confirms the details of their order. Form this an instruction to order the parts
is generated and the parts are ordered from the supplier. An invoice is raised using the
accounts object and a copy of the invoice is printed. The build details are specified and built
by the factory object. The delivery date is confirmed by the factory object and the object
along with the invoice is sent to the customer.
23
IBComputerScience - Textbook
Structured Charts
Another chart that can be used to show the operation in an organization is the structured
chart. The structured chart allows us to take a big process and refine it into smaller more
manageable processes. A common example of how this can be used is shown below. It
makes use of generating an employees pay, this is a complex procedure as it involved
deducting tax etc.
Once the programmers start to develop the system they will also use flowcharts and
pseudocode to model the system, this will be covered in the computational thinking unit.
Prototypes
As part of the design phase the developers may produce a prototypes. Prototypes are mock
ups of the system or very basic versions of the system that are given to the stakeholders to
use and gather feedback allowing refinement of the system to happen before development
fully begins. Prototypes can be used to show where the problems are and what does and
does not work for the end users.
Examples of prototypes:
24
IBComputerScience - Textbook
The first picture shows the original design of the interface and then how it was created in a
basic form on the computer. Users would then have been asked to interact with the product
and provide feedback before it reached its final version as shown. Google glasses could be
an example of a prototype, Google created a version of the glasses and you could register to
buy a pair, if you bought the pair you had to participate in the development of the glasses by
giving feedback to the product. Google quietly retired the project after receiving negative
feedback. If the companies had not involved the end user they may have ended up with an
disliked / unworkable product.
It is impossible to discuss the design and development of systems without thinking about the ethics
behind the system. Is it ok to ask people to regularly change their working habits because a new system
has been developed? Many people feel uncomfortable with change, is it ok to make people feel unhappy
in their work on order to progress?
Also it is undeniable that technology makes processes more streamlined, reducing the need for as many
workers. To what extent is making people redundant acceptable in the pursuit of a “better” product?
It is important that devices and systems are usable. System designers spend a lot of time
and effort ensuring everyone can use their product however, there will be accessibility
issues that need to be taken into consideration. Accessibility issues are the issues people
may have when they are trying to use the system. The table below shows common devices,
the usability/accessibility and the solutions to these.
25
IBComputerScience - Textbook
For any device you use it is possible to think of problems that may occur for some people. In
most cases there is technology available that can compensate for the issues.
Usability
Usability is problems that may occur when people are using the system. Things that
designers have thought of but which may still occur. These problems are system based not
issues that the user may have.
In the following scenarios the usability issues are discussed as well as what can be done to
overcome the issues.
Ticketing systems allow you to buy tickets online. This could be for planes, concerts, the
cinema etc. Usually when you buy tickets there is not too much of a rush therefore the
ticketing system can handle the amount of enquiries. Sometimes however, there are very
popular tickets that will sell out within minutes – it is possible that when selling the ticket is
double sold leaving one person disappointed. How does the system cope with these?
One way in which the system copes with this is when you are allocated a ticket a “hold” is
placed upon the ticket. The transaction must be completed within a set time otherwise the
ticket is placed back into the pool. In theory the ticket could be selected at exactly the same
time although this would be a very freak incident as the processing speed of computers is so
fast.
Voice recognition allows you to speak to a machine rather than enter the instructions in the
traditional manner. This allows people with access issues to access the machine easily, it
also means computer equipment can be used by a wider range of people from young
children to older adults. But what happens when you have a strong accent? In the UK there
are 57 recognised regional accents. How does the computer cope with the accent of
someone from the Highlands and Islands of Scotland compared to a broad Liverpudlian
accent that has many vowel changes?
The short answer is the system can not very well. Most software is trained to understand
the accents of the target market however very strong regional or strong but non descript
accents can often confuse the machine.
Computer systems contain many components, many made from finite rare materials. It might be worth
considering the following question:
To what extent is it our moral responsibility to find sustainable sources of Technology, before developing
more technology based on depleting resources?
As computers are being made more ‘intelligent’ and more intuitive for people to use especially younger
children. Should programmers be responsible for making them safe?
26
IBComputerScience - Textbook
4: Why is it important to include the end user in the analysis and design stage?
1: KCM telecommunications company are currently using an outdated system and have
employed someone to create them a solution. Explain the options available to move to the
new system? Which would you recommend for the company? Why?
2: It is argued that we have become too reliant on technology. What are the social issues
associated with this?
3: Xcel properties is a company specializing in finding homes for expatriates. They have a lot
of data on their system including names, addresses and salary details. Discuss the ways in
which they could ensure they do not lose data due to a technical failure.
4: You are developing a new system for MSL enterprises. Discuss they ways in which you
could test the system to make sure it functions correctly.
5: Why are updates required in a system? How do you release these updates to the users?
27
IBComputerScience - Textbook
To most people the inner workings of a computer system are magic, something that is not
easily understandable and will always remain a mystery. To these people it might be
surprising to learn that computers are actually dumb. All work computers complete have to
be simple arithmetic or logic calculations. Eventually computers probably will be able to
learn things for themselves and make their own decisions but at the moment they have just
been cleverly programmed to look intelligent.
In this unit we will peek inside the box to have a look at what it does.
Computer Architecture
A computer system can be represented using the following diagram:
ALU M M
Input Output
D A
CU R R
Cache Memory
RAM Memory
Hard Drive
28
IBComputerScience - Textbook
Computer systems work using input devices, processor, memory and output devices. In this
unit we will look at each of the individual components separately and then look at how they
work together.
Input – An input into a computer system usually comes from a device. Such as a mouse, a
keyboard, a scanner, or a touch screen. The input from the device is processed by the
processor before being sent to memory if required.
Inside the processor (also known as the central processing unit) there are four components
you need to know about:
ALU – The arithmetic and logic unit, this unit performs all the calculations and logical
comparisons for the machine.
CU – the control unit, the control unit is responsible for the overall running of the machine,
ensuring instructions are decoded correctly.
MAR – Memory Address Register, this register stores the address of the next instruction of
the program.
MDR – Memory Data Register, this register stores the data that is in current use.
Once the processing has occurred the output is displayed on screen if necessary. Otherwise
the machine just continues onto the next instruction.
First of all there are two types of memory in a computer system. The first is primary
memory. This is the registers, the cache and RAM. The data in this memory is lost when the
computer is switched off and can some times per referred to as volatile memory. As
explained above the registers are the smallest memory inside the computer system. They
can only store one single piece of data at any given time. This is the data that is currently
being used. As they are the smallest they are also the fastest memory in the machine. The
cache memory is the memory closest to the processor, as it is closest to the processor and
relatively small it is the next fastest memory in the machine. The cache memory stores the
most commonly used instructions. This speeds up the computer. The final piece of primary
memory in the system is RAM – random access memory. Random access memory stores
the operating system and the programs/files currently in use. Once you turn off the
machine everything in RAM that is not saved to secondary memory is lost. In the instruction
cycle the data in RAM is taken to the register when needed. RAM is relatively quick to
access.
If the operating system and programs are stored in RAM but RAM is lost when the computer
is switched off you may be wondering how the computer ever switches on. There is a
special section of primary memory called ROM. Read only memory (ROM) is as the name
suggests permanent instructions stored on a chip. When you press the power button on
your machine the ROM is activated, points the processor towards the start of the operating
system and from there the operating system takes over the running of the machine.
29
IBComputerScience - Textbook
The machine instruction cycle, is the cycle that happens thousands of times per second in
your machine. It is required to carry out the instructions in the computer. It is useful to
know this cycle as it explains how each section of the computer system is used.
3. Execute
The Control Unit of CPU passes the decoded information as a sequence of control signals to
the relevant function units of the CPU to perform the actions required by the instruction
such as reading values from registers, passing them to the ALU to perform mathematical or
logic functions on them, and writing the result back to a register. If the ALU is involved, it
sends a condition signal back to the CU.
4. Store result
The result generated by the operation is stored in the main memory, or sent to an output
device. Based on the condition of any feedback from the ALU, Program Counter may be
updated to a different address from which the next instruction will be fetched.
Secondary Memory
Secondary memory or backing storage it is where all the files and programs are stored when
not in use. In the computer system this is the hard drive, however you also have removable
backing storage in the form of SD cards, memory sticks and to some extent CD/DVD’s.
Backing storage has too slow a read/write speed to be used in the same way as primary
memory however it is required in a computer system to store the data when not in use. If
we did not have backing storage the computer would have to be switched on all the time
and much more susceptible to data loss. Magnetic tape in some cases is sometimes still
used for backing storage, this is because it can store lots of data in a small space.
Random Access: Random access memory means that you can skip straight to the file you
want. Therefore it is quick to access files.
Sequential Access: Sequential access memory means that you have to look through all the
files in order before reaching the one you want. Files located at the beginning are quick to
find but files located at the end would take a long time to reach. Sequential access is only
really used for backing up data now as it is not useful to store data this way for everyday
use.
It is useful for you to know roughly the size, speed and uses of the following secondary
memory devices:
30
IBComputerScience - Textbook
Before there were CD’s which stored 650 mb of data, floppy disks were the normal form of
removable backing storage. These held 1.44 mb of data which is roughly 1/3 of a song.
In the late 80/90s one of the biggest selling computers was the Amiga 500 it had a massive 512Kb
or RAM.
31
IBComputerScience - Textbook
Operating Systems
As discussed throughout this unit, the operating system is essential to the running of the
computer. It runs the machine and allows us to open the programs we want to without it
being too difficult. Without the graphical user interfaces we are used to computer systems
would be to complex for anyone but expert users to understand.
There are many different operating systems each serving different purposes. Mobile
operating systems allow us to communicate and using apps on smartphones, network
operating systems allow networks to be managed. Traditional operating systems allow us to
use laptop and desktop computers, they usually allow us to connect to networks. Dedicated
operating systems are operating systems that serve specific purposes for example. They are
the systems that allow banks to carry out transaction in batch (processing payments etc.),
they allow central heating systems to respond to sensors. Real time operating systems we
have not covered as much, they are responsible for systems such as auto pilot, air traffic
control, life support machines (systems where “crashing” could be catastrophic). In this unit
we are mainly focused on the operating systems we find on laptops and desktops.
Interface - The operating system provides a user interface allowing us to interact with the
computer. There are three different types of interfaces:
32
IBComputerScience - Textbook
Advantages
Easy to operate
Simple and impossible to mess up
Disadvantages
Slow to operate
Cannot skip steps and can only access a function
through a specific route
PS3 interface
Advantages
- Good to use and simplifies for user
Disadvantages
You’re limited if you want to go more in depth
takes up a lot of memory with the animation
Apple Graphical user interface
Graphical User Interfaces make frequent use of metaphors:
File icons -> within the computer files aren’t really represented by respective icons
Desktop -> files aren’t actually organised on a desk
One example metaphor I found was the “Trash Can” or “Bin” when
we put the files in there we are not literally deleting them. We are
marking them for deletion and the computer will deal with them
later. In some cases we are only putting them in a different
virtualisation of our file area until we tell the computer to ditch
them.
Managing Time
The CPU as you know is required to execute
instructions - the operating system manages the CPU
33
IBComputerScience - Textbook
time allowing all operations to be completed. (this will be explored more in the resource
management unit).
Multi Task
The operating system allows us to have many programs open at the same time and to be
able to perform different operations at the same time. For example you might be working
on a report, listening to Spotify, have your email open etc. The operating system divides the
processor time between the programs in order to make it looks like the programs are
running simultaneously.
Manages Memory
The operating system manages the memory of the computer system, it transfers data to and
from backing storage and controls the primary memory.
Using your knowledge of the O/S you run list some functions that you think may be used to
manage memory in the computer system:
Manages Peripherals
A peripheral device is generally defined as any auxiliary device such as a computer mouse or
keyboard that connects to and works with the computer in some way.
Mouse
Keyboard
Headphones
Keyboard
Microphone
Printer
Peripherals need to be managed as they operate at different speeds, the operating system
needs to account for the difference between the output speed or input speed of the
peripheral and the CPU operating speed. It does this by providing a buffer.
For example sending data to a printer.
if we did not do this then when we sent information to the printer it would render our
computers useless for a while as the CPU would have to wait of the printer to receive the
information fully before moving on to the next task and printers read data much slower than
CPU’s.
Organises Memory
34
IBComputerScience - Textbook
The above graphic shows how we the user see files, organized in to folders easy to find.
However the graphic below shows how files are actually stored. They are separated across
the hard drive, into separate sectors and tracks, large files stored over many sectors. The
operating system manages where the files are saved, and where to retrieve them from if we
want them displayed on our screen
Security
User accounts allow us to have different users set up on the machine, this operating
system keeps each users file separate from the other
35
IBComputerScience - Textbook
User privileges, the operating system allows different privileges to be set for
different users, this means that executable files can be limited to only trusted users,
helping to keep the machines safe.
Anti virus software is provided by the operating system to prevent viruses access the
machine
Firewalls are provided by the operating system to prevent unauthorized access to
the machine
Utilities
The operating system also provides many utilities that help the computer to function
correctly. For example:
Defragmentation software - software that takes the sectors of the hard disk that are empty
as the file has been deleted and moves them together. This limits the read/write time and
means bigger files can be stored consecutively.
Application Software
The Operating System is known as System software, it does not do any tasks for us. If we
only had an operating system our computer would not be that useful. That is why we need
application software. The following table shows the different application software available
to the user and the jobs it can carry out.
Database SQL Server, MS Store data in an organized Produce reports from data,
Access and logical manner which store information, query data
can be used to produce
information
36
IBComputerScience - Textbook
the network
Sound editing Garageband To create songs The ability to record into the
software Audacity software, or add recordings to
the software in order to
manipulate them into songs
There are many similarities in the menu structures across software packages. This is to help
people learn the software quickly and become competent within a reasonable timescale.
There are many common metaphors used across platforms such as scissors for cut, a floppy
disk for save. By having these common metaphors, people feel less alienated by new
software and can adapt to the software quickly.
Binary Representation
All computers use binary to represent data, the computer is filled with millions of transistors
that are either on (1) or off (0). Depending on the state of the transistors depends on the
data that is processed. All data must be represented as 1 and 0, nothing in a computer
system is represented in any other form.
Computers used to be very simple devices they performed calculations depending on how
vacuum tubes were set. Using programs where the user could write a program, print out punch
cards and manually feed the punch cards into their machines in order to run their program.
Following on from this we had procedural programming where computers that had to follow
steps in order. Now we have object orientated multiple input programs. These programs
required much more memory and more sophisticated data representation.
Expressions of Size
The smallest information that can be stored in a computer is a bit a bit is a 1 or 0, the next
measurement is a byte which is 8 bits.
37
IBComputerScience - Textbook
Bit 1 or 0
Byte 8 bits
RAM is measured in gigabytes (usually). Hard drives in gigabytes, although terabytes are
becoming more common. As technology has progressed the size required to store data has
decreased. What once required a whole room of storage now only required a postage
stamp sized device.
The 2014 MacBook pro had 8Gb RAM and 512Gb memory
The IBM Mainframe (which sent man to the moon) has 8 – 64 kb RAM and 1mb memory (not
even enough space to store a word document containing a picture)
38
IBComputerScience - Textbook
Binary Conversion
One thing you need to be able to do on this course is to convert binary numbers into decimal
and vice versa. To do this it is important to think about how numbers work.
Decimal - the decimal/denary number system is based on 10 units (0 - 9), once we pass the
number nine we have ten + the number of units. In primary school you may have learned
numbers as hundred, tens and units.
If we have a closer look at the number 8495 this becomes more clear. We know that this is
eight thousand four hundred and ninety 5 but how? it is all to do with place holders.
Each space in our number represents the number of each value that needs to be added for
example:
10 ^ 3 = 1000 10 ^ 2 = 100 10 ^ 1 = 10 10 ^ 0 = 1
8 4 9 5
We know that in a decimal number system once we get to 9 we need to add one in the next
column. The same principle works for binary. Binary is base 2 therefore is can be a 1 or 0 if
we have 1 and need to add one we move along the number line.
1 0 1 1
Using this principle we can work out any number in any base as long as we have the correct
number line
0 0 1 1 0 1 0 0 1 1 1 1
1 0 0 1 0 0 0 0 0 0 0 1
0 0 0 1 1 1 1 1 1 1 1 1
39
IBComputerScience - Textbook
1 0 0 1 0 0 1 1
1 0 1 1 0 1 0 1 0 1 0
Binary Addition
1 + 1 = 10
00001001
1+1+1 = 11
00001111
= 00011000
This works however if we run out of bits to move along to then an overflow error occurs.
This means that the number of bits allocated to the variable has been exceeded and an error
has happened. Therefore in Java programming it is important to use the correct variable
remembering int has an upper limit of 2,147,483,647.
Decimal Numbers
Decimal numbers are stored in a different way. It is similar to scientific notation. We store
the number without the decimal point (mantissa) and then the number showing where the
decimal point should be (exponent).
40
IBComputerScience - Textbook
With all the talk of colours and storing colours it is important that there are many options
available to people producing digital images. It would be difficult for users to remember
binary numbers for colours this is why hexadecimal has been used as a kind of shorthand to
remember binary, instead of writing down the 16 bit colour code you break each 16 bit
colour code into 4 bit chunks and use the hexadecimal short code.
Bin 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111
hex 0 1 2 3 4 5 6 7 8 9 A B C D E F
To convert 0110111000001000 separate 0110 1110 0000 1000 and add the correct hex 6E08
The same method is used to remember any binary numbers. Hexadecimal numbers are also
used to refer to memory locations on the machine.
File Extensions
Remembering that all data is stored as binary file types are important, the file type tells the
computer what encoding has been used so that the computer knows how to read it. For
example 00000000 01000001 could be the letter A (in Unicode), it could be the number 65,
it could be a sound in an MP3 file or a colour in a picture. It depends on how the computer
needs to decode the data. Common data types are as follows:
Text
41
IBComputerScience - Textbook
bits, therefore there are only (2^7) or 128 characters that are available. What are the
problems with this? iCloud
128 characters is not enough to represent anything that is not the Latin alphabet
Internationalisation is a problem without more than 128 characters, therefore global use of
software would be a problem
To overcome this problem Unicode was used. Unicode uses 16 bit to 32 to store characters
this allows 65 536 - 4294967296 available characters. Allowing all possible (known)
alphabets.
If you were creating a program that would only be used in one specific language then ASCII
encoding would be best as it saves space. However, if you are unsure of where the product
would be used Unicode should be used.
Pictures/Graphics
A bitmap is like the name suggests a map of the picture showing where each colour should
go. The picture is made up of pixels and the colour information for each pixel that is then
reproduced by the computer onto the screen.
42
IBComputerScience - Textbook
The image on the left is the original image and on the left the zoomed image. Each pixel
requires 24bits to store the colour information.
The number of bit required to store the picture is known as “colour or bit depth” the
number of bits available for colour information the less bits available the less colours
available for use:
43
IBComputerScience - Textbook
1 2 (20)
2 4 (22)
8 256 (28)
16 65536 (216)
24 16777216 (224)
It is pointless storing colour information in more that 24bits as the average human can only
distinguish between 16 million colours.
44
IBComputerScience - Textbook
You need to be able to calculate the storage requirements of any given file. For example if a
picture is 300 dpi and it is 5.5 * 4.5 with a 16 bit colour depth what size will the
(uncompressed) file be.
A vector graphic is different, it stores the information in layers. Each layer stores the
coordinates of where it should be on the page and reproduces itself on the screen. As this
coordinates are stored relative to the size of the page, the image can be scaled up and down
easily without loss of detail.
Metadata
Metadata is data about the data object for example when you take a photograph with your
camera on your mobile phone it stores additional information such as the place the photo
was taken, the data and time the photograph was taken and where it is stored on the phone.
This metadata is stored alongside the photograph to help with searching, and to help
applications track where the photos come from.
Compression
Compression of files is required so they can be sent across networks easier. It also allows
more to be stored in memory as uncompressed pictures, videos and audio files use a lot of
space.
There are two types of compression:
Lossless compression – compression techniques that compress the data without losing any
of the original information.
Lossy compression – compression techniques that compress data but lose original
information.
45
IBComputerScience - Textbook
Techniques:
Reduce the sample rate (the number of times the sound is produced per second)
You can exploit the limitations of human hearing and get rid of the sounds humans
won’t hear
To decrease the size of movie files you can:
TOK Link
To what extent are the ways in which meaning is encoded in computer languages similar to the
ways in which humans convey knowledge?
If we don’t understand the language used to store our data how do we know what we see is a
true representation?
46
IBComputerScience - Textbook
Boolean Logic
Boolean Operators
AND NAND
OR NOR
NOT XOR
This statement can be represented using the Boolean statement. When A is the temperature
and B is the rain.
A •B
It has to be warm (input A) AND NOT raining (input B) for conditions to be right for a picnic
Another example would be “if there is no seatbelt of the door is open sound an alarm”, can
be represented as the following where A is the seatbelt and B is the door.
_
A+B
Truth Tables
47
IBComputerScience - Textbook
AND OR NOT
0 0 1 0 0 1 0 0 0
1 0 1 1 0 0 0 1 1
0 1 1 0 1 0 1 0 1
1 1 0 1 1 0 1 1 0
Using the same examples as above, the truth tables show when the output will be true.
48
IBComputerScience - Textbook
You can also use truth tables to determine if two Boolean expressions or equal or not.
The truth table shows that these two expressions are not equal.
Circuit Diagrams
It is also important that you can represent Boolean logic statements as circuit diagrams.
Circuit diagrams consist of inputs, logic gate and outputs. For this course you have to be
able to:
Draw a logic diagram for a given expression
State the expression that is being represented by the diagram
Draw a truth table for the logic circuit shown
OR + If 1 or both is true
put it through
NOR _ Inverse of OR
+
49
IBComputerScience - Textbook
salesTax = a – b + 0.1
Work out the value of this expression when a is 600 and b is 200.
The programmer has made an error in the code. When a is 600 and b is 200 the expected
answer is 40.
Rewrite the line of code with added parenthesis to give the expected result
2: Ahmed is writing a program to record the data of members of the school football squad.
The input data will be validated. One input is the number of years a member has played for
the team. This will be 0. 1 or 2.
The flow chart for the validation of number of years is shown below:
INPUT
Number of years
0
IF number
of years 1
50
IBComputerScience - Textbook
The squad has 30 members. Ahmed stores the records in an array called Squad. To
calculate how many females there are he designs this Pseudocode.
NoOfFemales = 0
Index = 1
While Index < 30
If Squad[Index].sex = “f”
Then
NoOfFemales = NoOfFemales + 1
End if
Index = index + 1
ENDWHILE
3: The operating system controlling the student’s home computer is a single-user, multi-
tasking operating system.
4: Complete a truth table to show the outputs for the possible inputs to this circuit.
a)
b)
A and B OR NOT B
7: Amalia Rogriguez is a student and is completing her homework. This requires her to view
webpages, edit documents and print out a draft copy.
However, she is also surfing the web, keeping up to date on her social networking sites as
well as downloading apps and music from a P2P site.
a) For one of the above applications, outline one task that is carried out by the application
program itself.
Within the application the GUI elements are reliant on the operating system.
51
IBComputerScience - Textbook
b) Identify two GUI components that are common to all of the above and carried out by the
operating system.
Outline how the use of abstract GUI components simplifies the application programming.
8: The operating system in the latest mobile phones allows the user to open more than one
application at the same times.
a) State three possible applications that might be open at the same time.
10: Explain how the use of cache memory can speed up a computer system.
23
194
3940
482
0111100
1011011
1100011
1010101
So far in this book we have covered the use of networks and how networks have changed
peoples lives. However, we have not looked at what a network is, what types of networks
there are and how networks function. This unit will cover these topics.
Network Fundamentals
Types of Networks:
There are many different types of networks, each with their own unique purpose. The
following is not an exhaustive list of networks but are the main networks to be aware of.
Local Area Network - A network for one organization that covers one building or campus. It
holds the data and storage for that organization on that campus. To run this network you
will need a server and machines to connect to the server. You may also have printer,
scanner and other devices connected to the network. An example would be any network in
an office building.
Virtual Local Area Network – Virtual area networks have the same characteristics as a local
area network however, instead of using their own wiring etc. they will make use of wiring
currently in place but because they are virtually a local area network they will not be able to
see other devices on the same physical connections. An example of this may be if several
companies share a building they may use the same network cabling but each company has
its own separate network.
Wireless Local Area Network – A Wireless local area network functions exactly the same as
a LAN without the wires. The advantage being people can connect to the network with
tablets and mobile phones.
Wide Area Network – A wide area network is a network that spans larger geographical areas
for example they may span countries or continents. The purpose of the network is to share
information and store data. It is likely that a WAN makes use of both private hardware
within buildings but public hardware to connect across countries. An example of this would
be if a company has offices across several locations and they are all connected together.
Internet – The Internet is the most common WAN it is a connection of networks all joined
together to cover the world. Most people connect through a telephone socket in their
home/office, which is connected to a local exchange that is connected to a national
exchange, which then connects to another national exchange.
Storage Area Network – Due to the limitations of storage on individual machines, storage
area networks can be used to store data. The SAN will most likely consist of many machines
connected to a network that contains many storage devices. Instead of storing data locally
on a machine it is stored on the network and accessed when required. An example of this
would be in the film industry, film is very memory intensive, when editing movies it is likely
that footage is stored on the network and only moved to machines when it is being worked
on.
Extranet – An extranet is a network that has a public section and a private section. The
public section is used to show public information such as events, information about the
company etc. however it will also have a private area people are required to log into to get
53
IBComputerScience - Textbook
to more private information. The extranet usually uses a website to gain access. An
example of this would be a school website that has information about the school but a log in
area containing materials for study etc.
Personal Area Network - A PAN is usually within one household and often uses wireless
capabilities. In a PAN many personal devices are connected together and can share
information if necessary. An example would be a household that uses laptops connected to
the Wi-Fi, as well as tablets, games consoles and televisions, there may also be storage on
the network where data can be moved to.
Peer to Peer Network – A P2P network allows users to share information however the
information is stored on each persons machine and accessed from each persons machine
rather than a server. Although they can be used for legitimate reasons they are often used
to share copyrighted material. Users download the peer-to-peer software, they become a
seed for each of the materials they wish to share and when people put out a request for the
material their computers start to upload the data to others.
Virtual Private Networks allow people to use public network connections to access private
networks. For example connecting to a work private local area network from home or
another location. Using VPN technology allows companies to keep their local area network
safe but provide a secure method of connecting from outside.
The VPN acts as a trusted mid point between the computers outside the company network
and the company network. First of all a request is made from the computer to join the
network. To do this it contacts the VPN and sets up a secure connection using
authentication. Once the secure connection is established the VPN uses tunnel software to
set up a link to the Local Area Network, because the request comes from a trusted IP (the
VPN) the authentication occurs and the computer can connect through the VPN. In addition
the VPN model provides encryption, all data travelling along the connection is encrypted so
even if attacked only encrypted data would be seen. It provides message integrity so it is
clear no tampering has occurred.
Another use for VPNs is to provide people with access to an IP address with a different
geographical location. This can be useful in many situations such as accessing data where is
may be censored, being able to access information from another country if away from
home. As with peer-to-peer networking people have exploited the use of VPN’s to
participate in illegal activities such as accessing television shows that would otherwise be
unavailable in their current country.
Research has shown that due to Network technology improving people work longer. Should
businesses make a conscious effort to stop people working longer or now much of the work is
less manual has it become the social norm?
Data Transmission
54
IBComputerScience - Textbook
If I developed a system independent of other people chances are with the right talent I could
build a perfectly good system.
Application layer - closest to user, provides the support to the application that needs to the
network resources. We interact with this layer
Presentation layer – The layer responsible for the transfer of data between formats. So the
data can be read by receiving computer o/s level
Session layer – Responsible for creating a session between the two computers
Transport layer –makes sure the packets get there correctly
Network layer – Adds the IP address of sender and destination IP address router level
Data link layer – responsible for transferring the data, takes the binary and makes it readable
by structuring it
Physical layer – actual connecting devices,
55
IBComputerScience - Textbook
Standards are a means of communicating between different servers, so local servers and
networks can be connected in order to share information and data. Without standards no
networks could communicate, thus the Internet as a whole would not work, because nobody
could access anything.
The whole point of the Internet is to give a medium for sharing data, without standards,
which give the ability to share data between systems, it would have no purpose.
This would affect the majority of the world, a specific example that would be affected would
be multinational corporations. Without a medium for sharing data from one office in one
country to another, their business would be less efficient. Additionally, the clients would be
affected because of their inability to interact with the business.
The Internet would be totally useless because systems are programs within your computer
that are made in a language. The Internet gives us access to other people’s systems and
gives us the ability to download and use them. Without standards there is a very high risk of
systems being in different languages not allowing others to use systems available to them on
the line.
Protocols
When discussing standards it is also essential to think carefully about protocols. Protocols
are the list of instructions devices agree on to determine how to communicate. It is an
agreed behaviour between devices. Without them devices would not be able to
communicate as: data integrity could be compromised, the flow of data could be
interrupted, deadlocks could occur, congestion may happen and error may occur. An
example of this can be demonstrated when we think about driving.
Data integrity: data integrity is concerned with the validity of the data, data can be changed
in transmission in a number of ways but data integrity checking aims to ensure the data
received is the same as the data sent. This is completed using Hash functions, Hash message
authentication codes perform a calculation on the data and then sends the code with a
secret key to the destination. If the hash codes match it is assumed the data has not been
tampered with.
Error Checking: A check digit is sent with the packet, it is recalculated at the destination,
and if this matches it is assumed that the data has not been tampered with.
Sending Data
56
IBComputerScience - Textbook
Data Packets:
On your machine if you look closely at activity monitor you may have seen this following:
This shows the number of packets my machine has received and sent. I sent a lot more data
that I received. Packets are how data is sent across networks. The data to be sent is broken
down into packets, numbered and sent on their way. At the other end the packets are
collected put into order and unpacked. Data is sent in packets as it is more efficient, sending
a big file as one packet would cause unnecessary congestion on networks.
57
IBComputerScience - Textbook
Packet Switching
Circuit Switching
Data is sent along the same route. The advantage to the is the packets are sent in order and
will arrive in order so they are easier to piece together and less likely to get lost. The issue is
they are easier to eavesdrop upon and could be intercepted.
Like all networks, computer networks have flaws. Even if I have the fastest connection in the
world it is limited by the connections it is connected to.
An example being the rail network shown. Traffic can move very fast in the Davos valley and
very fast in the St Moritz valley however between the two valleys is very slow because the
connections are much slower.
Another example would be the school network, inside the school the network is very fast, as
is the connection to the outside networks however when we reach the local hub traffic is
slowed which when many people are trying to watch an offsite video on the network can
slow the network down.
One way to help prevent the slowing of traffic on the network would be to compress the
data, we looked at data compression in the computer organisation unit. However, data
needs to be compressed so it fits into less packets and is easily transported across the
networks. The less packets on the network the less congested and therefore faster the
network.
58
IBComputerScience - Textbook
Transmission Media:
When creating a network there are many different transmission mediums you can use:
Coaxial Cable Much slower Very reliable but Reasonable Relatively cheap
than fibre optic can have although they
interference can be listened to
Twisted Pair Faster than Very reliable but Reasonable Relatively cheap
Coaxial but can have although they
slower than fibre interference can be listened to
optic
Wireless Networks
Advantages:
They are cheap to set up
They can be set up anywhere as no need for wiring
Multiple devices can be added with ease
Disadvantages:
59
IBComputerScience - Textbook
WiMAX Works the same as In theory 1gbps and a the technology is still
wifi but uses a range of 30 miles in its infancy and is still
different / faster likely to be interfered
standard with
60
IBComputerScience - Textbook
Future developments:
One development that might possibly replace WiFi is Lifi, using light emitting diodes, LiFi,
uses light to transmit signals to devices. It is extremely fast with speeds up to 224 gigabits
per second. The downfall of this technology is that is requires the light to be seen.
Network Security
Networks allow us to send data to many devices across the globe. They have enabled us to
build global corporations that share the same data. They allow us to speak to people on the
other side of the globe but they do all this through sharing data. There is rarely a week goes
by where there is no news of a data breach in a system, people stealing data because of
flaws in networks. In this lesson we will look at the different security methods employed to
stop these breaches and their perceived effectiveness.
Physical
it is a good idea to have physical security, such as locks on doors etc. In the past people
used to leave their routers either unprotected or in windows with the username and
password on display, this led to people using the devices without authorization.
Coded
Trusted MAC MAC addresses are the unique Using only trusted MAC
identifier assigned to items on addresses could mean that
a network. Having a “white genuinely good websites are
list” of trusted MAC addresses blacklisted by accident.
allows the network prevent
access to and from non trusted
places.
Protected Access Use a username and password If there is a high turn over of
to gain access to the router people in the company
means that only authorized constantly providing user
and trusted users can access names and passwords is time
the system. consuming.
61
IBComputerScience - Textbook
i) VPN
ii) Denial of Service Attack
iii) OSI Model
iv) Data Packet
v) Compression
2: Explain clearly the difference between Packet Switching and Circuit Switching when
sending data across a network. Stating Advantages and disadvantages when appropriate.
3: Describe three security measures that could be taken to prevent hacking on a network.
62
IBComputerScience - Textbook
Computational thinking has recently emerged as one of the key skill sets to have in the 21 st
century. Essentially it is the ability to see a big problem and break it down into its
components parts in order to manage it more easily.
63
IBComputerScience - Textbook
Thinking Procedurally
Thinking Procedurally requires us to identify the task that needs to be completed, enables us
to evaluate the correct order for the task and allows us to understand that tasks can be
separated and completed be different people/methods.
Stage One:
Ask
Questions
Stage Two
Look for trends in the data you have been given, are
there any generalizations you can make? If there are
any outlying data items are they exceptions or a
second emerging pattern?
64
IBComputerScience - Textbook
Stage Three
Sub Procedures
Sub procedures are a list of things that can happen independently within the main task.
They can usually be reused in other programs or systems. For example if were to build a car
you could say that the main method would be:
1: Build engine
2: Build chassis
3: Add braking system to chassis
4: Add fuel system to chassis
5: Add exhaust system
6: Add interior
7: Add frame
8: Paint
9: Add wheels
65
IBComputerScience - Textbook
Some of these things can be carried out at the same time. For example an engine could be
built at the same time as I build the chassis. Some of these things could be reused in
different procedures.
For example: An Audi A3, Golf and Skoda Fabia (I think) are all the same chassis they just
contain different frames, slightly different engine configurations and different interiors.
To make these cars Volkswagen would not change the factory just the procedure. e.g. if i
separate the building an engine component of the making the car, the adding a frame and
the adding the interior component then I can create any version of the car I want.
As a diagram this may look like the following:
Build
Chassis
Build Build
Engine Frame
Add
braking
system
Prepare
Add
Interior
Fuel
system
Add
exhaust
system
Paint
Add
Wheels
66
IBComputerScience - Textbook
.
Thinking Logically
We make decisions everyday hundreds of them. Should I leave the house at 730 or push it
to 735? should I catch the 8 or the 51 bus? Should I have canteen food or go to the salad
bar? Many of these decisions won’t make a big difference but nevertheless we make them
all the time. Decisions that may be more pertinent to you at this stage of your schooling
may be where to study and what to study. These things do have a knock on effect for your
future.
Below is an example of some decisions and the effects that they may have.
Whether to stay in bed 5 Stay in bed 5 minutes longer Making your friend wait longer
minutes longer or get up with and possibly miss the bus
the alarm
Whether to take the short cut Take the short cut Look a little bit muddy at
which is messy or the longer school
road
67
IBComputerScience - Textbook
It is important for programming to be able to identify the factors (or circumstances) around
the decisions that need to be made. For example if I wanted to write a program that told
you what to do at the weekend what factors would be involved?
IF AND OR NOT ELSE - these are important words that you will come to associate with both
decision making and in the magical art of programming. IF is the word that accompanies
Weather
most decisions made, AND OR NOT ELSE help us to make up the conditions associated with
the decision. Cost
for example here is the thought process I had for choosing a Halloween costume:
TV shows I
have to
binge
watch 68
IBComputerScience - Textbook
You can see from this that you can break most decisions into statements using the words IF
AND OR NOT ELSE
Branching is the word that describes what happens as a result of the conditions taken. It is
effectively the steps that you follow as a result of what has been said. It is the path that is
followed. This could be modelled using the following.
Decisio
Decisio Decisio
Link to programming IF statements are the backbone of computer science. They allow us to
create functioning programs that allow user interaction.
To what extent can reason be distilled into algorithms? When we are reasoning are we really just making
algorithms in our head to help decision making? If this is the case can we create one big self help book for all
life’s situations in order to help people out?
Thinking Ahead
So far in the course we have thought about the process we
would carry out to solve our problems however, we have not
stopped to think about the tools we need in order to solve the
problems. We need to think about the tools we need in order
to complete the task and then outputs that we expect to
receive from the system. If we have these ideas firmly in our
head then we can begin to plan our systems easily.
69
IBComputerScience - Textbook
Thinking about what we need is called pre planning. Why is pre planning required? if we
pre plan then we can collect the things that we need in order to complete a task, this
enables the task to go smoother as we know we have all the inputs we require. For example
baking a birthday cake. The pre planning that is required would be to know what ingredients
I need for the cake and the icing. This is important as if I don’t have them then can’t have
the output that I want.
Algorithms and methods, the backbone of all computer programs. Very rarely in
programming will a program follow instructions in a linear fashion. Where we can start at
the beginning and follow each instruction one by one until we reach the end. Programs are
designed to allow interaction between machine and user, in order to for this to happen we
need to have different methods associated with different tasks. The simple way to view
methods is in the following way:
Input
some kind
Input of output
Input
Therefore when designing or using a pre existing methods you need to know the pre
conditions (inputs) that the method needs in order to complete the task.
In programming these inputs become the parameters you have to pass into the methods.
The outputs become the return types you expect from the parameters.
Exceptions:
Most problems contain exceptions that are outwith the norm. An example I can think of in a
school that runs trip for every child there is a selection process usually all grade 9’s go to the
grade 9 trip. All grade 10’s to the grade 10 trip, Grade 11’s go to the European trips and the
Grade 12’s go outside Europe. However due to personal reasons some grade 12 students
may choose to stay in Europe. This is an exception to the rule, it would be something we
have to consider but only after we have dealt with the patterns.
70
IBComputerScience - Textbook
Thinking Concurrently
For the purpose of this section we are going to have to think about building a house. The
stages involved in building a house can be summarised in the following way.
some of things can only be done one after the other for example. You can’t add a roof to a
house without walls. That would not work.
For example:
71
IBComputerScience - Textbook
Bars that appear after one another means that the tasks are non - concurrent the previous
task must be completed before the next one is started. Bars that appear in line with each
other or overlap in some way are concurrent they can be completed at the same time.
Concurrent processing can be used to complete problems quicker. If you can divide the
tasks up and then complete them together then the length of the project is shortened.
There are both advantages and disadvantages to this as described below:
The overall time taken to complete the project More people on site could lead to more
is decreased complications
Less wait time on projects as things are being Harder to manage more people on site.
carried out simultaneously
72
IBComputerScience - Textbook
Thinking Abstractly
Abstraction in simple terms is the representation of the “real world” or real world concepts
in the virtual worlds or programs. Abstraction requires us to start thinking about objects as
separate parts rather than the sum of its parts. One example of this would be an airport.
Airports are often just thought of places where we go in order to get somewhere different
but what makes up an airport really?
Shop Longhaul
Premises
Aeroplanes
Airline Airport
Staff
Shops European
Stock
Airport People
Security
Desks
Baggage
Check in Area
1st Class
Passengers
Lounge 2nd
Class
73
IBComputerScience - Textbook
If we were to implement the airport program then many of these boxes would become
classes and subclasses of each other.
Another way to think about abstraction is looking for the commonalities within objects and
then identifying the difference that make them unique. One example of this would be
animals. What makes us different from animals? How is a fish different from a cat?
As all computer systems are essentially aiming to represent the real world virtually,
abstraction is essential. We need to be able to show the interactions between objects in
order to elicit information or perform calculations. Whether this is completed through a
database, a program or a simulation model all objects need to be represented. In order for
programs to work efficiently we need to have as little duplicated data as possible. In
databases this is completed through a process called normalisation in coding it is by using
superclasses and subclasses.
+
So how does this look in programming and why do we do it? You know that duplication of
data is a bad thing because having to update data in many places is inefficient and leads to
mistakes. Therefore we use super classes and sub classes. Using the animal example again
we are going to create a program containing classes and sub classes.
Its possible to see abstraction everywhere. We use an abstraction in our daily lives all the
time. For example a calendar is an abstraction of time, it is a visual representation of how
we see time.
74
IBComputerScience - Textbook
Perception
One of the problems with abstraction is that the way the item is abstracted depends on the perception of the
person doing the abstraction. For example creating the classes and methods of a school from a teacher’s
point of view would be very different to a student’s point of view. To what extent do you agree that
abstraction depends on perception? Is there any way we can make it less so?
To what extent is a computer model of reality analogous to the knowledge models built up by humans about
the real world? Can we model things in the real world when many of the things we take for granted in the
real world are arbitrary divisions?
To what extent is intentional human involvement essential in the development of knowledge in the Arts? If
we have algorithms to create Art do we need artists?
To what extent is faith essential in the use and development of computer and software systems?
75
IBComputerScience - Textbook
1: Mr Smith is having a new house built and will require local tradesmen to complete a
number of tasks:
The Gantt chart below shows the tasks involved in the building of the house.
(d) Describe how the idea of abstraction applied to one of the tasks.
(e) Explain one advantage and one disadvantage of carrying out a number of tasks
concurrently.
2: Train Stations have many different sections, represent a Train Stations as an abstract
format.
3: What are pre conditions and why are they required when discussing algorithms?
4: Why is breaking a program into objects useful when working as part of a development
team.
5: Using your knowledge of thinking procedurally, create a procedure for booking flights to
New York.
76
IBComputerScience - Textbook
77
IBComputerScience - Textbook
The focus of this unit is to look more closely at the inner works of a computer system and to
think about the limitations of some systems.
When reconstructed all of these parts need to be connected in someway and they need to
work together to do useful things. One way of getting them to work together towards a
common goal is to have a “manager” of the machine. This is where the operating system
comes in to play. In the Computer Organisation unit we looked at the role of the operating
system in this unit we will look a little closer.
78
IBComputerScience - Textbook
In this unit you will be required to think about the following products:
Mainframe Computers
Servers
Personal Computers
Tablets
Laptops
Mobiles Phones and Digital Cameras
For each of the devices we will think about, what needs to be managed, What the limitations
of each device is and how we can overcome these limitations.
Examples are shown below, this however is in no way an exhaustive list.
Mainframe
Resources to be managed: multiple
processors, RAM and the secondary
memory.
Issues with mainframes: the space
requirements of a mainframe are large. You
need specialized people to run a mainframe.
Mainframes are only useful if storing
analysing terabytes of data and above.
Overcoming these limitations: Consider the
space requirements and if you don’t have
enough room consider using a server
instead. One specialized machine can do the
job of many machines.
Server
Resources to be managed: connections to
other devices, files stored on the server
Limitations of Servers: If all data is stored on
them then they can run out of space fairly
quickly
Overcoming this problem: To overcome this
problem it is worth considering if only some
data should be stored on the server and
some on personal machines.
79
IBComputerScience - Textbook
Personal Computers
Resources to be managed: processor,
primary memory and secondary memory,
peripheral devices
Limitations to Personal Computers: Single
processor machines might have issues
rendering large graphic files or high quality
video.
Overcoming the limitations: To overcome
the limitations you could invest in a
computer with multiple core processors,
increase the ram or improve the video card.
Laptops
Resources to be managed: processor,
primary memory, secondary memory,
wireless connections
Limitations: One limitation of the laptop is
its limited memory and processing power,
trying to render video on this machine would
be a very slow process. Complex processing
will drain the battery of the laptop quickly,
therefore the type of work being carried out
should be considered carefully. Wifi can be
slow especially if transferring large amounts
of data.
Overcoming the limitations: One way to
overcome the limitation is to consider
whether video rendering needs to happen
on this machine and if so consider editing
smaller sections of video at a time. To avoid
draining the battery it might be good to close
applications not in use, or remain connected
to a power lead. To overcome the Wifi
problem connect the laptop using a wired
connection.
Tablets
Resources to be managed: Processor,
primary memory, secondary memory, touch
screen.
Limitations to the device: trying to run a full
application on this device is difficult as it
does not have the power. The memory is
not big if storing lots of files.
You can consider whether you need full
functionality for the tasks you are
completing and if not use ‘light’ versions of
web apps. You could also consider buying a
tablet with expandable memory.
80
IBComputerScience - Textbook
Mobile Phones
Resources to be managed: Processor,
primary memory, secondary memory, touch
screen, network connections.
Limitations to the device: the battery life is
short on phones when in high use therefore
if relying on a phone to complete many tasks
you should leave it plugged in or ensure
there is a charging option nearby. Many
functions of a phone rely upon good
connectivity, if completing a video call or
downloading a large file try to stay within in
a high connected area.
Digital Camera
Resources to be managed: processor, SD
card, battery, focus
Limitations to this device can include video
recording, it will only shoot for 7 minutes at
a time and the microphone is not great. One
way to overcome this is to get an external
microphone that you can plug in.
In this section of the unit we will look in more detail at the operating system, the operating
system we will focus on would be one that you find on a desktop or laptop computer. It has
limited network capabilities (it will connect to a network) and also supports multiple user
accounts.
Inside the computer is organized chaos, I like to think about each of the areas as annoying
toddlers:
There is the peripheral who Then there is the hardware Then we have the memory
just wants to be seen who wants to be noticed who can’t put anything away
properly
81
IBComputerScience - Textbook
them. If they need attention, it stops all none critical processes attends their needs then
moves on. The problem with hardware is not all hardware speaks the same language.
When a device is loaded onto a system it has an associated driver, this driver enables the
operating system to decode what it wants and through the translator that is the operating
system all devices can talk to each other. Then there is secondary memory when we store
files the files are stored in fragments. These fragments are stored all over the hard drive as
there might not be room to store all the fragments next to each other. Each fragment has a
pointer telling the OS where to go to retrieve the next fragment of the file. The operating
system is responsible for finding the starting point of the file and then the next section of the
file. It can also compress the data on the disk so there are more blocks available to store
data next to each other. Finally the operating system needs to manage primary memory it
does this by keeping a track of what programs are open and which program needs the
processor time at any given point. If you open the activity monitor on a Mac O/S computer
or Task Manager on a windows machine you can see all of the tasks the operating system is
trying to manage.
Lets look at how the operating system manages resources in more detail.
Managing Memory
Computers need to be able to do more than one thing at a time for example, they should be
able to have a word processing package open while allowing us to listen to music and be
distracted by the internet and emails. However, unless they have more than one processor
computers can not truly multi task instead they take advantage of how fast they run to
pretend to multi task. To do this they can employ a couple of techniques:
Time slicing is the first technique – the processing power is split between different
operations. A fixed amount of time is set for each operation once the time limit is reached
the current state is saved, added to the list of tasks in its current state and the next task is
tackled. This means that every operation is given the same amount of processor time but if
the task is not finished within the time it has to be placed back into the queue.
Priority – the program that is “in focus” occupies most of the processors time but when
waiting upon input or it is sitting idles the resources are transferred else where. The main
program takes up a bulk of the time but the processor makes use of the downtime. If you
open activity monitor you can see the different processes being switched between.
The main thing to remember about managing memory is because processors run so fast we
will never notice that the tasks are not happening simultaneously (until something goes
wrong).
Scheduling
When using the time slicing or priority systems the processor has to have some way of
deciding what processes fit where in the schedule. The following techniques are options:
First in first out: This operates the same as a queue. The first job into the system is the one
that is completed first. However, if there is a big job at the front of the queue this could
slow the system down.
82
IBComputerScience - Textbook
Shortest Job First: in this system the shortest jobs (as the name suggests) are always
completed first. The main issue with the system is that if there are many shorts jobs that
continue to be added the longer jobs will never be reached.
Round Robin Scheduling: each process is given equal time once that time is finished the
current state is saved and the processor moves onto the next task, the unfinished task must
then wait until the processor time returns to it before continuing. The Mac operating
system uses this type of scheduling.
Multi Level Queue Scheduling: processes are marked as either batch or interactive. The
processor schedule different processes at different times based on this. Windows uses this
type of scheduling.
The amount of Random Access Memory is something that should be considered carefully
when choosing a computer system. The more RAM available the more memory intensive
programs you can run without issues and you can have more programs open at the same
time. Sometimes we over load the memory and the operating system has to compensate for
this through virtual memory and paging.
A section of the RAM is sectioned off as virtual RAM, programs that the user currently has
open which are not being used are stored in this section of the hard drive. The operating
system leaves a “page” in the actual RAM and if the program is selected the program is
brought into the actual RAM and another program is moved to virtual RAM. The advantage
of this is the user can have many more programs open than they should be able to.
83
IBComputerScience - Textbook
Managing Peripherals
Interrupts – inside the machine there is a bus known as an interrupt bus. The interrupt bus
is linked to the processor. When the peripheral has an input or an issue it sends a message
on the interrupt bus. The processor saves its current state and then attends to the
peripheral. Once the peripheral has been dealt with the previous tasks are resumed.
Examples of interrupts include: input from the keyboard, a read/write signal from an SD
card or an issue with a printer.
Polling – polling is another way to check for peripheral issues, the processor intermittently
checks each device for a signal. If there is not issue it moves on to the next task. Again as
processors work so fast you would not notice the delay.
one of the jobs of the Operating System is to make things easier to understand for the user.
One way in which this happens is through virtualization. Each of the folders shows a section
on the server. Although it is not literally divided the OS allows us to think that there is literal
divide between sections and that data we have stored in each section will remain safe. 3
TOK Links
To what extent does the use of abstraction in computer system promote or restrict the exchange
of knowledge?
How can we take the complexities of human languages and model them using graphics?
84
IBComputerScience - Textbook
85
IBComputerScience - Textbook
1: Use the Internet to compare the OS on apple mac book pro to the OS on the Apple
iPhone 7
Similarities Differences
2: Why does it make sense that washing machines, microwaves and IPods have dedicated
operating system?
4: Why is it sensible for a washing machine / mobile phone etc. to have a reduced
instruction set?
5: Why are interfaces required in a Computer System? What consequences would there be
should interfaces not exist?
7: explain what scheduling in an operating system is. Give two examples of scheduling
policies that exist in operating systems.
8: Explain how virtual memory makes use of paging to increase the size of the RAM.
9: What are interrupts? Why do you think they are more efficient than polling?
86
IBComputerScience - Textbook
This unit concentrates on sensors and how they interact with systems to produce
autonomous machines that we interact with on a daily basis.
Sensors
There are many different systems with which we interact on a daily basis including washing
machines, traffic lights, automatic doors, GPS systems. For this course you need to be able
to identify the sensors and processing that may taking place in any given system. However
the first thing that we need to think about it what sensors exist. Below is a list (by no means
exhaustive) on sensors, what they do and possible uses.
Temperature Makes sure that objects are not Used in order to regulate the temperature
over/under heated. of a pool.
Sound Converts a sound into an electrical Could be used in an alarm system, if there is
signal sound detected and alarm would sound
Tilt Makes sure that a certain angle is Can be used in mobile technology for games,
not passed, if so, the object will or to create electronic spirit levels.
automatically adjust.
Altimeter Instrument used to measure the Airplane or helicopter cockpit to get the
altitude of a given object over a high of the object
certain level
Oxygen Measures the amount of oxygen in In Oxygen sensitive environments such as
the given liquid or gas. space stations
Pressure Pressure sensor cause a reaction Can be used to detect if someone is waiting
when a certain amount of weight or for a door to open.
pressure is applied to them
Speed Displays the speed of a given object In speed cameras to detect the speed of a
car.
87
IBComputerScience - Textbook
Once you have a knowledge of sensors you can apply them to real situations to try and
understand what is happening in a given system. Examples of this are given below:
The sensor on the train door will stop the door from closing
on the people entering the door. If there was no sensor
people would be hurt if they tried to enter the train when the
doors are closing. Or they would get stuck and it could
cause an accident. It is likely that the door uses a proximity
sensor. If people are within the proximity of the open door
it will not close. Pressure sensors would not work as it is
Train doors
Blog.sbb.ch
Making a System
88
IBComputerScience - Textbook
Thankfully we don’t need to know that we just need to know about sampling and what
happens with the data.
Sampling
Sampling refers to how we gather data from analogue signals. The computer takes
snapshots of the data several thousand times per second using an analogue to digital
convertor. These snapshots are then fed into the processor as digital data.
Once the digital signal reaches the processor an algorithm is followed to make decisions
based on the data given. For example if a temperature of 20 degrees is read into the system
the processor then has to decide whether to take action or not. If the algorithm decides
that an action needs to happen then this is passed onto the transducer. The transducer
activates the correct mechanical system and the process is completed.
Sensor A/D
Convertor Processor
tranducer
89
IBComputerScience - Textbook
A worked example of a green house is shown below. If the greenhouse gets too hot then
the windows will be opened and the heaters switched off. If the greenhouse gets too cold
the heaters will be turned on and the windows closed. Otherwise nothing happens.
Embedded Systems
The above items all have one thing in common. They all contain embedded systems. These
are dedicated operating systems with specialized instruction sets that help the systems use
sensors to make decisions.
90
IBComputerScience - Textbook
In this course you need to be able to discuss embedded systems within items. Some
examples are shown below:
Dishwasher:
Inputs: Multiple inputs; Cycle, time, sensor for shutting of
hatch
Transformation: Transformed into 1s and 0s so that the
system can read it and apply the best fit.
Processing: Takes in the 1s and 0s and then applies and
orders the system what to do based on what the input is.
Transducing: Activates the appropriate cycle and sets the
time for this cycle
Output: The system starts to run once the hatch is shut
www.pixabay.com
Car
Inputs: Press the acceleration pedal
Transformation: Transforms the amount of pressure
put onto the pedals into binary code (1 and 0).
Processing: The system reads the binary and detects
how much the car needs to accelerate by.
Transducing: More fuel is put into the engine and all
the required settings are adjusted.
www.pixabay.com Output: The engine goes faster which makes the car
accelerate.
Vacuum:
Inputs: time, power, sensor feedback
Transformation: Data is transformed to binary so that the computer can
understand it and perform the task
Processing: The 1s and 0s are transformed into commands that are sent
to the system
Transducing: The power is set with a certain input time, when it is near
a wall, it turns
Output: The vacuum starts going around as soon as it is activated by the
user
www.pixabay.com
91
IBComputerScience - Textbook
Loop Systems
An open loop system is a system that does not make use of feedback. For example tumble
dryers. If you put clothes into a tumble dryer it will continue to dry until the timer stops.
There will be no feedback about the dryness of the clothes at any point.
INPUT time
Time on controller set
Timer started
Element heated
OUTPUT clothes
There is no comparison between the values that come out of the system and what
we want to come out for the system.
There is no self regulation of the system
If there is a problem / disturbance in the system then the control can not process
this, it must be dealt with manually
Therefore user of open looped system must be very skilled as they have to understand how
to optimize the system manually to get the best results.
- light switches
- toasters
- sinks
- hobs
- remote controls
- clothes dryers
- volume on stereos
92
IBComputerScience - Textbook
A closed loop system is a system which makes use of feedback. If we use the same example
before, that of the tumble dryer. If you select the dryness level that you want and there is a
sensor in the system then the system will keep drying until the clothes reach the desired
level of dryness.
In Pseudocode
INPUT dryness
The users of the system have no requirement to be as skilled as the sensors and feedback do
most of the work. It is the programmers of the system who are responsible for optimizing
performance not the operators of the system.
Closed Loop Systems are good for the following:
- Heating systems
- Refrigerators
- Cookers
- Air conditioning systems
- ABS systems in cars
- Auto pilot
93
IBComputerScience - Textbook
All systems that use sensors require control panels that can be used to control the input and
outputs of the system. The control panels are used to set the variables, the actions that
should occur when certain conditions are met and changes to the system.
Centralized - in a centralized system all of the rooms/areas are controlled from one panel.
The advantages of this are that you only have to input the variables once, the costs are
lower as you only have one control panel to set up. A disadvantage to having a centralized
system is that if the system breaks you lose functionality to all rooms/areas and each room
has to have the same variables you can not set different variables for each item.
Distributed - in distributed systems all of the rooms/areas have their own control panels.
The advantages of this are that you can set different variables for each area. If a system
breaks you still have several other systems to call upon. The disadvantages are that it is
more expensive to set up as you have more equipment to buy and it takes longer to set up
the different areas.
Autonomous Agents
“Intelligent agents are software entities that carry out some set of operations on behalf of a
user or another program with some degree of independence or autonomy, and in so doing,
employ some knowledge or representation of the user's goals or desires”
(Wikipedia)
Autonomous agents in control systems are entities that carry out actions based on the
feedback of the sensors. They do this without interference of the end user. The only action
the end user has is to set the initial variables.
In this course you need to be able to for any given scenario discuss the advantages and
disadvantages of using autonomous agents as well as the connection media required. One
example that was used in the past was that of a farm.
Farm Example:
As you can see the farm has many different animals and many different buildings. There will
be a system in place to heat / cool the barns as necessary and also to identify when animals
need attention.
- Evaluate the use of both a centralized and a distributed system and make a decision
about which would be best for the farm
- Discuss the welfare of the animals with regard to using sensors to make decisions
- How could a mobile control panel be useful to the farmer?
94
IBComputerScience - Textbook
In the farm it is clear there are several types of animals who need looking after. If a
centralized system was used the farmer could control all the barns from one system,
however, it would mean that all animals would need the same conditions. In a distributed
system each barn would be able to have different conditions, as this is a farm and it is likely
the animals would need different conditions even though it is more expensive and more
tricky to manage I would recommend a distributed system
Using sensors to manage the animals could be useful, sensors would quickly be able to tell if
the barn was too hot or too cold and adjust the machinery in the barn accordingly. If there
were sensors alerts could be sent to the farmer if food or drink needed replenished.
The mobile control panel could be useful to the farmer as the if they are away from the main
area they still have access to the controls. This means the are able to respond to any alerts
immediately.
95
IBComputerScience - Textbook
Utilitarianism
“It’s too dangerous. You can’t have a person driving a two ton death machine.”
Elon Musk (March 2015)
It important as technology is progressing to think about what Musk claims. He claims that cars will
become so safe that it will be difficult to get insurance if you drive your car but this means that
algorithms will have to be written to drive the car and will have to be written to mimic the instincts of
drivers so where does that lead us?
Cornell university have been conducting a survey of the general public with the vision that cars
should be programmed to act in the manner that people expect them to. Which leads to the
following question:
Specifically in the following situations do we injure / possibly kill one person over the group of
people, how do we decide which life is more important?
96
IBComputerScience - Textbook
Check
Time
Check
Check Temp
Temp
97
IBComputerScience - Textbook
1a: Identify one situation in which the system should respond to:
b: State three hardware devices that are needed to process and capture the data.
d: The company currently uses a manual system for the heating system. Employees take
the temperature of each tank using a thermometer and then manually carry out the
processes required to regulate the temperature.
e: The company decides to move to a computerized system. This will allow them to control
the temperature on a more frequent basis as staff are often too busy to be effect. They are
unsure whether to have all 30 tanks on one system or have separate systems. Evaluate the
decision of having all 30 tanks on separate systems and make a recommendation to the
company.
2: In all areas of the home you can find system that are controlled by technology.
For one of the systems identified above identify two sensors that are required.
Explain what would happen in one of your identified system if there were no feedback.
98
IBComputerScience - Textbook
What is Programming?
Computers are essential dumb machines, they have to be told very carefully and very simply
what to do. An example of this would be when trying to teach a small child how to shower,
the conversation might be similar to the following:
1: walk into the bathroom
2: turn the shower on
3: adjust the temperature of the shower
4: stand under the shower
5: shampoo your hair etc…
But what happened? The child still has their clothes on!
That’s because we didn’t say remove your clothes at any point in the instructions. As with
small children you can not make any assumptions with computers you must make
everything clear.
Fundamentally computers can only carry out four functions. They can carry out simple
calculations (add, subtract, multiply and divide), they can compare data, they can retrieve
data and they can store data. Combining these fundamental operations allow us to
complete more complex tasks. A simple example of a compound operation is find the
largest. To complete this task the processor inside the computer needs to perform the
following tasks:
99
IBComputerScience - Textbook
7: retrieve largest
Through the use of compound operations we can create complex programs for use. In order
to create complex programs we use high level languages. Software instructions that allow us
to create programs. There are two types of programming language types. General purpose
programming languages and specialist programming languages.
Translation
There are three levels of computer languages and these are shown in the following table:
100
IBComputerScience - Textbook
High level languages need to be translated into programs the computer understands. This is
done in two ways.
Stage One: During development a translator is used to translate the program line by line
into machine code. Similar to when speeches are being translated in real time between two
languages. This can take a long time however the advantage of this process is errors can be
pinpointed and fixed easily by the programmer. To run a program using a translator you
need the source code and the debugging program.
Stage Two: After development a compiler is used, it changes the program from a high level
language and into machine code. This is done all at the same time, the same as if a person
translated a whole document using an online translate tool. It can work without using the
translator however it is very difficult to find mistakes. The compiled program is then an
executable file that can be used stand alone on a machine.
101
IBComputerScience - Textbook
Object Orientation
What is it?
In the past programs were written procedurally the computer viewed and executed the code
line by line, as programs became more complex this led to very long and complicated
programs. The result is now we have object orientated programming, each object is a
separate item which can be manipulated with its own behaviours. This allows us to make
complex programs easier.
An easy way to think about object orientation is a class is a noun and the method is the verb.
An object is like a living creature is has knowledge inside of them telling them how to do
things, they can remember things. Instead of interacting with them on a low level we
interact at a high / abstract level.
Example: If I am your air ticket object and you send me the message “buy me return tickets
to Rome this weekend”. I know where to look for cheap tickets, I know where Rome is and
how to get them. I buy your tickets, I print them off and I hand them to you. You have no
idea how I did it, however I have your tickets.
This is how objects and methods work, I can ask my object to do things, I don’t know how it
does these things but it does and the result is I get what I want.
What is a class?
We start any program with a set of classes. Classes are the blue prints for the objects we
create. Our program will always have a main class which is the control class for the program
and will most likely have at least one other class which will be used to create an object we
can manipulate.
One example of a class is a bicycle class. Imagine we wanted to store details about all the
bikes stored in a school. We would need a bike class that stores our knowledge of what a
bike should have and do. We know that they speed up and slow down, this would be
represented in Java using the following code:
gear = startGear;
speed = startSpeed;
}
102
IBComputerScience - Textbook
gear = newGear;
}
speed = speed – 1;
}
public void speedUp(){
speed = speed + 1;
}
}
At the moment our bike will do nothing as it is only an idea. Its only when we create an
instance of our bike with a start speed and a starting gear do we have something tangible we
can manipulate. To do this we have to call the special constructor method from the method
that is running our program. The constructor method is the methods that “constructs” the
object. In Java it looks similar to this:
3: Using the example above explain what the numbers between the ( ) are.
4: Think about a dog, what instance variables and methods would you need to create a dog?
Critters are little creatures that can be adopted and grown into pets. They are brightly
coloured creatures and each has a special power. The eat and drink like regular animals but
they exercise by flying. An example critter is shown below:
Name: Katie
Colour: Blue
Special Power: Invisibility
Eats: popcorn
Drinks: Mountain Water
Implement the Critter class in java and use a main method test class to check it works.
103
IBComputerScience - Textbook
Inheritance
It is clear from the above example that although classes are very useful they do not allow us
to specialise items in the way that we would like. An example would be there is no such
thing as a bicycle, there are several different types of bicycle you could have a road bike, a
mountain bike and a racing bike. Although they have similar properties they also have very
different properties. Java allows us to deal with this using a concept called inheritance. We
can put all of the common variables and methods for each class in a special class called a
super class. Variables and methods specific to each type of item can be placed in the
subclasses. The advantages of this are:
- you have to use both the super class and sub classes in any code
- it take additional time and effort to use inheritance
- maintanence is harder as you need to change the sub class and the superclass
- if you delete the superclass the subclass will fail.
First of all we would have our superclass with the common methods for bikes (speed up,
slow down and change gear)
104
IBComputerScience - Textbook
}
We would then need to have additional classes for each of the specialized bikes, these are
called sub classes.
105
IBComputerScience - Textbook
When planning our bike program we would create a class diagram, this would look similar to
the following:
Bicycle
Int gear
Int speed
setGear()
applyBrake()
speedup()
Is_a Is_a
Is_a
Person
String fName
String sName
Int Age
getFirstName()
getSecondName
getAge()
Student Teacher
getGrade getDept()
getProgram getClass()
changeProgram(
int x)
106
IBComputerScience - Textbook
Parameters
Parameters are used to pass information between the classes used in a program. Without
the use of parameters our programs would all have to be in the one class which defeats the
purpose of object orientated programming. Parameters allow us to pass information
between the methods in our classes. We use parameters in several ways throughout the
programming process.
Formal Parameters – the information and type of information the method expects. These
are declared in the method signature e.g.:
This method when called is
public void speedUp(int increment)
expecting an integer value in the
brackets
Actual Parameters – when you call the method, the actual parameters are the information
you send into the method to make it work e.g.:
This is the data being sent in the
myBike.speedUp(10) method. The method will then
do something with this data. It
could also be a variable
One of the first ways we use parameters is with constructor methods. The parameters in
between the brackets are the initial values we are using to create our object. It is important
in all cases we send the information in the correct order, otherwise it will not work correctly.
Using the example above we would call our constructor (to make our bike) with the
following declaration:
This line of code will make a new mountain bike object that we can manipulate with a start
suspension of 2, a start gear of 1 and a start speed of 10. We can adjust these numbers
using methods, sometimes methods use parameters for example we can speed up the
mountain bike using the following method:
myMountainBike.speedUp(10);
we are passing in the actual parameter of 10, we know therefore that when we invoke this
message the speed of the bike is increased by 10.
107
IBComputerScience - Textbook
Write a simple calculator program – when run it should add, subtract, divide and
multiply two numbers together. It should have a calculator class where all the hard
work is completed and a main method class to run the program.
Ext. use IF statements and user input to make this a useful calculator
Variables
Variables are used to store data while the program is running, for example it might store
user input which is then used in an IF statement. It could be used to store the result of a
calculation which is them displayed to the user. It is important to remember that the value
in our variables will only be held while the program is running.
Variable Types
There are two types of variables primitives and objects. Primitive data types can only store
data there are no methods associated with them e.g. integer, double, character. Object data
types have their own methods associated with them e.g. the string object has a length,
charAt etc. methods. When you create your own classes you are creating types of object
variables that can be used by programs.
108
IBComputerScience - Textbook
Declaring Variables
Before a variable can be used it has to be declared, this means telling the program that you
would like to set aside an area in memory that you will refer to with a set name, and the
data type you are going to store in it. Sometimes you can set an initial starting value to the
variable.
String username;
Double cost = 5.99;
Int age = 15;
Boolean answer;
Double newBalance = cost * 0.1;
Cow myCow = new Cow(12,1)
Strings
Strings are important variable types for any program. They are a collection of alphanumeric
characters. As Strings are object variable types they have several methods available to use
with them. The Methods available are:
Scope of Variables
Depending on where the variable is declared, depends where the value can be seen and
used in the program.
Public Account () {
These are instance variables required
Private double balance; throughout the class
Private double interest_rate;
return balance;
}
109
IBComputerScience - Textbook
Account, balance, interest_rate, getInterestBalance() etc. are all identifiers. Identifiers are
the names of the classes, methods, variables in java. It is how they identify themselves in
the program.
Constant Variables
Constants are variables that do not change their value throughout the program. There value
should be set at the time of creation. For example if you were creating a program that was
calculating the VAT of an item you know that it is unlikely the rate of VAT will change.
Therefore you would set it as a constant value. Naming conventions in Java show constant
variables in capital letters. E.g.
Casting
Sometimes we have to force our variable into a different variable type this is achieved
through casting. For example people can not take 0.25 out of their bank account therefore
the amount the are withdrawing would be rounded up to an integer. This is achieved using
the following.
(int) (balance * 100) – this forces the result to be an integer
rather than a double
Relational operators are usually used in IF statements to help make a decision. These
operators only work with primitive data types:
110
IBComputerScience - Textbook
The following relational operators are very useful for comparing Strings.
Boolean Operators
These are useful for ending loops && means and so both conditions have to be met. ||
means of, either condition must be met to end the loop. Examples of use are shown below:
2: Create a simple program that will ask for my first name and second name. It should then
- take the first 3 letters of my first name and concatenate them into the last 3 letters
of my surname and store and print this in a new username variable.
111
IBComputerScience - Textbook
Methods
Methods are the pieces of code that will allow are programs to function in a useful manner.
Without methods our programs will perform nothing of interest. The syntax of methods is
very strict, if you do not follow the syntax correctly then you will experience problems with
your programming.
Method Signatures
Methods signatures are very useful as they tell us what the method expects as parameters
and what the return value will be.
e.g.
Public double calculateInterest(double interest_rate, double
amount_saved)
it would be called from another method using a line of code similar to the following:
myAccount.calculateInterest(interest, savings);
Return values
The return value is the value that is sent back to the method that called the method. The
type of data being returned must be declared in the method declaration. Examples are
shown below:
112
IBComputerScience - Textbook
Constructor Methods
When we create a class we have a “blueprint” for an object but the object does not actually
exist. To construct the object we need to have a constructor method within the class.
The method that construct the Account object my account is the constructor method it looks
like:
Balance = startBalance
Accessor Methods
When using encapsulation all instance variables should be set as private, this means they
cannot be “seen” by other objects. However not being able to see the contents of the
variables would render most of our programs useless. Therefore accessor methods are
create which allow private variables to be seen by other objects. Below is some examples of
accessor methods.
username = person.getFirstName()
Mutator Methods
When using encapsulation all instance variables are private therefore we can not access
them outside of the object. However in most cases we need to be able to set or change the
contents of the variables inside the object. This is when a mutator method is used.
Inside the person class the code would look like this:
In the object using the person class the code would look like this:
Person.setFirstName(iniFirstName);
113
IBComputerScience - Textbook
Public/private and protected modifiers determine which object can see the methods of a
class.
This is shown in the following table:
Public
When you declare a method as public it can be seen by all objects everywhere and can be
used by all objects everywhere.
Private
Private methods can only be seen inside the class in which they are declared.
Protected
Protected methods can be seen by their class, the package they are declared in and their
subclasses.
Extends
Extends is used with inheritance to show that the object inherits the methods from the
super class as well as having its own methods.
Static
Using static means you do not have to create an instance of something as it is available for
use in the class without having to explicitly declaring it.
Example:
instead of saying
a.getAccNumber()
114
IBComputerScience - Textbook
2: What information can you gain from a method signature? How will this help you in your
programming?
115
IBComputerScience - Textbook
Encapsulation
Encapsulation is an essential concept of object orientated program. It means that all of the
components of the class are kept together in one place. This allows the class to become a
single entity that can be used in other programs.
For programming it is also very useful as you can use the premade classes such as String,
Math, Scanner etc. without understanding how they work. We can import them make use
of their methods by providing the correct parameter values and understanding the return
value we will get but we don’t understand the inner works.
116
IBComputerScience - Textbook
Instance variables should be declared as private as this ensures they can not be accidently
changed from outside the class. They can only be purposefully changed using the correct
mutator method.
The correct method declarations should be used, only methods that can be used outside the
class should be public e.g. mutator and accessor methods, the rest should be private.
Public Account () {
Balance = startBalance()
Pixabay.com
117
IBComputerScience - Textbook
Libraries
Libraries make use of encapsulation and are collections of classes that can be reused by
other classes throughout the program. They have several advantages:
The Math class is one of the most useful libraries as it has lots of preprogrammed maths
functions that can be used. The only thing you need to know in order to use it is the
method name and the parameter required.
The Java API page has a list of all of the library classes that are available for use in Java, this
can save a lot of time and energy. An example of a program that uses libraries is shown
below. In this program it will roll the dice until snake eyes (two ones) are thrown. It will
then report the number of rolls taken to reach this.
do {
dice.roll();
System.out.println("The dice come up " + dice.getDie1()
118
IBComputerScience - Textbook
}
Check your Understanding
1: Implement the above snakes eyes program in Java. How does this
program make use of both libraries and encapsulation?
Pixabay.org
Pixabay.org
119
IBComputerScience - Textbook
IF Statements
IF statements are very important in programming all programs need to be able to make
decisions.
The statements follow a similar pattern
IF (condition) then
Do this instruction
IF (condition) then
Do this instruction
ELSE
Do this instruction or an error message
An example of an IF statement would be to modify the main method to ask the user which
bike they would like to purchase / use and then create a bike based on their choice.
120
IBComputerScience - Textbook
This code
get the info
from the
user
The if statement
what to do is in the
{}
121
IBComputerScience - Textbook
2: Another game that can be made with IF statements is a text based adventure game. In
the 1990’s they tried to make a virtual reality show called ‘Knightmare’, we are going to
make an even worse version.
How it works:
1: Give the user a question and 2 or 3 options. E.g. “You walk into the banquet hall and you
are faced with a talking wall. What do you do 1 – run the other way, 2 – talk back with an
attitude, or 3 – answer his riddles in a suave style. “
You then use the answer and use if statements to decide what happens next.
e.g. IF input == 1
122
IBComputerScience - Textbook
print “you ran the other way what are you a chicken? What do ye now? 1 –
the door is locked scream and hope someone rescues you, 2 – pick up the
cement you see in the corner?”
if (choice == 1)
print “no one came its over”
else if (choice == 2)
print “ok walk to the wall, what happens next? 1 – the wall
charms you? 2 – you cement up his face
if……..
Else if (choice == 2) // this refers back to the original question
As you can see there are a lot of nested ifs but used well could create good game.
Loops
Loops as the name suggests repeat sections of code over and over until a condition has been
met. There are two types of that exist in java.
Conditional Loops:
Conditional loops repeat sections until a condition is met. For example it might repeat until
someone enters the correct password or the person has had three attempts. They can be
used to repeat a program until the user presses quit. Conditional loops will repeat an
unknown number times. The following is an example of a conditional loop:
123
IBComputerScience - Textbook
This is the
condition that
must be met to
end the loop. The
code between the
do and while will
repeat
It is important when using conditional loops that you get the end condition correct
otherwise you will enter an infinite loop that would eventually crash the computer!
124
IBComputerScience - Textbook
And example of someone getting in an infinite loop is demonstrated quite nicely in the big
bang theory here:
https://www.youtube.com/watch?v=k0xgjUhEG3U
Fixed Loops:
Fixed loops will repeat a section of code a set number of times. For example if we need ten
words we would use a fixed loop to ask the user to enter a word ten times. Fixed loops will
always repeat a set number times.
125
IBComputerScience - Textbook
The 21 sticks game. In this game the pile starts with 21 sticks. Each person removes one or
two sticks. The loser is the person who runs out of sticks.
1: Declare variables
no_of_sticks = 21
userOneInput
userTwoInput
sticksLeft = true
2: Start loop
2.1 prompt user one for entry
Pixabay.com
126
IBComputerScience - Textbook
2.2. IF input == 1
no _ of _ sticks = no _ of _ sticks – 1
check no_of_sticks
ELSE
No_of_sticks = no_of_sticks – 2
Check no_of_sticks
2.3 repeat above of user two
127
IBComputerScience - Textbook
Arrays
If we were to store the grade of everyone in a grade 9 maths class we would required 15 –
25 variables based on the number of students in the class. E.g.
int classMember1;
int classMember2;
int classMember3;
This is not very efficient, it would mean hours of extra coding and the variables could get
complicated.
To solve this problem there are variables called arrays. Arrays allow many variables to be
stored under the same name. To think about it in a non programming way I would think of it
as a named shelf that you can store information on. Arrays allow us to store data in a
streamlined way and because they are objects they have associated methods we can use to
make things easier.
classMarks Array
classMarks[0]
73
64 classMarks[1]
classMarks[2]
77
98 classMarks[3]
64 classMarks[4]
56 classMarks[5]
128
IBComputerScience - Textbook
Declaring Arrays
The first way to declare the array is to name the array and then tell the program what data
you will be storing in the array straight away.
This is useful if you know the data at the time of programming however, it does not allow for
any interactivity from the user. The second and more common way to declare an array
which allows for interaction from the user is to use the size declaration. We declare an array
and say how many spaces we want to keep free to use, we can then fill these at a later date.
The above code creates an integer array with 10 spaces we can then use a for loop to fill
these spaces when we have the data. It is important to note that once declared an array
can not change size.
All data can be stored in arrays, Arrays can be set to store primitive values such as integers,
doubles, Booleans etc. or they can be used to store any class that you create or currently
exists in the java API e.g. Strings.
An example of a program using an array is shown below. It allows the user to enter the
grades for the students in a class and then calculate the average grade.
int myvalue;
myvalue = input.nextInt();
classGrades[i]=myvalue;
}
for (int x = 0; x < classGrades.length;x++){
129
IBComputerScience - Textbook
3: Random haiku generator – using two arrays one with 3 syllable sentences and one with 7
syllable sentences generate haikus.
130
IBComputerScience - Textbook
Arrays of Classes
Arrays of primitive data types although useful in certain cases, such as calculating grade
averages, can be quite limiting in a real world program. Similarly when we have been using
classes we have only created one instance of a class which is also incredibly limiting.
Wouldn’t it be good if we could combine several instances of a class and store them in an
array? Luckily Java allows us to create arrays of classes.
An example would be a group of students. It might be useful to store their first name, last
name, email, grade and then have an array of all the students in the class. In this case a
pupil class would be created and then an array of classes used to store the instances of the
classes.
class9J[]
pupil
fName
sName
grade
You can access each individual element in the classes using the code similar to the following:
131
IBComputerScience - Textbook
if you used an array of classes to store the data of the students in the class as described in
the arrays section, you could use the following code to find the average grade. You could
also add additional methods to find the student with the highest mark, students who are
getting low grades etc. This is shown in the program below.
132
IBComputerScience - Textbook
Standard Algorithms
As you have seen in the Array of classes program in the previous section, storing and
gathering information from an array is very useful. For some operations in the array there
are standard algorithms that you need to know. These are the accepted best practice ways
to carry out a set task.
Filling an Array
This code will fill an entire array at the same time. However this could be modified to add
your own code to get user input etc.
INITIALIZE total = 0
FOR each element in array
Total = total + array [current element]
Return total
double total = 0;
for (int i =0; i < array.length; i++){
total = total + array[i];
}
double average = total / array.length;
133
IBComputerScience - Textbook
Count Occurrences
Count the number of times a certain value appears in an array. The example below uses the
word “tree”.
INITIALIZE total = 0;
FOR each element in array
If (array [current value] = tree)
Total = total + 1
Return total
int total = 0;
for (int i = 0; i< array.length; i++){
if (array[i].equals(“tree”)){
total = total + 1;
}
}
134
IBComputerScience - Textbook
This algorithm will search an array for a value, if it finds the value it will return a true value.
This algorithm will search for a value in an array and return the position of the value in the
array if it is found in the array. The one problem with this code is if there is more than one
instance of the item then it will only report the position of the last time it appears.
In the programming folder there are partially completed java programs. Open them and
enter the code for the standard algorithm identified. There is pseudocode inside the class.
135
IBComputerScience - Textbook
While one dimensional arrays allow us to store a list of items under one variable name. Two
dimensional arrays allow us to store data in a matrix. One way to think about this is a table
filled with data.
So far what we know about arrays is that they allow us to store information under the same
variable name. We need to use loops in order to use array efficiently and they can be useful
for storing data in programs. For example an array of animals could be drawn as shown
below:
ANIMALS
[0] [1] [2] [3] [4] [5] [6]
The arrays we know could be considered as lines of data or lines of classes. However, there
is another type of array which is known as a two dimensional (2D) array. A 2D array allows
us to create a matrix or table that we can use to store data. The best way to show this is
using a game of noughts and crosses.
Other uses for 2D arrays could be keeping track of seats that are available on trains, planes,
concert halls etc. When data needs to be stored in a table form a 2D array is very useful.
136
IBComputerScience - Textbook
1: Create the following Noughts and Crosses program. This shows how Columns and Rows
are set out.
Public tictactow()
{
board = new String[ROWS][COLUMNS];
for (int i = 0; i < ROWS; i ++)
for (int j = 0; j < COLUMNS; j++)
board [i][j] = “ “ ;
}
public void set(int i, int j, string player)
{
if (board[i][j].equals(“ “)){
board[i][j] = player;
}
public String toString(){
String r = “ “;
For (int i = 0; i ++)
{
r = r + “|”;
for (int j = 0; j < COLUMNS; <j++)
r = r + board[i][j];
r = r + “|\n”;
}
return r;
}
}
Import java.util.Scanner;
Public tictactoeRunner
{
public static void main (String[] args){
While(!done)
{
System.out.print(game.toString());
137
IBComputerScience - Textbook
Imagine that the two dimensional array could be used to allocate seats on an airplane. It
would become quite a useful tool. Devise a program that will represent an aircraft as a two
dimensional array of classes, you can then use this two dimensional array to store passenger
details.
138
IBComputerScience - Textbook
Sorting Algorithms
Algorithm Efficiency
You need to know how the following algorithms operate and what their efficiency is,
however to start with we need to understand how the Big O notation quantifies algorithm
efficiency.
O(1) The algorithm uses the same amount of operations regardless of the size of the data
structure or input.
O(log n) The time taken to complete the algorithm increases slightly each time, however it is
not exponential or linear to the size of the input. If you imaging trees, half of the tree gets
removed each iteration of the algorithm.
O(n) the number of operations required to complete the task increases in direct proportion
to the size of the input
O(n^2) the time taken to complete the algorithm grows exponentially in proportion to the
size of the input
The algorithms you need to know for this course are: sequential search, binary search,
bubble sort and selection sort. The following section describes each algorithm with its
pseudocode, how it operates an its efficiency.
139
IBComputerScience - Textbook
The following array will be used to demonstrate how the algorithms work:
TEST_SCORES [10, 34, 11, 45, 67, 54, 40, 32, 9, 15]
140
IBComputerScience - Textbook
return mid
}
return not_found // value would be
inserted at index "low"
}
Algorithm: Bubble Sort
Pseudocode Description
For I = 1 to N - 1 The first and second item in the array are
For J = 1 to N - 1 compared, if the first is higher than the
If (A(J) > A(J + 1) second then they swap. The second and
Temp = A(J) third are then compared if the second is
A(J) = A(J + 1) higher than the third they are swapped. This
A(J + 1) = Temp continues until a lower value is found and it
End-If can not be swapped. The start of the array is
End-For then revisited until the array is in order.
End-For
Walk through of the algorithm
1st iteration of loop
10, 34, 11, 45, 67, 54, 40, 32, 9, 15
2nd iteration of loop
10, 11, 34, 45, 67, 54, 40, 32, 9, 15
3rd iteration of loop
10, 11, 34, 45, 54, 67, 40, 32, 9, 15
4th iteration of loop
10, 11, 34, 45, 54, 40, 67, 32, 9, 15
5th iteration of loop
10, 11, 34, 45, 54, 40, 32, 67, 9, 15
6th iteration of loop
10, 11, 34, 45, 54, 40, 32, 9, 67, 15
7th iteration of loop
10, 11, 34, 45, 54, 40, 32, 9, 15, 67
8th iteration of loop
10, 11, 34, 45, 40, 54, 32, 9, 15, 67
etc. until the array is sorted
141
IBComputerScience - Textbook
142
IBComputerScience - Textbook
TOK Thoughts
In Computer Organisation we will look more closely at how data is stored however in the past ASCII code
was used to store characters. ASCII allowed 128 characters including special characters to be stored in the
machine. As the use of computers became more global it was understood that 127 characters is not nearly
enough characters to store the character sets required, Unicode is now used which uses 16 or 32 bits to store
characters.
To what extent do you agree with this statement? Can you find evidence to support or disprove this
statement.
Legally programmers must abide by the intellectual property laws, which states that you may not use
another’s program without their permission. You must also when using open source code fully acknowledge
the original author of the code. However when producing a piece of code it is your responsibility to ensure it
works correctly.
With this in mind think about the following statement, do you agree or disagree with the statement. In the
commercial world to what extent is the statement true.
“Programmers should take full responsibility for their code, if there is a flaw in the code that is
exploited by malicious code/hackers, it is the programmer who is at fault”
143
IBComputerScience - Textbook
Additional Projects - SL
Instructions:
It is a well known fact that all super heroes have unique characteristics. The following flow
chart shows the unique character traits of each super hero. What you have to do is create a
program that will ask the user questions and depending on their answers show them which
super hero they should be and their characteristics.
Start loop
Get user input
If userInput = password
Display enter message
Found = true
End if
End loop when tries > 3 or found = true
Display failed message
Extension Task (higher level): create a password list in a text file. Compare the user input to
the text file. If the password appears in the field then allow access.
144
IBComputerScience - Textbook
Instructions:
Loop
Generate random firstname
Generate random surname
Display name
Until
User presses x
* note this program does make use of the random number generator which is part of the
maths class *
145
IBComputerScience - Textbook
Instructions
*Extension task – if you are HL you could use an array list and let the user store as many
items as they like. This could also be saved to file for use at a later date.*
146
IBComputerScience - Textbook
Recursion
“I like broccoli its recursive” – possibly the most geeky thing ever said about a vegetable but
I stand by my statement. A broccoli is an example of recursion occurring in nature. When
you have a broccoli it and break is down, it holds the same shape getting smaller and smaller
until it gets too small to see.
This is a larger form When broken down Broken down further In a smaller form it is
of broccoli, it looks the same still the same still the same.
Itcuties.com 27/5/14
Another form of natural recursion you may be familiar with is
when you look in the mirror with another mirror and the image
seems to never end. Or there are a few examples with art and
album covers.
147
IBComputerScience - Textbook
Very simply put recursive methods are methods that call themselves with modified
parameters until they reach their base case.
Advantages of using recursion are that the solutions tend to be shorter and less code
intensive than iterative solutions however they are very memory intensive and can take a lot
of processing power. As you will find out when we complete the following tasks.
Fibonacci numbers are one of the most common algorithms for demonstrating recursion.
Fibonacci numbers are as follows:
F(1) = 1
F(2) = 1
F(n) = F(n-1) + F(n-2)
If you are mathematically challenge like me, in Fibonacci numbers the current number is the
sum of the previous two numbers. Therefore the Fibonacci sequence is as follows:
Towers of Hanoi
One of the most famous recursive problems is the “Towers Of Hanoi”. The Mayans had a
belief that if this game was solved with 64 discs the world would end. Why did they think
this? And how did technological advancement start to spoil indigenous beliefs? (TOK)
148
IBComputerScience - Textbook
You may have played it before or studied it in Maths. In case you haven’t you will find it at
the following link:
http://www.mathsisfun.com/games/towerofhanoi.html
1. if n is 1 then return 1
end Hanoi
if (num == 1) {
// Base Case: Move 1 disk...
System.out.println("Move disk from " + from +
149
IBComputerScience - Textbook
tower.solveTower(); // C1
}
}
Mayans believed that if this problem could be solved with 64 discs the world would end. Using
technology we have solved the problem it would take 18,446,744,073,709,551,615 moves. With
this in mind is technology ruining indigenous knowledge?
150
IBComputerScience - Textbook
So far in this course you have used arrays of classes to store the data in use. Although they
have been effective for the programs you have written so far, there are several limitations to
arrays. One of the main disadvantages is that you have to declare the size of the array at the
time of running the program. This is a problem because how do you know how much data
someone wants to add? Also this means that this section of memory will be permanently
blocked off for the array, what happens if you only use 10% of it? Searching algorithms and
sorting algorithms would be hideously inefficient and you would be wasting lots of memory
for no reason.
The alternative – the abstract data structure grows and shrinks to meet the demands of the
program. They also have libraries of methods associated with them so we can write more
effective programs very quickly.
Memory ineffective as
Storing more space
Than necessary
151
IBComputerScience - Textbook
One of the Advanced Data Structures you need to know about it an Array list. An array list
has similar properties to arrays however, there size does not have to be declared at runtime.
Also Array lists only store objects. If you want to store primitive data types in Java using an
array list you need to use the following “cheats”. Byte – Byte, Boolean – Boolean, char –
Character, double – Double, float – Float, long – Long, short – Short.
Methods that you will find useful when using Array Lists:
Method Action
ArrayList<pupils> myClass = This code constructs an empty ArrayList that
new ArrayList <pupils>(); will hold instances of the pupil class.
myClass.add(new Adds a new instance of pupil to the myClass
pupil(parameters)); array list (this will add the pupil to the end of
the list)
myClass.add(1, jess); Adds a new instance of the pupils class to
the array list at the index 1
myClass.remove(2); Will remove the instance of the object at
index 2
myClass.set(5, maya); Will replace the instance of the pupil object
at index number 5 with the pupil object
maya.
Pupil temp = Gets the last instance in the array list and
myClass.get(myClass.size()-1); stores it in a temporary pupil object.
This program sets up an array list of animals called theFarm then prints out all the cows on
the farm (simple but shows some useful methods).
152
IBComputerScience - Textbook
1: Implement the Farm program above and ensure you can get the addition function and
getting information from the array list working. You should also try to remove an item from
the array list.
2: Criminal Database:
Information
Pirate A – Name: Sandy McDonald Home Port: Lerwick Theft: Diamonds Date: 15 th
September
Pirate B – Name: Bob Walker Home Port: Invergordon Theft: Rum Date: 20th January
Pirate C – Name: Archie McDonald Home Port: Arran Theft: Rubies Date: 23rd May
Pirate D - Name: Steve Smith Home Port: South Shields Theft: Coal Date: 5th June
153
IBComputerScience - Textbook
This is an example of a double linked list, it contains pointers to the next object and pointers
to the previous object. This means the list can be traversed both ways. Unless we reach the
end of the list, we then have to point the list back to the start.
This is a circular linked list, it contains pointers back and forth as well as a pointer from the
last instance to the first instance in the list. It is the most comprehensive of all the linked
lists. However, in IB all you need to be able to code is the singular linked list.
154
IBComputerScience - Textbook
The advantages of linked lists are as well as being able to expand and contract as required,
searching and sorting does not require any physical movement of the objects just the file.
We don’t move the object just the pointers. The start pointer begins at bob and then moves
from there.
To add an instance break the pointer between two instances and add the object by
repointing them
Joe
To remove an instance break the pointer between the two instances and repoint the pointer
to the next in line
Every so often a garbage disposer (yes really) will come along and remove the objects that
have been discarded.
The good news is for this course you can use the LinkedList class in java. The previous
course you had to write them yourself! Methods you need to know are shown below as is
an example program. One important thing you need to know about linked lists would be
that they need a special helper method called an iterator to look through the list. I like to
think of an iterator as a cursor blinking before the current object that allows you to attack
the object but that might just be me.
155
IBComputerScience - Textbook
Method Action
LinkedList<pupils> myClass = This code constructs an empty LinkedList
new LinkedList <pupils>(); that will hold instances of the pupil class.
Add (E e) Add an instance of the object at the current
point in the linked list
Add (int index, E e) Add an instance of the object at a specified
index
AddFirst (E e) Will add an instance of the object to the
start of the linked list
AddLast (E e) Will add an instance of the object to the end
of the linked list
Clear() Will empty the list
Get (int index) Will return the object at a specified index
getFirst() will return the first object in the linked list
getLast() Will return the last object in the linked list
Remove() Will remove the current object in the list
Remove (int index) Will remove the object at a specified index
removeFirst() Will remove the first object in a list
removeLast() Will remove the last object in a list
Size() Will return the number of objects in the list
isEmpty() Will check if the list is empty
Import java.util.LinkedList;
Import java.util.ListIterator;
public class ListTester{
Iterator.remove();
For (String name: staff)
System.out.println(name + “ “);
System.out.println();
}}
156
IBComputerScience - Textbook
1: Implement the program above paying particular attention to how the iterator works.
On Facebook you constantly see updates such as “if I was a character from sesame street I
would be the Count” or “the city I should definitely live in is Paris”. In this task you are going
to create a program that tests how pirate someone is. In an advanced data structure you
will store questions. Each will have 4 possible choices and each choice has a points value.
You should keep a running total of the points and at the end depending on how many points
the person has display how pirate they are. (the question are on the next page)
Class Diagram:
Question
String Question
String answerA
String answerB
String answerC
String answerD
Int valueA
Int valueB
Int valueC
Int valued
getQuestion()
getAnswerA()
getAnswerB()
getAnswerC()
getAnswerD()
getValueA()
getValueB()
getValueC()
getValueD()
Program Outline:
157
IBComputerScience - Textbook
> 30
You are indeed a pirate, head out on your boat, raise your skull and crossbones and sail off
into the sunset.
<30 and >25
you are well on your way to becoming a pirate, with a bit more training you could be
spending your life at sea.
<25 and > 18
You are average, you dream of the sea but you are far too nice to live it. Maybe consider the
wanderlust lifestyle
<18
You couldn’t be less of a pirate if you tried and that is ok the world needs good people too!
158
IBComputerScience - Textbook
ADT – Stack
Item
Item added Item added removed
to stack to stack from stack
Stacks are an example of a first in last out (filo) system. The methods of the stack that you
need to know are:
The following is a program that makes use of a very simple string stack:
public static void main(String[] args) {
myStack.push("hello");
myStack.push("my name is: ");
myStack.push("Linz");
while(!myStack.isEmpty()){
String temp = myStack.pop();
System.out.println("the pushed item was: " + temp);
}}
159
IBComputerScience - Textbook
1: implement the program above and make sure you have a good understanding of what
the pop, push and peek functions do.
Program the stack to show why this is a good way to count daisies. E.g. it should allow the
users to enter as many daisies as they like then calculate the total.
160
IBComputerScience - Textbook
ADT – Queue
Queues are, as the name suggests, like a queue of items (escalator, check out queue, coin
dispense). You add to the queue at the bottom and remove from the top (metaphorically).
myQueue.addLast("how do like");
myQueue.addLast("them apples");
myQueue.addLast("bad movie");
myQueue.addLast("reference");
161
IBComputerScience - Textbook
System.out.println(myQueue.removeFirst());
myQueue.removeFirst();
myQueue.removeFirst();
System.out.println(myQueue.getFirst());
}
As you can see there is no queue class, therefore we have to use a linked list to create a
queue. The example above is the format the IB use for linked lists.
1: Implement the above linked list and check that you understand how it works. Be aware
that the main method only class the constructor of the “ExampleQueuev2” method. This is a
little different to how we have done things before.
2: A past paper question for this unit is shown below. Implement the queue suggested to
prove that the queue is the best data
structure for this. You will need a bus
class which stores the driver, the
route and the id number of the bus.
162
IBComputerScience - Textbook
A tree is a dynamic data structure which uses pointers to show where to get the next data
from. As trees are sorted, if a tree is balanced, it can be more efficient to search for data in
the tree.
Trees can be used for storing unique keys (references to files) so they can be retrieved
quickly. They can be used for searches when the search data is changing regularly.
Non binary trees – in a non binary the roots can have more than two children
Binary trees – in a binary tree the roots can have a maximum of two children
Lotus, Ford, Seat, Citroen, Vauxhall, Volkswagen, Porche, BMW, Dacia, Ferrari
163
IBComputerScience - Textbook
Each node can have two children (one left and one right), each child has one parent. The
nodes at the edge of the tree are called leaves. The starting node is the root and each whole
branch from a node is called a subtree.
BMW, Citroen, dacia, Ferrari, ford, lotus, Porsche, seat, Vauxhall, volkwagen
bmw, Ferrari, dacia, citreon, ford, Porsche, volkwagen, Vauxhall, seat, lotus
Lotus, Ford, Citroen, BMW, Dacia, Ferrari, Seat, Porsche, Vauxhall, Volkswagen
164
IBComputerScience - Textbook
165
IBComputerScience - Textbook
Tree Implementation
166
IBComputerScience - Textbook
Tree implementation is quite complex however here is code that will allow someone to add,
remove and search a tree.
167
IBComputerScience - Textbook
168
IBComputerScience - Textbook
169
IBComputerScience - Textbook
1: Implement the above tree and make sure you understand how it works.
2: If you are feeling brave, because the tree is abstract it will hold any object in the nodes.
Use the above code to store objects in a binary tree.
170
IBComputerScience - Textbook
Conventions
When developing code it is very rare you develop on your own. Therefore it is important
you follow certain conventions when coding. This will help to keep your code:
- readable so others can help / further develop it
- save money as people understand it quicker
So how do we use the conventions:
1: First of all at the start of your program have a long comment explaining the name of the
class, the author, the version, the date created and a description of what the class does
2: All Variables should have meaningful names i.e. the variable name should correspond to
what it stores
int total_value;
String first_Name;
Boolean game_End;
3: All methods should have meaningful names i.e. from the name of the methods you
should be able to understand what the method does
4: Constant variables (variables whose values do not change) should be all capitalized
int VAT_RATE = 0.20;
5: All pieces of code should be commented, this will allow people to fully understand what
is happening in the program.
// this method will total the values in the
// array and then divide by the length of the
// array to find the average and return as an int
6: Spacing should be used to indicate which lines of code are between which brackets.
Variables
Start of code
Loop
If statement
Code to execute if true
End if
End loop
End method
171
IBComputerScience - Textbook
The following program is a simple program that allows us to read from one file and add it
and some other data to a new file. You can find a video of it working on schoology.
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws
FileNotFoundException {
172
IBComputerScience - Textbook
Try and create the program in your own folder. Be careful the files must be in the same
folder as your Java folder.
So far we have looked at input and output based on the Fileinputstream and
PrintStreamWriter, these are fine when you would like to deal with text input and output
however it can also be useful to use the inputstream and outputstream methods. These
write the files using Bytes, a more complex way of storing the data.
Encryption has moved on in the past 2000 years however the first recorded use of
encryption was with Julius Caesar in the Roman times. He wrote letters and then moved the
letters forward by a set number in the alphabet. These were then decrypted using the
number by the recipient.
173
IBComputerScience - Textbook
This class ciphers the data from the in file that is passed in and writes it to the out file that is
passed in. there is two methods encryptStream which reads in the data byte by byte.
The encrypt method takes the byte and adds the selected amount to each byte
Main Method:
174
IBComputerScience - Textbook
In Caesars Cipher we looked at using the data stream tool to encrypt files (badly) we will
now take this the step further and look at how we can use this to store records in a file. We
can then search for these files and updates the.
Main Method:
175
IBComputerScience - Textbook
176
IBComputerScience - Textbook
177
IBComputerScience - Textbook
178
IBComputerScience - Textbook
In the Bank Account simulator we used the random access files to store and read from the
files however if we had many files this would slow down the process. It is better for us to
use an Array List (or similar) to store the changes temporary and then write them to file
when we finish with the program.
The code I have created shows you how to make use of this feature in a very simple
program. In order to be able to use this code in your internal assessments you must be able
to understand it.
You could once you modify the code read the file into a linked list or a binary tree.
The Pupil Class – very simple class which allows us to create and access pupil data
The only
interesting thing
is the addition of
serializable
The Main Method (some of this could be moved to another class similar to bank data)
179
IBComputerScience - Textbook
Create an array
list and read
from file if it
does not exist
make it
Offer options
Add a pupil to
the ARRAY LIST
code
Search and
display pupil
from
ARRAYLISTw
180
IBComputerScience - Textbook
Search and
remove person
from ARRAY LIST
Create the program above, this should now be used as a template for all future programs.
181
IBComputerScience - Textbook
Text based programs are very rarely acceptable anymore due to the nature of people using
computer systems. As computer systems are accessed by most people graphical user
interfaces have become indispensable. In this section you will use an online resource to
learn how to make a graphical user interface and then create your own quiz game.
This netbeans tutorial is very good at showing how to add functionality to a graphical user
interface. You should follow the tutorial and create your own “calculator”.
https://netbeans.org/kb/docs/java/gui-functionality.html
What essentially is happening is you have built an interface with a number of objects
attached to it. Each object is listened too by the object listener. Once the listener detects
your object has been clicked it carries out the event attached to the object.
The next stage is to take the information you now know and apply it to the quiz game. The
quiz game can be split into three stages:
First Stage:
Second Stage:
Third Stage:
Fourth Stage:
On the following page is some of the code you might find useful.
182
IBComputerScience - Textbook
One the page for question one you should initialize a variable for the score. There should
then be a Score initializing method which takes in the value of score from the previous
question and displays it on the screen. The code for this is shown in Figure 1 and 2 below.
Figure One
Figure Two
The following code shows the IF statement used to check if the answer is correct or not.
When the user presses the button on the question 1 screen the following IF statement is
carried out. The text from the box is read into a variable called Answer. If the answer
matches the correct answer a message is displayed, 1 is added to the current score and the
next question is shown. Otherwise, the correct answer is displayed and the next screen is
shown.
183
IBComputerScience - Textbook
Finally on the start screen we set the initial value for the score variable that will be passed
from frame to frame. Also when the button is clicked the quiz is started. When the exit
button is pressed the game ends.
184
IBComputerScience - Textbook
Additional Projects – HL
The following section contains ideas for additional projects. Some can only be implemented
if you have reached higher level but there are plenty for everyone to attempt. You should
attempt as many as you can in order to get your programming skills up to scratch. A
recommendation would be that you make a plan before you start to code.
This program will make use of files and Linked Lists to create a program which gives presents
the user with a selection of logic problems which they must answer before moving on. The
program will also store a list of users and their scores. It will save the users progress and
will display top scores when asked.
1: Display Menu
if user selects option 1
enter game
load game file
load player file
else if user selects option 2
display top scores and progress
load player file
else
exit
Game: Scorer
185
IBComputerScience - Textbook
Class Diagrams:
Task Player
Int lvlNumber String firstName
String intro String surname
String question Int score
String options Int levels
String correctAns Double percComplete
getNumber getName()
getIntro getFName()
getOption getScore()
getCorrectAns setScore()
setLevel()
setPercComp()
186
IBComputerScience - Textbook
Traveltrade.visitscotland.org
187
IBComputerScience - Textbook
188
IBComputerScience - Textbook
189
IBComputerScience - Textbook
190
IBComputerScience - Textbook
your game will allow you to enter the details of five horses
your game will allow five players to choose the first, second and third place horse
your game will allow the user to display a list of the horse names and odds
your game will randomly pick a first, second and third place horse
your game will print out what the five players have chosen and you manually check the
horses
191
IBComputerScience - Textbook
your game will include all functions of the simple game and the enhanced game
your game will calculate the winnings based on the bet the user placed and the odds the
horse had
your game will print out the winnings for each player
No Pair – the lowest hand, containing five separate cards that do not match up to create any
of the hands below.
One pair – two cards of the same value, for example two queens
Two pairs – two pairs e.g. two queens and two fives
Three of a kind – Three cards with the same value, for example three queens
Straight – five cards with consecutive values
Flush – five cards of the same suit
Full house – three of a kind and a pair
Four of a kind – four cards of the same value
Straight flush – A straight and a flush: Five cards with consecutive values of the same suit
Royal flush – the best possible hand in poker, A 10, jack, queen, king and ace all of the same
suit.
192
IBComputerScience - Textbook
The current system uses an online database which the company finds
clumsy and unnecessarily complex. As part of the programming team
which is developing the new system you have decided to use an Object –
Orientated programming (OOP) approach. The team will be divided into
sub groups.
Certain songs are classified as starSongs these songs make 25cents per
stream and can be set to have heavy rotation list (this means they get
played more often in a playlist set to random). Other songs are classified
as albumSongs these songs can not be set to heavy rotation and only make
15 cents per stream. Album songs can be set to skipped, so they do not
feature in any playlist.
No album can contain no more than 5 starSongs and no more than 15
albumSongs.
this.songTitle = title;
this.songPayment = pay;
this.songDuration = duration;
}
193
IBComputerScience - Textbook
Question 6 Continued:
title = theTitle;
this.addArtist(Artist);
}
theStars[stars] = x;
stars ++;
}
public void addAlbumTrack(song x){
theAlbumTracks[albums] = x;
albums ++;
}
public artist getArtist(){
return theArtist;
}
public void addArtist(artist x){
theArtist = x;
}
public void printAllAlbum(){
// code to be completed
}
a) Describe, with the aid of a UML diagram how the song class could make [4]
use of inheritance.
d) Describe the purpose of a constructor method, using the code to help you. [2]
194
IBComputerScience - Textbook
method.
7: Currently the software uses a linked list to store the list of songs the user places
into a playlist.
a) The playlist should be able to provide a shuffle function. Explain why using
an array would be beneficial when providing a shuffle feature. (You may [2]
use a diagram to illustrate)
195
IBComputerScience - Textbook
Why is it important?
The internal assessment is an individual project that is undertaken to demonstrate your
knowledge of computational thinking and system fundamentals. It is designed so you can
showcase the skills you have learned in these units.
At standard level the Internal assessment is worth 30% of your overall grade. At higher level
it is worth 20%. Both courses are expected to spend around 40 hours on it. You can use
more time but this will be outside of class and you should take care to ensure you do not
infringe any academic honesty agreements.
This document is designed to help you through the process. There are additional help forms
in the appendices should you need them.
What is it?
- Planning
- Solution Overview
- Development
- Functionality and extensibility of product
- Evaluation
196
IBComputerScience - Textbook
Choosing a topic
The project that you choose for you internal assessment MUST have an identified client.
Examples of this from previous years include:
The history department (middle school) – creating an app quiz to help students quickly test
their knowledge
IB economics students – creating a program to help them draw graphs quickly and easily
Assistant principal of the school – a program to keep a record of academic periods missed by
students due to absence
School secretary – create a program to identify free teachers in any given block and to assign
them cover lessons
It might be useful at this point to complete the “choosing a topic sheet”. This will help you
to identify your strengths as a programmer and identify a client.
Once you have identified possible projects complete the proposal sheet and hand it to your
supervisor. ONLY when your supervisor has agreed your topic and your identified client has
agreed to by your client can you proceed with your internal assessment.
TOK Links
Reasoning – you need to use reason as a way of knowing in order to reach a workable solution
for your client.
Hopefully your final solution can provided new knowledge to the classes shared knowledge.
197
IBComputerScience - Textbook
Academic Honesty
It is essential that all work completed in this internal assessment is your own. You can
reference other materials (all programmers do) and use your course notes to help you but
this must be clear in the text and in your bibliography. Students have been found cheating
in the past and dealt with the consequences.
Below is a list of behaviours which will be deemed as academic dishonesty with regards to
this piece of work. The list is not exhaustive, if in doubt ask!
1: Copying code from the Internet – you can be influenced by the code of others however it
must be made clear using comments in your code and appear in your bibliography.
2: Working with others – I know the standard of programming each of you have, it is fairly
clear when you are producing work that is not your own
3: Copying the exemplar – everyone has their own writing style mine has been provided as
an example use your own style to describe what you have done.
4: Getting help from others – it is an assessment others in the class can not help you, ask me
and I will help.
198
IBComputerScience - Textbook
You will find the planning documents in the appendices useful for this section.
199
IBComputerScience - Textbook
200
IBComputerScience - Textbook
Development - Marks
In this section you will:
- Identify techniques used to develop the product (algorithms, data structures etc.)
- Explain the techniques used
201
IBComputerScience - Textbook
you will find the “making the video” document at the back of this guide very helpful in this
section.
202
IBComputerScience - Textbook
Evaluation - Marks
In this section you need to have:
203
IBComputerScience - Textbook
204
IBComputerScience - Textbook
Proposal Form
Option 1
Client:
Problem:
Possible Solution:
Possible Techniques:
Option 2
Client:
Problem:
Possible Solution:
Possible Techniques:
205
IBComputerScience - Textbook
Client:
Problem:
Possible Solution:
Possible Techniques:
You must discuss your options with your supervisor and they will guide you how to make a
decision before moving on.
206
IBComputerScience - Textbook
Problem:
In this box write out the problem that you and your client have identified.
Client / Advisor:
In this box write out who your client and advisor will be
Rationale:
In this box write out the reason why you have chosen to create a solution, how will it help
your client, why are you using java?
Useful words: consult, discuss, clear, interview, client, java, advantages, data, cross platform
207
IBComputerScience - Textbook
Test Table
Description of the test here The reason why you are The expected outcome here
carrying out the test here
Think carefully:
This is a big part of computational thinking which the assessment is assessing. Show that
you have a clear idea of the logical steps you need to follow in order to complete the task.
Gantt Chart
Copy the stages you have in your list of tasks and paste them into the column.
You have 30 periods in class to do the IA, you may use additional periods but they must be in
one of the tech rooms supervised by a Technology Teacher. Who will then sign your sheet.
System Diagram
You must provide a diagram that shows how the classes interact with each other.
208
IBComputerScience - Textbook
UML Diagrams
It is essential you use class diagrams to show the instance variables and methods in your
class. Ideally your methods should show the return types and the parameters expected.
Explanation
In this section discuss why you have structured the program in this way and why you have
chosen these classes.
Record of Tasks
This is a requirement of the IB you must maintain a record of tasks to show what you were
doing and when. It should show logical progression in your programming, show consultation
with your client and show that you adapted to problems:
209
IBComputerScience - Textbook
This is your chance to SHOW the examiner what you have learned and how you have used it.
Use the word limit to explain the complexity in your program. Include explained extracts of
your code.
210
IBComputerScience - Textbook
there are examples of last years videos on schoology. I suggest you view them to
get an idea of what is required.
Plan your script carefully and watch the video back can the examiner fully
understand and appreciate your program based on what you have. If not go back
and ADD more information.
211
IBComputerScience - Textbook
Test Table
You must have conducted interviews etc. place these in the appendix
- discuss what your user thought was good
- discuss improvements your user thought were necessary
- discuss any problems your user may have had
- make reference to the relevant pages / areas in the appendices
Improvements
What do you think you could do to improve your program, if you had more time?
What do you think others with more programming skills could do to improve your program?
How would these improvements make the program better for the end user?
If your program was adopted by the end user then what could be added to make it more
useful, you do not need to be able to do these improvements
212
IBComputerScience - Textbook
Problem:
The languages department would like an interactive game that tested student vocabulary.
They would like to be able to add vocabulary to the program as the students learn it. This
would make the program more useful. At present there is not a product on the market that
supports this.
My client for this project will be Mr Smith the German Teacher in my school. My advisor will
be Ms Stephenson my Computer Science teacher.
Rationale:
After discussing the problem with Mr Smith it is clear that students need to be continuously
reminded of the vocabulary they have learned throughout the year. However exposing
students to too much vocabulary too quickly can put them off learning the language. He
would like a program that presents students with vocabulary tests based on what they
should know. Ideally if a student is happy with a word they should be able to mark it as
something they are happy with, if a student is unhappy it should be left unmarked. (see
appendix I for full interview transcript)
By putting the vocabulary in a computer program it will be easier for the students. The
vocabulary can not get lost. If the vocabulary is stored on the computer it is easy for the
teachers to add to the data. Due to the data being stored on the computer many people can
have access to it but the teacher only needs to change it once. It can also be customized for
different users.
I am using Java as it is cross platform therefore students with Macs can use the product as
can students with PC’s.
Success Criteria
213
IBComputerScience - Textbook
Testing Plan
Test Reasoning Expected Outcome
Test one: Run the program on This will test that the program runs The program will run
both an apple computer and a on both PC computers and mac on both machines
PC, ask the users to note any computers. Therefore any student without any
problems in a feedback form. can run the application on their significant errors.
computer.
Test Two: After discussing The program stores all the required The file can store
with Mr Smith it is thought vocabulary for a course. 500 entries which
that the ability to store 500 can be read into the
entries would be sufficient. Array List without an
issue.
Test three: I will ask Mr Smith The teachers should be able to add The teachers can add
and his colleagues in the vocabulary to the program. the vocabulary to
language B department to the program. Ideally
test the program. I will they will be able to
observe them adding add it without too
vocabulary. much additional
help.
Test Four: I will ask Mr Smith The teachers should be able to The teachers can
and his colleagues in the delete vocabulary from the delete vocabulary
language B department to program. from the program.
test the program. I will Ideally they will be
observe them deleting able to do this
vocabulary. without too much
additional help.
Test Five: I will gather a group I will get the students to complete a The students can
of test users. If a user questionnaire regarding usability. mark whether they
understands the vocabulary Also they will have to count how understand a word
then they can add a star. many times a word reappears and or not. They can also
When the program is run how many times a starred word use the program
there should be more appears. They can also use the easily
unstarred words appearing program easily.
than starred words.
Test Six: I will ask Mr Smith The program will allow two way The vocabulary is
and his colleagues to check translation accurate
the translations as they
appear in the file.
Test Seven: I will run the The program will allow two way The is two languages
program this will show the translation. on the screen but
translation between two the words mean the
languages. same.
214
IBComputerScience - Textbook
In order to complete the project I have identified the following tasks that required
completing:
215
IBComputerScience - Textbook
UML Diagrams
MainMethod
Question <> set
File inputFile
DisplayMenu()
sortAlpha()
displayDifficult()
displayHappy()
addWord()
removeWord()
runTest()
Question
String AWord
String Eword
String Defiinition
String diff
setAWord(String x)
getAWord()
setEWord(String x)
getEWord()
SetDef(String x)
GetDef()
SetDiff()
216
getDiff()
IBComputerScience - Textbook
PseudoCode
For the more complex methods, I have wrote out the pseudocode, this will allow me to plan
my methods carefully and will make coding easier.
Test Class
Main Class
Display menu
DO
PRINT options
cOption = user input
if option 1 - call sort method
217
IBComputerScience - Textbook
Add word
Remove word
Sort Data
218
IBComputerScience - Textbook
219
IBComputerScience - Textbook
Development Example
1: Techniques Used
a) User Interface
b) Variables
c) Loops
d) If Statements
e) Search Algorithm
f) Object Reader / Writer
A – User Interface
The user interface I have used is a text based user interface. The main reason for this is
because my client did not specify that it had to be a touch based system for a tablet. Also by
having a text based system the emphasis is on the vocabulary and not the graphics.
Figure 1
Figure 2
Figure 3
220
IBComputerScience - Textbook
Figure 4
Figure 5
Figure one shows the menu that is displayed to the user when they first run the program.
Figure two shows the test in action and how it deals with regular and non regular input (it
accepts the input but marks it wrong). Figure 3 shows the user input when setting up the
test, at the moment there is no way to stop users choosing more questions than there are
words. Figure 4 shows the listing of the dictionary and figure 5 shows how irregular input it
dealt with when loading a dictionary. At present the user can choose 1 to 3 however
anything over 3 will load the French dictionary. Unfortunately if the user chooses a letter or
symbol the program breaks.
– Variables
The variables I have used in my program vary between variables that would be easy to
maintain and variables that make sense only to me. In order to make this program more
maintainable I would probably change the variable names. I have when appropriate used a
mix of local and global variables. All the file names are appropriate.
– Loops
loops have been used throughout the program. The main loop is to continue the program
until the user presses exit.
Another while loop has been used as a search throughout the array list. For loops have been
used to loop repeat the question code for the number of questions the user has asked for.
221
IBComputerScience - Textbook
– If Statements
IF statements have been used throughout to show determine user choices. This is in the
start sections, and the menu section.
– Search Algorithm
Several search algorithms have been used throughout the program. For example in option 3
to search for the difficulty words (figure 6), to search for the word to be removed (figure 7).
To search for the word to add difficulty to (figure 8).
Figure 6
222
IBComputerScience - Textbook
Figure 7
Figure 8
I have used the object input stream and object output stream to read information into an
arraylist for manipulation and then it is saved back into the file when the program is closed.
223
IBComputerScience - Textbook
2: Testing Table
Testing Plan
Test Reasoning Expected Outcome Actual Outcome
Test one: Run the This will test that The program will run The program is stable
program on both an the program runs on both machines on both platforms.
apple computer and on both PC without any However, there are
a PC, ask the users computers and significant errors. problems with the
to note any mac computers. showing difficult words
problems in a Therefore any method, it generates
feedback form. student can run an error. This is
the application on something I would
their computer. need to fix.
Test Two: After The program The file can store 500 The program does
discussing with Mr stores all the entries which can be store 500 words.
Smith it is thought required read into the Array
that the ability to vocabulary for a List without an issue.
store 500 entries course.
would be sufficient.
Test three: I will ask The teachers The teachers can add The teachers can add
Mr Smith and his should be able to the vocabulary to the vocabulary easily after
colleagues in the add vocabulary to program. Ideally they being shown once how
language B the program. will be able to add it to add a word. They
department to test without too much found the user
the program. I will additional help. interface intuitive.
observe them
224
IBComputerScience - Textbook
adding vocabulary.
Test Four: I will ask The teachers The teachers can The teachers were able
Mr Smith and his should be able to delete vocabulary to delete the words
colleagues in the delete vocabulary from the program. easily after being
language B from the program. Ideally they will be shown the process
department to test able to do this once.
the program. I will without too much
observe them additional help.
deleting vocabulary.
Test Five: I will I will get the The students can The students were able
gather a group of students to mark whether they to use the program
test users. If a user complete a understand a word or easily (please see
understands the questionnaire not. They can also use questionnaire in
vocabulary then regarding the program easily appendix) however,
they can add a star. usability. Also there were some small
When the program they will have to problems with the
is run there should count how many display difficulty
be more unstarred times a word method.
words appearing reappears and
than starred words. how many times a
starred word
appears. They can
also use the
program easily.
Test Six: I will ask The program will The vocabulary is The vocabulary I have
Mr Smith and his allow two way accurate entered is accurate
colleagues to check translation however, there is no
the translations as way to change a word
they appear in the once it has been
file. added.
Test Seven: I will The program will The is two languages The translation is for
run the program this allow two way on the screen but the the correct word,
will show the translation. words mean the where there is no
translation between same. direct translation
two languages. between languages
another word has
been substituted and
noted in the
description.
To obtain my end user feedback I conducted an interview with Mr Smith (see appendix), I
conducted observations (see notes in appendix X), I also conducted questionnaires with
students (raw feedback can be found in appendix X). For the end user feedback the overall
response to the program was positive. Teachers would be able to use this product as an
additional tool to help students learn vocabulary, students found it useful and liked the
competitive element of the quiz. The teachers were not bothered about the text interface
as it allowed students to focus on the vocabulary however, the students would have
225
IBComputerScience - Textbook
preferred a graphical user interface. Both suggested that before it was used by all members
of the school it might be useful to solve the difficulty problem or remove that function as it
does not add much value to the program.
4: Improvements
The improvements I would make to this program based on my own thoughts and the end
user feedback would be:
1 - add a search function that would display a particular entry in the dictionary
2 – complete the sort function so students can see the data in alphabetical order either by
English word or acquisition word
3 it might be useful if the data was formatted better so it was easier to read
4 it might be good if there were a students version and a teacher version so students
could not add and remove words
I think it is a good start to this program, however, the following improvements could be
made. I would add a function to show specific entries. I would have a start menu that asked
if you were a student or a teacher and password protect the teacher area. These would be
easy additions to make to the program. As previously discussed the variables, method and
filenames are all logical and the code is well commented so this should be an easy job for
anyone to do.
To expand the program would be simple. Firstly more languages could be added for the
mother tongue students. There could be further games available for use. Verb tables could
also be added to help students with the correct verb endings. Finally there is no reason why
this program could stop at languages, science and maths could make use of the program by
having a scientific terms dictionary.
226
IBComputerScience - Textbook
Welcome to penguins with problems. Your task is to help Alfie the penguin get home. To
begin press 1, to see top scores press 2, to exit the game press 9 (also throughout)
Question 1
Alfie says “ Help me I am trapped in a dark and cold place and can’t seem to find a way out.”
To help alfie out answer the following:
Alfred and Roland have been hired to swo flower seeds. They split the field in half so they
can work independently. Alfred plows the field twice as fast as Roland. However Roland
sows the seeds three times faster. If sowing the plot earns 100 CHF how much should go to
Roland?
1 – 33
2 – 66
3 – 50 *
4 – 25
Correct! They sowed half the field each there for half the money each. Alfie says “great! I
can see a door.
Question 2
1–z
2–a
3–t*
4–e
Correct! The last letter of alphabet is T. Alfie has escaped the door but is confronted with a
slippery tunnel.
Question 3
Alfie says “I Can see a wooden ramp, maybe I can reach it”
Help Alfie reach the ramp by answering”
SOS! 15 people are trapped aboard a ship that’s going to sink in exactly 20 minutes. Their
only chance of survival is the five person life raft stowed on their vesser. To make matters
worse, the waters around the ship are teaming with man eating sharks. So swimming to
safety is out of the questions.
The nearest Island and back to the boat takes nine minutes of the raft. How many people
will see dry land.
227
IBComputerScience - Textbook
1–5
2 – 13 *
3 – 10
4 – 15
Correct! 13 people will make it. Alfie has reached the wooden walkway and is heading
towards the light.
Question 4
Alfie has made it outside but there is an artic storm. Without his puddle of penguins Alfie
has no chance of survival. Help Alfie out by solving the following question:
Ten candles stand burning in a dining room. A strong breeze blows in through an open
window extinguishes two of them. Checking back on the candles later, you see that one
more candle has gone out. To make sure no more flames go out, you shut the window.
Assuming the wind doesn’t extinguish anymore candles, how many candles do you have left
in the end.
1–4
2 – 10
3–7
4–3*
Question 5
Alfie is so cold his flippers no longer work so he needs to find some skis. If you answer the
following question he should be able to find some.
A jokerless deck of 52 cards sits on the table. The cards are shuffled thoroughly and divided
into two stacks of 26 cards labeled A and B. If you divided the cards as described above and
check the contents of each piles 1,000 times, how many times could you expect the number
of red cards in one pile match the number of black cards in the other.
1 – 1000 *
2 – 500
3 – 250
4 – 10
Question 6
A glass jar hold a single germ. After one minute, the germ into two germs. One minute after
that, the two germs each split again, forming a total of four germs. Continuing at this rate, a
228
IBComputerScience - Textbook
single germ can multiply to fill the whole jar in exactly one hour. Knowing this, how long in
minuters would it take to fill the jar if you have started with two germs?
1 – 59 *
2 – 60
3 – 61
4 – 62
Alfie has managed to get the right way up in the snow drift.
Question 7
Alfie is confused and disorientated the snow drift has not been good to him. He thinks he
can get out but he needs your help.
“You only have one match left. You want to light the room with an oil lamp, start a fire to
warm the room and heat your bath water. In order to complete all of the above actions,
which of these should you light first?
1 – the fire
2 – oil lamp
3 – the bath heater
4 – the match *
Question 8
Alfie is walking along the road and comes to a junction. He cant decide between going north,
west or east. Help Alfie make the correct decision by answering the following question.
“A father and son are chatting when the son poses the question “Dad I’m 22 now but
just ,how old are you? The father replies you wanna know how old your old man is, eh?
Hmm, well, I tell you what. I’m as old as your age, plus half my age. How old is the father.
1 – 44 *
2 – 55
3 – 66
4 – 36
Correct! Alfie turned west and managed to find the correct route.
question 9
It has been a while since Alfie ate, he reaches the sea and is wondering whether to take his
chances and find some fish. Give Alfie a helping hand through answering this question.
“Three identical – looking umbrellas are sitting upright in a stand. Assuming the owners
don’t check their umbrellas labels, what percentage chance is their that only two people will
walk off with their own umbrella?”
229
IBComputerScience - Textbook
1 – 0% *
2 – 33
3 – 66
4 – 100
Correct! Alfie decides to jump into the ocean to look for some tea.
Question 10
Whilst swimming in the ocean looking for tea Alfie spies a great white shark. Help Alfie
reach safety by solving the following equation.
8–6=2
8+6=2
7+6=?
1–5
2 – 11
3–1*
4 - 13
Alfie is back off track he has decided to try and following the sun to the west. Help Alfie find
the right track by answering the following question.
12
Alfie has reached a cliff, there is no way across help alfie come up with an inventive idea by
answering this question.
13
After making it down the cilff alfie is in a valley he thinks he sees someone in the distance.
Help him reach them with the following
14
Alfie calls his friend but they cant quite hear him, amplify alfies voice:
15:
Unfortunately Alfies shouts have attracted a seal. Help him escape by quickly answering the
following.
16
Alfie meets his friend he needs food he is exhausted.
230
IBComputerScience - Textbook
231