0% found this document useful (0 votes)
0 views

Computer Science Notes

The document discusses algorithms, their constructs, and methods of representation such as structured English, pseudocode, and flowcharts. It outlines the stages of producing an algorithm, the importance of variables, and the binary number system, including conversion techniques and data storage formats. Additionally, it covers file formats like MIDI and MP3, emphasizing the significance of binary in computing and data representation.

Uploaded by

sheryhishmat
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Computer Science Notes

The document discusses algorithms, their constructs, and methods of representation such as structured English, pseudocode, and flowcharts. It outlines the stages of producing an algorithm, the importance of variables, and the binary number system, including conversion techniques and data storage formats. Additionally, it covers file formats like MIDI and MP3, emphasizing the significance of binary in computing and data representation.

Uploaded by

sheryhishmat
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 90

An Algorithm sequence of steps that can be carried out to perform Algorithms can be expressed in the following

a task. ways:-
Consider the following as an example:- - Structured English
1 Take a spanner and loosen the wheel nuts. - Subset of English language that consists of
2 Position a jack in an appropriate place. commands to describe an algorithm.
3 Raise the car. - Pseudocode
4 Take off the wheel nuts and the wheel. - Makes use of keywords and identifiers
5 Lift replacement w heel into position . without following any particular syntax of
6 Replace wheel nuts and tighten by hand. a programming language.
7 Lower the car. - Flowchart
8 Fully tighten wheel nuts. - Makes of shapes that are linked together
These directions may seem pretty straightforward but not followed to represent the sequence in an algorithm.
correctly in sequence may result in the process becoming very
difficult maybe even impossible.
In computer Science all Algorithms make use of the following basic constructs when writing algorithms:-
- Assignment
- A value is given a name (identifier) or the value is changed.
- Sequence
- The steps the are performed on after the other.
- Selection
- Some steps are performed only under certain conditions. Otherwise different (or no steps are performed).
- Repetition
- Some steps are performed a number of times. A.K.A iteration or looping.
- Input, Processing and Output
- Programs involve data and that is why we need input and output statements.
Stages in Producing an Algorithm:-
• Make sure the problem is clearly defined.
• Break the problem into sub problems (each sub problem will require a separate algorithm)
• Problems can be divided into
• Set up
• input
• processing
• output results.
• Decide on how the data is to be stored, manipulated and then displayed.
• Decide on a method for constructing an algorithm, i.e. pseudo code or flowchart.
• Decided on suitable names (identifiers) for variable names.
• Create test data (normal, abnormal and boundary) and trace tables for finding errors.
• If any errors have been highlight then correct them and re-test the code until it works perfectly.

Is your solution effective?


To check if your solution works perfectly, you should ask yourself the following questions:-
• Does the solution work for all data sets?
• Does the solution have any unnecessary processes that are never used?
• Are there any actions or processes that run more than necessary?
• Can you can come up with a simpler solution and yet achieve the same result?
Variables:-
- It is the space allocated in the main memory to hold some data.
- And of course, it’s contents are suppose to change during execution.
- Unlike constants.
- The size of variable (bytes) depends on its type.
- A variable is referred to by its name (identifier).
Operation Pseudocode Description
Assigning a Value INPUT number Number is assigned with 5 (assuming that is what the user put in)
Guesses ß 1 The value of 1 is assigned to (ß) to Guesses
Value Guesses ß Guesses + 1 Guesses will be added to 1 and then stored in Guesses overwriting the old value
Updating/totalling with the new one.
Copying a Value Total ß Sum The contents of Sum will be copied to Total.
Swapping Two Values We will need a temporary The value of A is temporarily stored Temp. (say A was 5 now 5 is Temp)
variable…say Temp The value of B (say 6) is now copied to A (overwriting 5).
Temp ß A The Value from Temp is then copied to B (5 overwrites 6).
AßB Therefore the value of A(was 5 now is 6) and B(was 6 now is 5) are swapped.
BßTemp

Local Variables:-
Variables that are used within a single module or subroutine (to be discussed later).
Global Variable:-
Variables that are used by all modules or subroutines.
Correlating Flowcharts and Pseudocodes:-
Database Structure:-

Data Types, Programming VS Databases


How to Solve Such Questions?
(part a)
Records can be represented by the rows (ignoring the labels). In this table
there are 6 Rows. Fields or attributes can be represented by the columns
and there are 7 fields in this table. The examiner can ask either the number
of records or fields. In this case we can see that the number of fields have
been asked.
(part b)
The primary key or KEY FIELD is a field or attribute that is unique for each
record. i.e. it can be used to uniquely identify a record. In this case we can
see that Class ID is such a field that can be used as a Primary Key. The
name also seems to be unique but there is no guarantee that any of the
mentioned names cannot be used again. Same is the case with other fields.
(Part C)
Query by Example Grid for this questions is requiring
the use of the following fields:-
• Student Name
• It can be seen here that the “SHOW” box is
checked that means that data in this field is
to be shown.
• History:-
• This field is used but not shown. The criteria
of the records should only be Where History
Marks are >60
• Geography:-
• This is field is also used but not shown. The
criteria of the records being shown is only
when Geography marks are >60
• It should be noted that both criterion are not on
the same row…Geography criteria lies on the OR
row. This means all records will be considered for
which either Geography > 60 OR History > 60.
Therefore, the results will be in exact order. AS
THE SORT HAS BEEN SET TO ASCENDING
ACCORDING TO STUDENT NAMES
Here we can see that the criteria have to be both
for MATH AND ENGLISH therefore they appear
on the the same row. Only student names are to be
displayed and since no order is specified the SORT
field is left empty…
Binary Number Systems
Students will be able to….
- Recognise the use of binary numbers in computer systems
- Convert positive denary integers into binary and positive binary integers into denary (a maximum of 16 bits will be used)
- Show understanding of the concept of a byte and how the byte is used to measure memory size
- Use binary in computer registers for a given application (such as in robotics, digital instruments and counting systems)
Introduction:-
No matter how complex the system, the basic building block in all computers is the binary number system. This system is
chosen since it consists of 1s and 0s only. Since computers contain millions and millions of tiny „switches‟, which must be in
the ON or OFF position, this lends itself logically to the binary system. A switch in the ON position can be represented by 1; a
switch in the OFF position can be represented by 0.
The Binary Number System:-
We are all familiar with the denary (base 10) number system which counts in multiples of 10. This gives us the well-known
headings of units, 10s, 100s, 1000s and so on
105 104 103 102 101 100

10000 1000
0 0 1000 100 10 1

The BINARY SYSTEM is based on the number 2. Thus, only the two „values‟ 0 and 1 can be used in this system to represent each
digit. Using the same method as denary, this gives the headings of 20, 21, 22, 23 and so on. The typical headings for a binary
number with eight digits would be
27 26 25 24 23 22 21 20
128 64 32 16 8 4 2 1

Range of Values (0-255)


Therefore a typical binary number would
be:- 1 1 1 0 1 1 1 0
The number would be repre
Conversion Techniques:-
- Binary to Decimal:-
o This is a straightforward process considering our example 1 1 1 0 1 1 1 0
27 26 25 24 23 22 21 20

128 64 32 16 8 4 2 1

1 1 1 0 1 1 1 0

Simply add the values for the bits that are ON (1) together i.e.
128+64+32+8+4+1 = 23810 - Decimal to Binary:-
o Consider the denary number 116. The technique involves finding a weighted value (i.e 128,64,32,16,8,4,2,1) from
the binary number table that is either equal to 116 or nearest (yet smaller) to 116. Since there is no value equal to
116 the next suitable number would be 64 since 128 is larger than 116. This bit will be turned ON and 64 will be
subtracted from 116. 116 – 64 = 52. Repeat the steps till you have turned all the bits equating up to 116. Your
solution should look like.

27 26 25 24 23 22 21 20

128 64 32 16 8 4 2 1
0 1 1 1 0 1 0 0

NOTE: All even denary number will end with a “0” in binary and ODD will end in “1” in binary.
Bits, Bytes and Size of Computer Memories:-
A Bit is an abbreviated form of Binary Digit. There are 8 bits in one Byte. Bytes are the smallest unit memory in a computer.
Larger or smaller computer all contain multiples of bytes. For example:-
1 kilobyte = (1 KB) = 210 1 024 bytes
1 megabyte = (1 MB = 220 1 048 576 bytes
1 gigabyte = (1 GB) = 230 1 073 741 824 bytes
1 terabyte = (1 TB) =240 1 099 511 627 776 bytes
1 petabyte = (1 PB) = 250 1 125 899 906 842 624 bytes
(all numbers are 1024 × 1024 and so on)
To give some idea of the scale of these numbers, a typical data transfer rate using the internet is 32 megabits (i.e. 4 MB) per second
(so a 40 MB file would take 10 seconds to transfer).
Most hard disk systems in computers are 1 or 2 TB in size (so a 2 TB memory could store over half a million 4 MB photos, for
example).
Manufacturers of storage devices often use the denary system to measure storage size. For example, 1 kilobyte = 1000 byte 1
megabyte = 1000000 bytes 1 gigabyte = 1000000000 bytes 1 terabyte = 1000000000000 bytes and so on.
The Use if Binary Number Systems:-
Consider the working of a washing machine. As
can be seen in the diagram heater and wash
motor are ON while everything else is off for this
machine.

Using Two Bytes:-


Larger denary numbers can be represented using two bytes.
215 214 213 212 211 210 29 28 27 26 25 24 23 2 2 21 20

32,78 16,368 8,19 4,09 2,04 1,02 256


6 4 2 6 8 4 512 8 128 64 32 16 8 4 2 1

With two bytes the range of denary numbers become 0-65,535

Binary Coded Decimal (BCD):-

Binary Addition:-
Bit wise addition:-
Sum Carry

1+0 1 0

0+1 1 0

1+1 0 1

1+1+1 1 1

The Following table will add the Bytes 11011011 + 11101101


*1 1 1 1 1 1 1 1 Carry

1 1 0 1 1 0 1 1 Byte 1
1 1 1 0 1 1 0 1 Byt3
1 1 0 0 1 0 0 0 Sum
*this bit can be ignored if the answer required is to remain within one BYTE.
Representing a Negative binary number:-
We use the following method to represent a negative number -76
Step 1:- convert the numeric part of the number into binary i.e. 76
128 64 32 16 8 4 2 1
0 1 0 0 1 1 0 0
Step2: Start moving from the right to left till you encounter the first “1”. Leave that bit and invert every bit that comes after
resulting in the following:-
128 64 32 16 8 4 2 1
1 0 1 1 0 1 0 0

The resulting binary sequence is -76.


Consider the following negative binary number 11011010. For negative binary numbers the most significant bit (the bit on the
extreme left) is always turned on. If we wish to represent this number in denary we will do the following…
-128 64 32 16 8 4 2 1
1 1 0 1 1 0 1 0

Notice that the place value for the most significant bit(MSB) is -128, this will be case for all negative binary numbers. The next step
is to simply add the weighted values together to get…
-128+64+16+8+2 = -42
1.1.3Data Storage
Introductions:-
There are many formats in which data is stored such as images, sound, videos and even text. This section will explore the different
types of data as well as the different techniques used for file compression. Students will also here about primary memory and secondary memory
as well as the main technologies used in (magnetic, optical and solid state).
File Formats:-
We will look at MIDI, MP-3, MP-4, jpeg, text and number format.
MIDI:-
Musical Instrument Digital Interface is involved with the storage of music files. MIDI files are not music files and do not contain any
sound, they are different from MP3 and MP4 files. MIDI files basically contain a list of commands that instruct a device on how to create a
particular sound. MIDI operates on 16 different channels (0 to 15) and contains instructions that indicate what key is to played and how hard it
is to be played. It also contains additional bytes that include PITCH BYTE on what note to play and VELOCITY BYTE to tell how loud to play
a certain note. If this “.mid” file is played back using a musical instrument then it will play according to the original version. Due to its 16
channels the MIDI files can support up to 16 different instruments. Due to a complete lack of audio in MIDI files it is 10 times smaller than a
normal MP3 file.
MPEG-3 and MPEG-4
MPEG-3 (MP3) uses technology known as AUDIO COMPRESSION to convert music and other sounds into an MP3 file format.
Essentially, this compression technology will reduce the size of a normal music file by about 90 per cent. For example, an 80 megabyte music
CD can be reduced to 8 megabytes using MP3 technology. MP3 files are used in MP3 players, computers or mobile phones. Files can be
downloaded from the internet, or CDs can be converted to MP3 format using FILE COMPRESSION software. The converted version does not
match the full version of a CD but still is usable for most general purposes. With the help of PERCEPTUAL MUSIC SHAPING sounds that
the human ear cannot hear properly are removed hence reducing the size of the file without affecting the quality too much. The quality of MP3
files can be different since it depends on the BIT RATE – this is the number of bits per second used when creating the file. Bit rates are roughly
between 80 and 320 kilobits per second; usually 200 or higher gives a sound quality close to a normal CD. MPEG-4 (MP4) files allows the
storage and transfer of multimedia files rather than just sound i.e. music, videos, photos and animation over some medium such as the internet
without losing any real noticeable quality.
Joint Photographic Experts Group (jpeg) files:-
The resolution of the photographs is reduced from First to Last. The first two are somewhat
sharp but the last one is almost unrecognisable. This is the result of changing the number of
PIXELS per centimetre used to store the image (that is, reducing the PICTURE
RESOLUTION).

When a photographic file undergoes file compression, the size of the file is reduced. The trade-off for this reduced file size is reduced
quality of the image. One of the file formats used to reduce photographic file sizes is known as JPEG. As with MP3 format, once the image is
subjected to the jpeg compression algorithm, a new file is formed and the original file can no longer be constructed this is also known as Lossy
compression. Jpeg will reduce the RAW BITMAP, which can be of TIFF (.TIF) or BITMAP (.BMP) image, by a factor of between 5 and 15
depending on the quality of the original.
For Example:-
An Image is 2048 pixels wide and 1536 pixels high with a total of (2048 * 1536) = 3,145,728 in other words more than 3 megapixel image. Since there are
three main colours (RED, GREEN and BLUE) each colour takes up one byte therefore a 3 megapixel image will take up 9 megabytes (3 megapixels * 3). If the
same image stored in jpeg will take up .6 to 1.8 megabytes.
Text and Number Formats:-
Text and numbers can be stored in a number of formats. Text is usually stored in an ASCII format. It is important that the correct
format is chosen if some form of processing is to be done. If number files undergo any form of file compression, then it tends to be lossless.
Since it very important that none of the information/data is lost. If ASCII format is used to store text on a file, then the word COMPUTER
would be stored as either:
67 79 77 80 85 84 69 82 or %43 %4F %4D %50 %55 %54 %45 %52
(the first code is in denary and the second in hexadecimal)
Text files can also undergo file compression. These use complex algorithms that work on redundancy or repeated sections of words.
The following section shows, in very simple terms, how this could work: The phrase „THIS SECTION SHOWS YOU HOW THIS WOULD
WORK‟ consists of 35 memory units (ignoring spaces). Repeated words, such as „THIS‟ could be put into a data dictionary and be replaced by
„1‟. Repeated word sections, such as „HOW‟ and „OU‟ could be replaced by the numbers „2‟ and „3‟. Our phrase then becomes „1 SECTION
S2S Y3 2 1 W3LD WORK‟.
1.1.3Data Storage
Again, ignoring spaces, this compressed form now uses only 23 memory units. This is about a 33% saving in file size. Obviously if
whole pages are to be stored, then repeated words and word sections become even more numerous. This is clearly an example of lossless
compression since the original phrase can be reformed if necessary using the data dictionary and compressed file.
Lossless File Compression:-
With LOSSLESS FILE COMPRESSION, all the data bits from the original file are reconstructed when the file is again uncompressed. This is
particularly important for files where loss of any data would be disastrous – for example, a spreadsheet file.
Lossy file compression:-
LOSSY FILE COMPRESSION is very different to lossless file compression. With this technique, the file compression algorithm eliminates
unnecessary bits of data as seen in MP3 and jpeg formats. It is impossible to get the original file back once it is compressed. This is why it is
chosen for files where removing certain bits doesn‟t detract from the quality.
CS 0478 Topic 1.2

Communication and Internet Technologies:-


When data is sent from one device to another, it is important to consider how that data is transmitted. It is also important to ensure that
the data hasn’t been changed in any way. The internet has now become an integral part of all of our lives. Therefore we will consider
some of the important technologies going on in the background which support the internet.
Data Transmission:-
Data transmission can be either over a short distance (for example, from computer to printer) over longer distances (for example, over a
telephone network).
Essentially, three factors need to be considered when transmitting data (each factor has to be agreed by both sender and receiver for this
to work without error):
• The direction of the data transmission (i.e. in one direction only or in both directions)
• The method of transmission (how many bits are sent at the same time)
• The method of synchronisation between the two devices.
Simplex, Half Duplex, Full Duplex:-
Transmission Type Description Example
Simplex Transmission is carried out one direction The Data being sent from computer to
only. From sender to receiver. printer.
Half Duplex The Transmission is carried out in both a phone conversation between two people
directions but one direction at a time. A where only one person speaks at a time
can send data to B and vice versa but one
at a time.
Full Duplex The Transmission is carried out in both Broadband connection on a phone line.
directions simultaneously. data can be sent
from ‘A’ to ‘B’ and from ‘B’ to ‘A’ along
the same line
Serial and Parallel Tranmission:-
Serial Data Transmission is when data is sent, one bit at a time, over a single wire or channel (bits are sent one after the other in a single
stream).

This method of data transmission works well over long distances. However, data is transmitted at a slower rate than parallel data
transmission. Since only one wire or channel is used, there is no problem of data arriving at its destination out of synchronization.
Parallel Data Transmission is when several bits of data (usually 1 byte) are sent down several wires or channels at the same time; one
wire or channel is used to transmit each bit.
This method of data transmission works very well over short distances (over longer distances, the bits can become ‘skewed’ – this means
they will no longer be synchronised). It is, however, a faster method of data transmission than serial. An example of its use is when
sending data to a printer from a computer using a ribbon connector:-

A common use for serial data transmission is Universal Serial Bus (USB) Parallel data transmission is used in the internal electronics of
the computer system. The pathways between the CPU and the memory all use this method of data transmission. Integrated circuits,
buses and other internal components all use parallel data transmission because of the need for high speed data transfer. 16-bit, 32-bit
and 64-bit buses, for example, allow much faster data transmission rates than could be achieved with single channel serial data transfer.
An internal clock is used to ensure the correct timing of data transfer; it is essentially synchronous in nature and the short distances
between components mean that none of the issues described earlier have any real impact on the accuracy of the data.
Asynchronous and Synchronous Data Transmission:-

Hassan Zulfiqar Haider


[email protected]
0323414090 Page 1
CS 0478 Topic 1.2
ASYNCHRONOUS DATA TRANSMISSION refers to data being transmitted in an agreed bit pattern. Data bits (1s and 0s) are
grouped together and sent with CONTROL BITS.

This means that the receiver of the data knows when the data starts and when it ends. This prevents data becoming mixed up; without
these control bits, it would be impossible to separate groups of data as they arrived.
SYNCHRONOUS DATA TRANSMISSION is a continuous stream of data (unlike asynchronous data which is sent in discrete groups).
The data is accompanied by timing signals generated by an internal clock. This ensures that the sender and receiver are synchronised
with each other. The receiver counts how many bits (1s and 0s) were sent and then reassembles them into bytes of data. The timing must
be very accurate here since there are no control bits sent in this type of data transmission. However, it is a faster data transfer method
than asynchronous and is therefore used where this is an important issue (for example, in network communications).
Universal Serial Bus (USB):-
The UNIVERSAL SERIAL BUS (USB) is an asynchronous serial data transmission method. It has quickly become the standard
method for transferring data between a computer and a number of devices.
Essentially, the USB cable consists of:
- A four-wire shielded cable
- Two of the wires are used for power and the earth
- Two of the wires are used in the data transmission.
When a device is plugged into a computer using one of the USB ports the computer automatically detects that a device is present
(this is due to a small change in the voltage level on the data signal wires in the cable). The device is automatically recognised, and the
appropriate DEVICE DRIVER is loaded up so that computer and device can communicate effectively. If a new device is detected, the
computer will look for the device driver which matches the device; if this is not available, the user is prompted to download the
appropriate software.
Even though the USB system has become the industrial standard, there are still a number of benefits and drawbacks to using this
system.
Advantages Disadvantages
Devices plugged into the computer are The maximum cable length is presently about 5
automatically detected; device drivers are metres
automatically uploaded.
The connectors can only fit one way; this The present transmission rate is limited to less
prevents incorrect connections being made. than 500 megabits per second
This has become the industry standard; this Older Standards may not be compatible in the
means that considerable support is available to users. near future.
Several different data transmission rates are
supported
Newer USB standards are backward compatible
with older USB standards

Error Checking Methods:-


Following data transmission, there is always the risk that the data has been corrupted or changed in some way. This can occur whether
data is being transmitted over short distances or over long distances. Checking for errors is important since computers aren’t able to
check that text is correct; they can only recognise whether a word is in their built-in dictionary or not.

Hassan Zulfiqar Haider


[email protected]
0323414090 Page 2
CS 0478 Topic 1.2

Whilst you probably had little problem understanding this text, a computer would be unable to make any sense of it. This is why error
checking is such an important part of computer technology. This section considers a number of ways that can be used to check for errors
so that you don’t end up with text as shown in the example above!

A number of methods exist which can detect errors and, in some cases, actually correct the error. The methods covered in this section
are:
• Parity checking
• Automatic repeat request (ARQ)
• Checksum
• Echo checking
Parity Checking:-
PARITY CHECKING is one method used to check whether data has been changed or corrupted following transmission from one device
or medium to another device or medium.
• A byte of data, for example, is allocated a PARITY BIT.
• This is allocated before transmission takes place.
• Systems that use EVEN PARITY have an even number of 1bits
• Systems that use ODD PARITY have an odd number of 1-bits.

If this byte is using even parity, then the parity bit needs to be 0 since there is already an even number of 1-bits (in this case, 4). If odd
parity is being used, then the parity bit needs to be 1 to make the number of 1-bits odd.
Therefore, the byte just before transmission would be:-

Parity Blocks:-

Hassan Zulfiqar Haider


[email protected]
0323414090 Page 3
CS 0478 Topic 1.2

Checksums:-
CHECKSUM is another way to check if data has been changed or corrupted following data transmission. Data is sent in blocks and an
additional value, the checksum, is also sent at the end of the block of data. To explain how this works, we will assume the checksum of a
block of data is 1 byte in length. This gives a maximum value of 28 – 1 (i.e. 255). The value 0000 0000 is ignored in this calculation.

Echo check:-
With ECHO CHECK, when data is sent to another device, this data is sent back again to the sender. The sender compares the two sets
of data to check if any errors occurred during the transmission process. As you will have no doubt worked out, this isn’t very reliable. If
the two sets of data are different, it isn’t known whether the error occurred when sending the data in the first place, or if the error
occurred when sending the data back for checking! However, if no errors occurred then it is another way to check that the data was
transmitted correctly.
MOD 11 Check Digit:-
A check digit is a number that is used to validate a series of numbers whose accuracy you want to insure. Frequently the last digit of a
number string such as identification number is a check digit. Lets say the identification number starts out at 6 digits. A calculation is
done using the six digits and a seventh digit is produced as a result of the calculation. This number is the check digit.

Steps to calculate the MOD11 check digit for a number such as an id #:


• Assign weights to each digit of the id #. The weights in MOD11 are from 2 through a maximum of 10 beginning with the low
order position in the field.
• Each digit in the id # is multiplied by its weight
• The results of the multiplication are added together
• This product is divided by the modulus number 11
• The remainder is subtracted from the modulus number 11 giving the check digit
Finding the check digit for the number 036532
Number 0 3 6 5 3 2

Weights x7 x6 x5 x4 x3 x2

Number * 0 18 30 20 9 4
Weights
0 + 18 + 30 + 20 + 9 + 4 = 81

Hassan Zulfiqar Haider


[email protected]
0323414090 Page 4
CS 0478 Topic 1.2
81/11 = 7 remainder 4
11 - 4 = 7
7 is therefore the check digit.
Hence the Number becomes 0365327

If the remainder from the division is 0 or 1, then the subtraction will yield a two digit number of either 10 or 11. This won't work, so if
the check digit is 10, then X is frequently used as the check digit and if the check digit is 11 then 0 is used as the check digit.

Example of verifying the number 0365327 where 7 is the calculated MOD11 check digit:
0 3 6 5 3 2 7

x7 x6 x5 x4 x3 x2 x1

0 18 30 20 9 4 7

0 + 18 + 30 + 20 + 9 + 4 + 7 = 88
88/11 is 8 remainder 0
Since the remainder from this calculation is 0, the check digit 7 is valid.
Automatic Repeat Requests:-

Internet technologies:-
Internet Service Provider (ISP):-
Each user makes use of an INTERNET SERVICE PROVIDER (ISP); these are companies that provide the user with access to the
internet. A monthly fee is usually charged for this service. The ISP will set up a user account which will contain a username and a
password; most ISPs also give the user an email address. Before ISPs became common in the 1990s, internet access was usually limited to
users who were part of a university or a government agency.
Internet Protocol (IP) Address:-
Each device on the internet is given a unique address known as the INTERNET PROTOCOL (IP) ADDRESS. This is a 32-bit number
which is usually written in the form:
109.108.158.1
A home computer is given an IP address when it connects to the internet. This is assigned by the ISP and is unique for that particular
internet session. The only IP addresses that remain fairly unchanged are web servers. An IP address can be used instead of typing in the
full URL. For example “http://109.108.158.1” would take you straight to the device corresponding to this address.
IP addresses and MAC addresses:-
MEDIA ACCESS CONTROL (MAC) ADDRESS is a unique number that identifies a device connected to the internet. So what is the
difference between an IP address and a MAC address?
• The IP address gives the location of a device on the internet,
• whereas the MAC address identifies the device connected to the internet.
Consider the IP address as the address of the house you live in. The MAC address can be thought of as a way of uniquely identifying
each person living in that house. It is possible to move house (so your IP address will change) but the same people will be living in the
new house (so their MAC addresses will remain unchanged).

Hassan Zulfiqar Haider


[email protected]
0323414090 Page 5
CS 0478 Topic 1.2
HyperText Mark-up Language (HTML):-
HYPERTEXT MARK-UP LANGUAGE (HTML) is used when writing and developing web pages. HTML isn’t a programming language
but is simply a mark-up language. A mark-up language is used in the processing, definition and presentation of text (for example,
specifying the colour of the text). HTML uses <tags> which are used to bracket a piece of code; for example, <td> starts a standard cell in
an HTML table, and </td> ends it. Whatever is between the two tags has been defined.

HTML structure and presentation:-


STRUCTURE is the essential part of the HTML document; it includes the semantics (meaning) and structural mark-up of the
document. PRESENTATION is the style of the document; i.e. how the document will look (or even sound if it includes multimedia
elements).
Some of the <tags> used to create a css file have been shown already in the HTML example shown above. The following examples shows
an example of how these <tags> can be used to create a stylesheet called example2.css. This is then used in a web page document. The
tags (h1, h3 and p) all define how the document will look when this css file (stylesheet) is attached.

Hypertext transfer protocol (http):-


HYPERTEXT TRANSFER PROTOCOL (HTTP) is a set of rules that must be obeyed when transferring files across the internet. When
some form of security (e.g. SSL certification or encryption) is used, then this changes to https (you also often see the padlock sign in the
status bar).
HTTP vs HTTPS:-
It is slower to use https than http; https is usually only adopted where sensitive or private data is being transferred across the internet.
Web browsers:-
A WEB BROWSER is software which allows a user to display a web page on their computer screen. Web browsers interpret or translate
the HTML code from websites and show the result of the translation. Users can either click on a link,
such as www.hoddereducation.co.uk/igcse
or they can type in the uniform resource locator (URL) manually.

Hassan Zulfiqar Haider


[email protected]
0323414090 Page 6
CS 0478 Topic 1.2

The web browser translates the web server name into an IP address which is part of the URL. The HTML code is returned and is shown
as a correctly formatted page on the computer screen. It is also possible that cookies may be sent from the web browser to the web server
when the code is executed.
What is a Cookie?
An HTTP cookie is a small piece of data sent from a website and stored on the user's computer by the user's web browser while
the user is browsing.

Hassan Zulfiqar Haider


[email protected]
0323414090 Page 7
Hexadecimal Number System

The Hexadecimal Number System:-


The HEXADECIMAL SYSTEM is very closely related to the binary system. Hexadecimal (sometimes referred to as simply ‘hex’) is a base 16 system and therefore needs to use 16
different ‘values’ to represent each digit. I includes the numbers 0 to 9 and the letters A = 10, B = 11, C = 12, D = 13, E = 14 and F = 15. As seen with the binary and denary
number representation:-
164 163 162 161 160
65536 4096 256 16 1
Since 24 = 16 therefore it can be concluded that 4 bits are needed to represent one Hexadecimal number.
Conversion Techniques:-
- Binary to Hexadecimal:-
o Consider the binary sequence 1 0 1 1 1 1 1 0 0 0 0 1
o We can start by dividing the above mentioned sequence into 4 bits each.
 1011 1110 0001
23 22 21 20 23 22 21 20 23 22 21 20
8 4 2 1 8 4 2 1 8 4 2 1
1 0 1 1 1 1 1 0 0 0 0 1
8 + 2 + 1 = 11 = B 8 + 4 + 2 = 14 = E 1

 Therefore
 1 0 1 1 1 1 1 0 0 0 0 1(2) = B E 1(16)
- Hexadecimal to Decimal:-
o Consider the Hexadecimal number ABE(16)
162 161 160
256 16 1
A B E
10×256=2560 11×16=176 14×1=14
2560 + 176 + 14 = 2,750 (10)
 Therefore
 ABE(16) = 2,750 (10)
- Decimal to Hexadecimal:-
o The process involves the following steps
 Convert the decimal number to binary
 The convert the binary number to hexadecimal as mentioned before.
The Use of Hexadecimal Numbers:-
1. Memory Dumps:-
Since it is much easier to work with B 5 A 4 1 A F C rather than 1 0 1 1 | 1 0 0 1 | 1 0 1 0 | 0 1 0 0 | 0 0 0 1 | 1 0 1 0 | 1 1 1 1 | 1 1 0 0 hexadecimal is often used when
developing new software or when trying to trace errors in programs. The contents of part of the computer memory can hold the key to help solve many problems. Hexadecimal is
often used when developing new software or when trying to trace errors in programs. The contents of part of the computer memory can hold the key to help solve many problems.
2. Hypertext Markup Language (HTML):-
(HTML) is used when writing and developing web pages. HTML isn’t a programming language but is simply a mark-up language. A mark-up language is used in the processing,
definition and presentation of text (for e.g, specifying the colour of the text). HTML uses hexadecimal number to represent the different colors by varying the intensity of the three
primary colors (RED, GREEN and BLUE).
Hexadecimal Number RED GREEN BLUE Color
FF0000 FF 00 00 Red
00FF00 00 FF 00 BLUE
0000FF 00 00 FF GREEN
FF0099 FF 00 99 PINK
3. Media Access Control (MAC):-
A MEDIA ACCESS CONTROL (MAC) ADDRESS refers to a number which uniquely identifies a device on the internet. The MAC address refers to the network interface card
(NIC) which is part of the device. A MAC address is usually made up of 48 bits which are shown as six groups of hexadecimal digits (although 64-bit addresses are also known).
Consider the MAC Address:- 60:F1:89:5A:BB:D4
Vendor# Serial#
NN NN NN DD DD DD
60 F1 89 5A BB D4
The first three digits (NN:NN:NN) represent the vendor id and the final three digits (DD:DD:DD) represent the device ID.
4. Web addresses:-
Each character used on a keyboard has what is known as an ASCII CODE (AMERICAN STANDARD CODE FOR INFORMATION INTERCHANGE). These codes can be
represented using hexadecimal values or decimal values. A good example of the use of ASCII codes is the representation of a web address (or URL, which stands for uniform
resource locator)

5. Assembly code and Machine code:-

Computer memory can be referred to directly using machine code or assembly code. This can have many advantages to program developers or when carrying out troubleshooting.

Assembly Language Code Binary Code


STO FFA4 (more manageable) 1010 0101 1110 0100 1111 1111 1010 0100 (very difficult to process)
Binary Logic
Producing a Truth Table from Logic Circuit:-
Solving a Logic Problem:-
Consider the Following Example
1.3.2 Computer Architecture/Fetch Decode Cycle
Von Neumann model
Von Neumann introduced the idea of the stored program. Previously data and programs were stored in separate memories. Von Neumann realized that data
and programs are indistinguishable and can therefore use the same memory. Von Neumann architecture uses a single processor. It follows a linear sequence of
fetch-decode-execute operations for sequence of instructions which makeup the program. In order to do this a processor has to use some special registers. A register
is simply a location that can store extremely limited amount of instruction or data only immediately before or after processing. The registers are outside the
immediate access store and consequently allow faster access to the data they store.
Processor uses a group of special purpose registers to execute a program. Program counter (PC): Program counter is sometimes called sequence control register.
It stores the address of the next instruction to be fetched. Memory address register (MAR): When the next instruction is needed, its address is copied from the
PC and placed in the memory address register. Memory data registers (MDR): It is sometime called the memory buffer register (MBR) because it acts like a
buffer, temporarily storing a data value before passing it on to e.g. CIR. Index register (IR): An index register in a computer's CPU is a processor register used
for modifying operand addresses during the run of a program, typically for doing vector/array operations. If the address is an indexed address, add the address
to the contents of the index register to form the address of actual data. Current instruction register (CIR): Holds the instruction that is about to be executed.
Status register: A status register, flag register, or condition code register is a collection of status flag bits for a processor. The status register is a hardware
register which contains information about the state of the processor.
Arithmetic logic unit
In digital electronics, an arithmetic logic unit (ALU) is a digital circuit that
performs arithmetic and bitwise logical operations on integer binary numbers. It is a fundamental
building block of the central processing unit (CPU) found in many computers. An ALU performs basic
arithmetic and logic operations. Examples of arithmetic operations are addition, subtraction,
multiplication, and division. Examples of logic operations are comparisons of values such as NOT,
AND,OR.

Control unit
The control unit is a component of a computer's central processing unit (CPU) that directs operation of the processor. It tells the computer's memory,
arithmetic/logic unit and input and output devices how to respond to a program's instructions.
It directs the operation of the other units by providing timing and control signals. All computer resources are managed by the CU (Control Unit).It directs the
flow of data between the Central Processing Unit (CPU) and the other devices. The Control Unit makes decisions and sends the appropriate signal down its
lines to other parts of the computer. It controls the timing of operations in the computer and controls the instructions sent to the processor and the peripheral
devices.
The fetch-execute cycle
An instruction cycle (sometimes called fetch-and-execute cycle, fetch-decode-execute cycle, or FDX) is the basic operation cycle of a computer. It is the process by
which a computer retrieves a program instruction from its memory, determines what actions the instruction requires, and carries out those actions. This cycle is
repeated continuously by the central processing unit (CPU), from boot-up to when the computer is shut down.
- Fetch Phase:-
1. The PC copies the address of the next instruction to be fetched into the Memory Address Register.
2. The Memory Address Register places the address on the Address Bus (one directional channel from processor to main memory for
transferring addresses of memory locations)
3. The MAR triggers are read signal that causes main memory to place instruction being asked on the Data Bus (two way channel b/w CPU
and RAM that is used for transferring programs and data).
4. The instruction on the data bus is sent to the MDR/MBR.
5. This instruction is then copied to the Current Instruction Register.
- Decode Phase:-
o The CPU will now examine the instruction in the CIR and “decodes” it. This means that a special part of CPU known as the Decode Unit
will make the rest of the CPU ready to carry out the instruction by sending out microinstructions. Every CPU has its own set of legitimate
instructions known as the Instruction Set. All software eventually ends up being instructions from this instruction set.
- Execute Phase:-
o After decoding the instruction a special part of the CPU known as the Execute Unit will carry out execution. After execution the PC will
point towards the next instruction.
1.3.3 Input Devices

Scanners:-
Scanners are either 2 Dimensional or 3 Dimensional but their purpose is the same; to convert an image which is physical form into digital form to be stored on
a computer.
- 2 Dimensional Scanners:-
The following steps take place for during the working of a 2-Dimensional scanner.
o The cover is raised, and the document is placed on the glass panel and the cover is closed.
o A very bright light illuminates the documents. The scan head rolls under the document thereby returning the image to a lens with the help
of a mirror.
o The image falls on a Charged Couple Device (CCD) which is composed of integrated circuits etched on silicon. The CCD is made of
thousands of light sensitive elements that create a charge when light falls on them. This way the an electronic version of the image is
formed.
 Computers equipped with OCR (optical character recognition) allow the scanned image to be converted to a document therefore
allowing editing.
 2D Scanning is used in Airports
 For scanning passports.
 For facial recognition.
- 3 Dimensional Scanners:-
This type of scanner is used when we want to create a scan of 3 Dimensional Figure by capturing the x, y and z coordinates of the real object. This
technology is heavily used in Computer Aided Design (CAD) allowing the electronic version of an image to be send to a 3 Dimensional Printer to
create a working model of a scanned image. There are numerous technologies used in 3D scanners – lasers, magnetic resonance, white light, and so
on.
Barcode readers/scanners:-
A barcode is a series of dark and light parallel lines of varying thickness. The numbers 0 to 9 are each represented by a unique series of lines. Various barcode
methods for representing these digits exist. The UPC ((Universal Product Code) version A) adopts different codes for digits for both left and right. The actual
left-hand and right-hand sides of the barcode are separated using guard bars and each digit is represented by bars of 1 to 4 blocks thick.
Guard Bars Table Representation

Representation of 543052

- Working of a Barcode Scanner:-


o The barcode is first read by a red laser or red LED (LIGHT EMITTING DIODE).
o Light is reflected back off the barcode; the dark areas reflect little or no light which allows the bars to be read.
o The reflected light is read by sensors (photoelectric cells).
o As the laser or LED light is scanned across the barcode, a pattern is generated which is converted into digital data – this allows the
computer to understand the barcode.
- Advantages Include:-
o much easier and faster to change prices on stock items
o much better, more up-to-date sales information/sales trends
o allows for automatic stock control
o faster checkout queues (staff don’t need to remember/look up prices of items)
o errors in charging customers are reduced
Quick response (QR) codes:-

QR Codes are also a type of Barcodes but unlike the latter, they are made up of filled in dark squares on a light background. Such as .A normal barcode
can hold up to 300 digits whereas a QR code can hold over 7000 digits. Because of modern smart phones, which allow internet access on the move, QR codes
can be scanned anywhere. This allows advertising of products on trains, buses, shopping malls and many other places with the help of built in technology and
QR reading App.
- Advantages Include:-
o There is no need for the user to write down or key in a website address; scanning the QR code does this automatically
o QR codes can store website addresses/URLs that appear in magazines, trains, buses or even on business cards, giving a very effective method
of advertising
Digital cameras:-
Digital cameras have replaced the traditional cameras that used film to capture photos. The film required developing before any results could be seen, making a
photography a very lengthy and expensive process. Digital cameras can now be easily connect to any computer with the help of USB cable or wireless
connections. The photograph is captured when light passes through the lens onto a light sensitive cell and processed by a microprocessor. This cell is made up
of tiny elements known as pixels. The number of pixels determines the size of the file used to store the photograph.
Keyboards:-
The most common input device it is used for inputting text, numbers, punctuation marks, symbols and instructions using a number of software applications. By
pressing down a key completes an electrical circuit. This circuit then transmits a binary signal (commonly using ASCII) to the computer to represent the key
1.3.3 Input Devices

pressed. Keyboards are a relatively slow method of data entry and are also prone to errors. However, frequent use of these devices can lead to injuries, such as
REPETITIVE STRAIN INJURY (RSI) in the hands and wrists. Modern ergonomic keyboards can help solve this problem.
Mouse:-
A pointing device that functions by detecting motion relative to its 2 dimensional surface.
- Laser Mouse:-
o A laser mouse uses a light source, typically a LED, and a light detector to detect movement relative to a surface. It is an alternative to the
ball mouse which uses moving parts to perform the same function.

o The light source is focused towards the surface below. The reflected light falls back to the camera integrated in Optical Mouse Sensor.
o The camera takes images of the surface with a frequency in the range of 1500 to 6000 images per second to calculate the position of mouse.

o These images are processed by Digital Signal Processor (DSP) and resultant co-ordinates are sent to the PC. The driver of the mouse
installed in the computer receives the co-ordinates and makes the cursor move on the screen accordingly.
- Tracker Ball:-
o Trackerballs are seen more often in an industrial environment – such as a control room. Because they don’t need to move, the trackerball
doesn’t need any desk space or special surface. The operator is also less likely to suffer from injuries such as RSI. A ball on the top of the
trackerball is moved to control a cursor on the screen.
Microphones:-
These devices are used for inputting sound to a computer. They can either be built-in or be connected as external devices. When a microphone picks up sound,
a diaphragm vibrates producing an electric signal. This signal goes to a sound card and is converted into digital values and stored in the computer. If the
microphone is being used in a VOICE RECOGNITION system, the user’s voice is compared to that stored in memory for identification. In SPEECH
RECOGNITION system the user’s voice is used to identify different words for further processing.
Touchscreens:-
Touchscreens are now a very common form of input device. They allow simple touch to launch an application or to carry out many of the functions of pointing
devices such as a mouse. One of the main uses of touchscreen technology is in mobile phones. There can be the following types:-
Capacitive:- Made up of many layers of glass that act as capacitor. Touching the top layers will result in an electrical change as a result of which the on board processor will
determine the coordinates of the place touched. It is medium cost, with sunlight legibility and allows for multi touch. The screen is also very durable. However, the user must use
bare fingers only to make use of such touch screens.
Infra Red(Heat and Optical):- In Heat based the coordinates of placed touched on screen is determined by some warm object coming in contact (i.e. fingers.). Whereas in
Optical, sensor detect disturbance in infra red light grid hence causing the coordinates to be identified. Both have multi touch and good screen legibility. The optical type even
allows for screen to be touched using gloves. However it is an expensive technology.
Resistive:- The top layer of screen is polyester and the bottom layer is glass. When touch the top and bottom layer come in contact as result of which a complete circuit is formed
and the coordinates are identified. Cheap technology and it is possible to use with gloves. Does not allow multi touch, poor legibility in sun light.
Sensors:-
Sensors are devices that read physical quantities from their surrounding in analogue form. To be cable of process this data is converted into digital data using an
ANALOGUE TO DIGITAL CONVERTER (ADC).
Some Types of Sensors
Sensor Measures Where Used
Heat Temperature Living room for central heating system
Humidity Water vapour in the air Swimming pool, greenhouse
Infra-red Infra-red radiation e.g. body heat Security alarm systems
Light Light levels External security lights
PH Acid/alkali levels e.g. pH of soil Environmental experiments, river pollution
Pressure Pressure Burglar alarm systems, automatic doors
Smoke Smoke in the atmosphere Offices
Sound Levels of sound Security alarm systems
Tilt Angle of tilt Windows in security alarm system
Touch Detects if one object bumps into another Computer controlled robots
Sample Questions Using Sensors:-
Working:- Possible Sensors:-
The Sensors take input from surrounding. The data is in Analogue form and Student should be able to mention
is converted into digital form using ADC. This digital data is sent to the the appropriate type of sensors based
microprocessors as a result of which the system undergoes the appropriate on the scenario. Knowledge of the
changes. purpose of all sensors is a must.

Interactive White Boards:-


Interactive whiteboards are devices that allow computer images to be displayed on a whiteboard using a digital projector. They also allow a user to write on the
whiteboard and the text or drawings produced are then stored in an electronic form for later use. Basically the information which is hand-drawn or hand-written
can be stored so nothing from, for example, a meeting is lost.
1.3.5 Memory And Storage Devices

Primary memory is computer memory that is accessed directly by the CPU. This includes
several types of memory, such as the processor cache and system ROM. However, in most cases,
primary memory refers to system RAM.RAM, or random access memory, consists of one or
more memory modules that temporarily store data while a computer is running. RAM is volatile
memory, meaning it is erased when the power is turned off. Therefore, each time you start up
your computer, the operating system must be loaded from secondary memory (such as a hard
drive) into the primary memory, or RAM.

Similarly, whenever you launch an application on your computer, it is loaded into RAM. The operating
system and applications are loaded into primary memory, since RAM can be accessed much faster than storage devices. In fact, the data can be transferred
between CPU and RAM more than a hundred times faster than between the CPU and the hard drive. By loading data into RAM, programs can run
significantly faster and are much more responsive than if than constantly accessed data from secondary memory. DVD RAM is a recent addition to the optical
media group. Unlike other CD and DVD formats, DVD RAMs have several discrete concentric tracks rather than a single spiral track. This gives them the
advantage that writing and reading can occur at the same time. This makes it possible to watch an already recorded television program at the same time as
different program is being recorded.DVD RAMs can written to many times.DVD RAMs have a long life estimated to be 30 years and re-write operation can be
carried out over 100,000 times which is 100 times more than RW formats.
Secondary memory refers to storage devices, such as hard drives and solid state drives. Unlike primary memory; secondary memory is not accessed directly by
the CPU. Instead, data accessed from secondary memory is first loaded into RAM and is then sent to the processor. The RAM plays an important intermediate
role, since it provides much faster data access speeds than secondary memory. By loading software programs and files into primary memory, computers can
process data much more quickly. While secondary memory is much slower than primary memory, it typically offers far greater storage capacity. For example, a
computer may have a one terabyte hard drive, but only 16 gigabytes of RAM. Secondary memory is non-volatile, meaning it retains its data with or without
electrical power. RAM, on the other hand, is erased when a computer is shut down or restarted. Therefore, secondary memory is used to store "permanent
data," such as the operating system, applications, and user files.
Hard disk:- A hard disk is really a set of stacked "disks," each of which, like phonograph records, has
data recorded electromagnetically in concentric circles or "tracks" on the disk. A "head” records
(writes) or reads the information on the tracks. Two heads, one on each side of a disk, read or write
the data as the disk spins. Each read or write operation requires that data be located, which is an
operation called a "seek." (Data already in a disk cache, however, will be located more quickly.) A hard
disk/drive unit comes with a set rotation speed varying from 4500 to 7200 rpm. Disk access time is
measured in milliseconds. The physical location can be identified with cylinder, track, and sector
locations.

Solid state devices (SSDs):- Solid-state drives actually aren't hard drives in the traditional sense of the term, as
there are no moving parts involved. A traditional hard disk drive (HDD) consists of a spinning disk with a read/write head on a mechanical arm. An SSD, on
the other hand, has an array of semiconductor memory organized as a disk drive, using integrated circuits (ICs) rather than magnetic or optical storage media.
Off-line storage is any storage that is not currently online, live or connected to the computer. The data stored in offline storage remains permanently in the
storage device even if it’s disconnected or unplugged from the computer after the data has been stored. Offline storage is generally portable in nature and can be
used on different computer systems. Common examples of offline storage include floppy disks, compact disks and USB sticks.
Solid state memory:- Solid state systems control the movements of electrons within the microchip. The 1s and 0s are stored in millions of miniature transistors
within the microchip. If a transistor conducts a current this is equivalent to a 1 otherwise 0.they consequently have no moving parts, consume much less power
and are extremely robust.
Memory sticks/pen drives:- It uses solid state technology to store several GBytes of data. It is usually connected to a computer through the USB port and power
to operate them is drawn from the host computer. They are small and very portable. Memory sticks and pen drives are used for transporting files between
computers or as a backup store. They are used a security device, a dongle, to prevent software piracy
Flash memory cards:- These are a form of electrically erasable programmable read only memory (EEPROM) and are another example of solid state memory.
They are used to store photos on digital cameras. Mobile phones use them as memory cards. They are also used in MP3 players to store music files. They are very
compact and robust.
Compact Disks (CDs):- The data is stored as a series of pits (equivalent to binary 1) and lands (equivalent to binary 0) in metallic optical layer. The pits are
formed by a laser beam etching the surface at the manufacturing stage. Only a single track exits which spirals out from the centre of the disk.
The pits and lands are read by a low-powered laser beam which follows the data stream and reads from the centre outwards in a spiral. The light reflects
differently off a pit than it does off a land and this interpreted a s1s and 0s.
DVDs:- DVDs can hold up to ten times the amount of data that a CD can store.DVD writers use a shorter wavelength of laser light than CD writers do, so the
pit on the disk surface is a lot smaller and more can be stored in the same space.
CDs and DVDs are cheaper and robust than hard disks but data transfer rates and access times for both are slower than hard disks.
Blu-ray:- These have largest capacity of all optical disks up to 100 GB or more. It uses a shorter wavelength for its laser beam, using light that is close to the
blue/violet spectra rather than the red light used by other optical devices. They are mostly used for storing films (movies)
1.3.4 Output Devices
Inkjet Printers:-
Description and Main Components The Working
The print head portion is made up of nozzles that spray tiny droplets of ink Data is sent to the printer driver. The driver makes sure that data is the
onto paper to form the characters. The ink comes from cartridges one for appropriate format for printing. It also makes sure that the printer is ready
colour and one for black. This ink can be formed from a thermal bubble and available. The data is sent to the printer buffer where it is stored whilst
(heat causes ink to vaporise forming a tiny bubble resulting in the ejection of ink) or waiting to be printed. After a sheet is fed to the printer the head starts moving
piezoelectric (in which a crystal is given a tiny charge resulting in vibration as result of from side to side printing the document. At each complete movement of the
which the ink is ejected). A motor moves a belt that moves the print head across head across the sheet of paper the sheet is moved a little so that printing can
the sheet of paper. The paper feed automatically feeds printer with paper be done on the next line. When buffer is empty more data is sent for printing
when required. with the help of an interrupt until there is no more.
Application:- INKJET PRINTERS are best for one-off photos or where only a few pages of good quality, colour printing are needed; the small ink cartridges or
small paper trays would not be an issue with such applications.
Laser Printers:-
Description and Main Components The Working
Unlike inkjet printer, laser printers print document using powders instead of This type of printer produces very high quality hard copy. It consists of drum
liquid ink. With the help of static electricity and heating these printers are that is electrically charged. A laser is used to change the charge on the drum
capable of printing documents at a much faster rate. Apart from the fact that for each dot of the output to be produced. Electrically charged toner is then
laser printers are capable of printing many more documents than inkjets, they attracted to the oppositely charged dots. The paper presses against the toner
are also capable of printing documents in one go. coated drum and is output with the pattern of dots required which is then
heated in order to permanently fuse the text/imagery. The page cannot be
printed until the whole document has been stored in a large buffer.
Application:- LASER PRINTERS produce high quality printouts and are very fast when making multiple copies of a document; any application that needs high-
volume printing (in colour or monochrome) would choose the laser printer (for example, producing a large number of high quality flyers or posters for
advertising) they have two advantages: they have large toner cartridges and large paper trays (often holding more than a ream of paper).
3D Printers:-
Description and Main Components The Working
3D PRINTERS are primarily used in COMPUTER-AIDED DESIGN (CAD) A design is created using a CAD software. The design is then exported in a
applications. They can produce solid objects which actually work. The solid format that is understandable by the printer. The 3D printer is set up to start
object is built up layer by layer (additive manufacturing) as opposed to removal printing. The object is then printed in thin layers. This can take up to several
of material to make an object (subtractive manufacturing e.g. carving of wood) hours depending on the size of the object. After printing the excess material is
using materials such as powdered resin, powdered metal, paper or ceramic removed and the object is left to settle for a few hours.
powder. Direct 3D printing uses inkjet technology in which the print head can
move in all directions. Binder 3D printing involves a powder type material
being sprayed first in the required shape followed by a glue that form a solid
layer.
Application:-This kind of printing is considered as the next industrial revolution. Possible applications include; prosthetic limbs, reconstructive surgery of body
parts, aerospace manufacturing using lightweight materials, fashion industry and even making objects that are no longer in production.
2D and 3D Cutters:- Both 2D and 3D cutters work in the same way being able to cut through various materials such as glass, crystal, metal and even wood
therefore being able to create intricate designs. However 2D cutters operate on “x” and “y” planes only whereas 3D cutters are capable of cutting through “x”,
“y” and “z” planes.
Actuators:- An actuator is an output device but it does not always provide output directly to the user. It can change some physical value in response to a signal
from an automated system or control system. Actuators naturally pair up with sensors, which can provide feedback to the control program about the effects of
its actuators.
Speakers:- Data is stored in digital form in computers. Therefore, to be able to create sound with the help of speakers, the sound has to pass through a DAC at
certain rate known as a “sampling rate”. To make these vibrations, speakers have a set of magnets. One of them is called the permanent magnet. It doesn’t move
or change polarity and is made of a magnetic metal like iron. The other magnet is an electromagnet. It is a coil of metal wire like copper or aluminum. When an
electric current is sent through the electromagnet, it is either attracted to or repelled away from the permanent magnet. The polarity of the coil can be reversed
depending on the current. This back and forth movement causes the diaphragm or cone to vibrate, because it is connected to the magnetic coil. This is the
sound that you hear.
LCD and LED:- LCD Short for liquid crystal display is a type of display used in digital watches and many portable computers. LCD displays utilize two sheets of
polarizing material with a liquid crystal solution between them. An electric current passed through the liquid causes the crystals to align so that light cannot pass
through them. Each crystal, therefore, is like a shutter, either allowing light to pass through or blocking the light. The LCD screen is more energy efficient and
can be disposed of more safely than a CRT. Its low electrical power consumption enables it to be used in battery-powered electronic equipment. LED (Short for
light emitting diode) is a flat-screen device in which an array of light-emitting diodes can be selectively activated by processor to display numerical
and alphabetical information ,used esp in pocket calculators ,digital timepieces, measuring instruments , and in some microcomputers.

DLP Projectors or digital light processing, uses tiny mirrors to reflect light toward the screen (an "on" pixel) or away (an "off" pixel). Most models use a color
wheel, literally a spinning wheel with color filters to create sequential color. Some high-end models use three DLP chips; one each for red, green, and blue.
DLP projectors range in price from a few hundred dollars to tens of thousands, and more. Most projectors in movie theaters use DLP.
LCD Projectors, which stands for liquid crystal display, is very similar to the technology found in most TVs. LCD projectors use three liquid crystal panels, each
tasked with creating an image using just one of the primary colors (red, green, and blue). All three are projected on the screen at once, so you see a full color
image.
LED vs. DLP projectors
 DLP is significantly more expensive than LCD, but requires less ongoing maintenance.
 LCD projectors are portable and lightweight.
 DLP quality is superior to LCD (although LCD is sufficient for most usage).
 Film, photography, highly detailed graphics and images, etc., will all appear crisper and brighter with DLP technology as compared to LCD.
CS 0478 Topic 1.3.7
People use many different languages to communicate with each other. In order for two people to understand each other they
need to speak the same language or another person, an interpreter, is needed to translate from one language to the other language.
Programmers use many different programming languages to communicate with computers. Computers only ‘understand’ their own
machine code. A program needs to be translated into machine code before it can be ‘understood’ by a computer.

Programming languages:-
What is a program?
Programs are our way of telling a computer what to do, how to do it and when to do it. This enables a single computer to
perform many different types of tasks. A computer can be used to stream videos, write reports, provide weather forecasts and many,
many other jobs. A COMPUTER PROGRAM is a list of instructions that enable a computer to perform a specific task. Computer
programs can be written in high-level languages or low-level languages, depending on the task to be performed and the computer to be
used. Most programmers write programs in high-level languages.
High-level languages:-
High-level languages enable a programmer to focus on the problem to be solved and require no knowledge of the hardware and
instruction set of the computer that will use the program. Many high-level programming languages are portable and can be used on
different types of computer. High-level languages are designed with programmers in mind; programming statements are easier to
understand than those written in a low-level language.
This means that programs written in a high-level language are easier to:
• Read and understand as the language used is closer to human language
• Write in a shorter time
• Debug at the development stage
• Maintain once in use.
The following snippet of program to add two numbers together is a single program statement written in a typical high-level language. It
shows how easy it is to understand what is happening in a high-level language program:
• Sum := FirstNumber + SecondNumber
There are many different high-level programming languages in use today including
• C++
• Delphi
• Java
• Pascal
• Python
• Visual Basic
• and many more.
Once a programmer has learnt the techniques of programming in any high-level language, these can be transferred to working in other
high-level languages.
Low-level languages:-
Low-level languages relate to the specific architecture and hardware of a particular type of computer. Low-level languages can refer to
machine code, the binary instructions that a computer understands, or an assembly language that needs to be translated into machine
code.
Assembly language:-
Few programmers write programs in an assembly language. Those programmers who do, do so for the following reasons:
• to make use of special hardware
• to make use of special machine-dependent instructions
• to write code that doesn’t take up much space in primary memory
• to write code that performs a task very quickly.

The above code written in assembly language will add two numbers together.
In order to understand this program the programmer needs to know that
• LDA
– means load the value of the variable into the accumulator
• ADD
– means add the value of another variable to the value stored in the accumulator
• STO
– means replace the value of the variable by the value stored in the accumulator.
The above words are referred to as mnemonics.

Hassan Zulfiqar Haider


[email protected]
0323414090 Page 1
CS 0478 Topic 1.3.7
Machine code:-
Programmers do not usually write in machine code as it is difficult to understand and it can be complicated to manage data
manipulation and storage.

The above code is a portion of a program to add two numbers together is written in typical machine code, shown in both hexadecimal
and binary. As you can see, this is not easy to understand in binary! Machine code is usually shown in hexadecimal
Translators:-
Computer programs can exist in several forms. Programs are written by humans in a form that people who are trained as computer
programmers can understand. In order to be used by a computer, programs need to be translated into the binary instructions, or
machine code, that the computer understands. Humans find it very difficult to read binary (hexadecimal is easier to understand) and
computers can only perform operations written in binary. A program must be translated into binary before a computer can use it; this is
done by a utility program called a translator. There are several types of translator program in use; each one performs a different task

Compilers:-
A COMPILER is a computer program that translates a program written in a high-level language (HLL) into machine code so that it can
be directly used by a computer to perform a required task. Once a program is compiled the machine code can be used again and again to
perform the same task without recompilation
The high-level program statement…

…becomes the following machine code instructions when translated

Interpreters:-
An INTERPRETER is a computer program that reads a statement from a program written in a high-level language, performs the action
specified and then does the same with the next statement and so on.
Assemblers:-
An ASSEMBLER is a computer program that translates a program written in an assembly language into machine code so that it can be
directly used by a computer to perform a required task. Once a program is assembled the machine code can be used again and again to
perform the same task without re-assembly.
The assembly language program statements…

…become the following machine code instructions when translated

Hassan Zulfiqar Haider


[email protected]
0323414090 Page 2
CS 0478 Topic 1.3.7
Compiler Interpreter Assembler

Translates a high-level language Executes a high-level language Translates a low-level language


program into machine code. program a statement at a time program into machine code.

An executable file of machine code No executable file of machine code An executable file of machine code
is produced is produced. is produced.

One high-level language statement One high-level language program One low-level language statement is
can be translated into several statement may require several usually translated into one machine
machine code instructions machine code instructions to be code instruction
executed.
Compiled programs are used Interpreted programs cannot be used Assembled programs can be used
without the compiler. without the interpreter. without the assembler

A compiled program is usually An interpreter is often used when a An assembled program is usually
distributed for general use. program is being developed. distributed for general use.

What happens when things go wrong?


As programs are written by humans, they may contain errors. There are several different types of error.
• A SYNTAX ERROR
– Is where a program statement doesn’t obey the rules of the programming language. A program cannot be translated if
it contains syntax errors.
• A LOGIC ERROR
– Is where the program doesn’t do what the programmer wanted it to do. Logic errors are found when a program is
being run.
Syntax errors:-
When a program is being compiled, if any syntax errors are found no translated program is produced. Instead, a list of all the errors in
the whole program is produced. The programmer corrects these errors and recompiles the program.
When a program is being interpreted, the interpreter performs the actions specified by each statement until a syntax error is
found. The programmer is then alerted to the place in the program where the error was found. The error is corrected by the programmer
and the interpretation continues until the next error is found or the task is completed.
Logic errors:-
When a program is being run, if it doesn’t do what it should do there is a logic error. These can be found by tracing what the
program does and using test data with expected results. Trace Tables in flowcharts is a good example of this process.
Using an Integrated/Interactive Development Environment (IDE):-
Most high-level programming languages offer the use of an IDE for program development. This contains an editor with an
interpreter and/or compiler together with debugging tools, which can improve the speed of program development.

Python IDE

Hassan Zulfiqar Haider


[email protected]
0323414090 Page 3
1.3.6 Operating Systems
Operating Systems:-
An operating system (OS) is a set of programs that controls how the hardware of a computer system works. It is a “gateway” between the user and computer
hardware and software. The OS manages the computer hardware and software resources and provides common services for the computer programs. The OS is
an essential component of the system software of the computer system. Application programs usually require an operating system to function.
The OS acts like a bridge between the application software and the computer hardware. Users need
applications software to carry out various tasks. The Software needs the OS to communicate with the
hardware. Some of the most important functions of an Operating System Include:-
- Accepting data from input devices and transferring it to computer memory.
- Making sure that the data is sent to the appropriate output device.
- Managing the transfer of data back and forth the computer memory.
- Allocating memory and other resources to programs and data.
- Controls the loading and running of applications.
- Provides multi programming and multi user capabilities.
- Manages security.

User Interface:- Users make use of a system known as (User Interface) that allows them to interact with the computer. There are two types:-
- Graphical User Interface
- Command Line Interface
Graphical User Interface (GUI) Command Line Interface (CLI)
Description:- Description:-
It is built around a collection of visual objects which include:- They do not provide visual elements to their users. Instead the user interacts
- Windows:- regions of the screen to display info. with the system using commands which are to be typed in on a black screen.
- Icons:- small pictures that represent folders and sw. The user will have to learn a wide range of commands to be able to effectively
- Menus:- a list of options that the user can select. use the system.
- Pointer:- is an arrow that be moved around to select various visual
objects.
Advantages:- Advantages:-
Are very easy to use due to their visual nature. CLI is very light weight and does not require powerful processors due to their
lack of visual elements.
Disadvantages:- Disadvantages:-
Due to their graphics, powerful computers are needed to run them. GUI is Commands are very difficult to use. Only meant for expert users.
very resource hungry.
Single-tasking OS:- This type of OS allows the running of only program at a time. (not used any more)
Multiprogramming OS:- This type of OS holds more than one program in memory. There are two types of Multiprogramming OS 1) Multitasking OS 2)
Multiuser OS.
- Multitasking OS:- The OS swaps programs in and out of the memory when needed.
- Multiuser OS:- This type of OS allows multiple users on different networks to be connected using some network to share processing time of a central
computer. The OS switches back and forth between different users giving each user a “time slice” of processing time.
Batch Operating System:- The Users of a Batch OS do not interact with the OS directly. Instead these users, prepare their inputs separately and hand them
over to a computer operator. The computer operator then proceeds to process these inputs once when a certain number of inputs have been arranged or if a
certain amount of time has passed. For example, processing utility bills at the end of the month after meter reading staff has provider their inputs.
Real Time Operating System:- Such data processing systems are used in control environments. As a result of which the time taken for processing an input is
very small. The response time (the time taken from receiving input to updating the system) is very small. For e.g. EFU controller of a car, heart rate monitoring
system.
Transaction Processing system:- The input is noted by the computer, but deals with them after a short delay. Meanwhile, it handles other inputs and data
management. The delay is short but considerably longer than real time processing. For example, booking flight tickets, ATM.
Interrupts:- An Interrupt is a signal sent from a device attached to a computer of from a program within the computer that causes the OS and CPU to stop
what it is doing and attend to the device/software sending the signal. Today all computers (large or personal) are interrupt driven. Opposed to the Polling
technique in which the CPU wastes valuable clock cycles prompting hardware/software if it needs services of the CPU. Interrupts are used all over the
computer, such as with devices such as printer or keyboard (in which each key stroke generates an interrupt).
Interrupt Service Routine:- Interrupt are handled using the Interrupt Service Routine. The Operating systems has smaller software component that is referred
to as the Interrupt Handler. Consider the following ISR for when a mouse moves:-
1. Mouse moves.
2. A hardware chip on the motherboard called the Interrupt Controller detects the mouse signal.
3. The Interrupt controller issues an interrupt signal and sends it the CPU.
4. Upon receiving the signal the CPU copies its registers’ content on a stack located on the main memory so that it can return to what it was doing
after dealing with the interrupt.
5. The CPU then starts executing the Interrupt Service Routine by moving the cursor image to the new location on screen and also responding to
any mouse clicks (if any).
6. After the ISR is completed, the CPU reloads the register values from the stack to carry on what it was doing before the interrupt.
It is the responsibility of the Interrupt handler prioritizes interrupts and arranges them in a queue while multiple interrupts are waiting to be dealt with.
Interrupts can Hardware Interrupts (such as an I/O operation) and Software Interrupts (such as a software requesting services of an OS). A Timer Interrupt is
generated by an internal clock indicating that the processor must attend to time critical activities.
CS 0478 Topic 1.4

1.4.1 Importance of security and data integrity:-


Data Security covers all activities related to keeping data safe.
It may include
• Prevention of unauthorized access.
• Intentional or Unintentional Damage or Corruption.
Data loss in the form of being recovered, copied, stolen and damage from computer systems may result in serious concerns for
companies.
Data Integrity:-
Data integrity is the maintenance of, and the assurance of the accuracy and consistency of, data over its entire life-cycle, and is a critical
aspect to the design, implementation and usage of any system which stores, processes, or retrieves data.
Possible Risks to Data:-
• Lost or damaged as a result of system crash or hard disk damage.
• Data corruption due to hardware fault or power failure.
• Data loss due to being overwritten both intentionally or accidently.
• Data Loss or Data Corruption due to a computer virus.
• Data being deleted or altered as a result of hacking.
• Data loss as a result of natural disasters, such as hurricanes and even fires.
• Data loss as a result of an act of terrorism.
• Data may be altered by employees seeking to cause harm to the company.
1.4.2 How is data kept safe?
Sensible companies and organisations take appropriate measures to ensure that the data they store remains secure. The most appropriate
measures to use will depend on:
• How important the data is.
• How confidential the data is.
• How likely it is that someone will want to steal, change or destroy the data.
If the stored data relates to identifiable individuals then a company must keep data secure to comply with the Data Protection Act. Some
of the more common measures used to ensure data security are described below.
• Making regular backups of files (backup copies should be stored in fireproof safes or in another building)
• Protecting yourself against viruses by running anti-virus software
• Using a system of passwords so that access to data is restricted.
• Safe storage of important files stored on removable disks, eg locked away in a fireproof and waterproof safe

Hassan Zulfiqar Haider


[email protected]
0323414090 Page 1
CS 0478 Topic 1.4
• Allowing only authorised staff into certain computer areas, eg by controlling entry to these areas by means of ID cards or
magnetic swipe cards
• Always logging off or turning terminals off and if possible locking them
• Avoiding accidental deletion of files by write-protecting disks
• Using data encryption techniques to code data so that it makes no apparent sense
Types of Protection:-
• Physical Protection
• Software Protection
Physical Protection:-
As you have seen, there are many different ways that you or a business can lose valuable data. With a little bit of planning and thought
however, the risks can be reduced or even eliminated. There are many things you can do to make your equipment more secure:
• Lock the room when not in use
• Use swipe cards or keypads to activate locks
• Bolt computers to the desk
• Use special pens to mark your postcode onto the computer case
• Keep windows shut especially if on the ground floor. Use bars.
• CCTV video cameras
Safe Storage of Data :-
Important data should be stored safely. Good quality disks or tapes should be used. These should be kept in a dust-free environment that
is not too hot and is nowhere near any magnetic fields. Often important data is kept in fireproof, waterproof safes.
Limiting Physical Access to Computers:-
Access to a computer system can be limited by keeping the system in a locked room. Unauthorised people should not be able to access
the computers.
• This would not however stop an employee who had the authority to access the computer room from causing deliberate or
accidental damage or stealing important data.
• A further limitation of this solution is that it is not always possible to limit access to a computer system physically.
Some systems, such as the Automatic Teller Machines (ATMs) used by banks to dispense money have to be available for the public to
use. Also, many computers are connected to networks and can be accessed from other computers on the network.
Biometrics:-
Biometrics means to measure and analyse some human characteristic in order to correctly identify an individual. Examples of physical
characteristics which can be used are:
• fingerprints
• voice patterns
• retinas or irises
• facial patterns
• palm prints
To use biometrics an organisation needs:
• A reader or scanning device that takes a biometric reading from a person
• Software that can convert the scanned information into digital format for the computer to use.
• This computer identifies the 'match points' from the digital information
• Once the match points have been identified the data is compared to all of the records held in the company biometric database.
• If a matching record is found the individual can be positively identified.
Software protection:-
Firewall
A firewall is a program or hardware device that filters the information coming through the Internet connection into your personal
computer or into a company's network. It is set up to allow mainly one way access, i.e. you can go out onto the Internet and access pages,
but it checks everything coming back against a set of rules. If the data coming back is from an unauthorised source, then it is blocked.
You may have heard people saying, 'I can't get on that site at school because it's been blocked'; that is the firewall in action.
Firewalls use 3 types of filtering mechanisms:
• Packet filtering or packet purity:-
• Data flow consists of packets of information and firewalls that analyze these packets to sniff out offensive or unwanted
packets depending on what you have defined as unwanted packets.
• Proxy
• Firewalls in this case assume the role of a recipient & in turn sends it to the node that has requested the information
& vice versa.

Hassan Zulfiqar Haider


[email protected]
0323414090 Page 2
CS 0478 Topic 1.4
A PROXY SERVER is a dedicated computer or a software system running on a computer that acts as an intermediary between an endpoint device,
such as a computer, and another server from which a user or client is requesting a service. The proxy server may exist in the same machine as a firewall
server or it may be on a separate server, which forwards requests through the firewall.

Firewalls can be customised using the following methods based on their threat levels:-
You can create or disable firewall filter rules based on conditions such as:
• IP Addresses
Blocking off certain IP addresses, which you think are harmful.
• Domain names:-
You can only allow certain specific domain names to access your systems/servers. Or even specify the types of
domains such as .edu or .org
• Protocols:-
A firewall can decide which of the systems can allow or have access to common protocols like TCP/IP, FTP
or UDP.
• Ports:-
Blocking or disabling ports of servers that are connected to the internet will help maintain the kind of data
flow you want to see it used for & also close down possible entry points for hackers or malignant software
• Keywords:-
Firewalls also can sift through the data flow for a match of the keywords or phrases to block out offensive or
unwanted data from flowing in

User Name and Password Security Systems


If a password system is in use then before you can access a computer system you must enter a valid user name and password. The process
of entering this information and being granted (or refused) access to a computer is known as logging on. Passwords can be cracked
(guessed) therefore it is important that:-
• Change your password regularly.
• Make your password at least eight characters long.
• Do not write down your password or tell it to anyone else.
• Do not use proper words of phrases - these can be found using a dictionary cracker.
• Use a mixture of upper and lower case letters and numbers.
Attempting to guess a password to gain unauthorised entrance to a computer system is an offence under the Computer Misuse Act 1990.
As with limiting physical access to a computer system, the use of a password system will not prevent authorised users such as employees
from damaging or stealing data.
Access Rights should be defined:-
A user should only be given access to files that he or she needs to use. Limiting the files that a user can access will limit the amount of
damage that he or she might do either deliberately or accidentally.
Logs/audit log files:-
One effective way of deterring authorised users from damaging or stealing data from a computer system is to get the system to keep logs
of all of the actions that each user carries out. A log must be used together with a user name and password system. All of the actions that
a user carries out are stored together with their user name in a log. If data is deleted, copied or changed the computer system manager
can identify the person responsible by examining the logs.
User Date and Time Action

Anas 27/04/2017 09:54 Log In

Munhib 27/04/2017 09:55 Deleted File “xyz”

Ahmed 27/04/2017 09:56 Copied File “abc”


Sample Audit file
Taha 27/04/2017 10:00 Checked email

If users know that their actions are being monitored then they are less likely to deliberately damage or steal data. Logs can also be used to
help trace any accidental damage to data. A log cannot stop a person from damaging or stealing data but it can help identify the culprits

Backups:-

Hassan Zulfiqar Haider


[email protected]
0323414090 Page 3
CS 0478 Topic 1.4
Whatever measures are implemented to try and avoid data being deleted or changed, it is impossible to guarantee that this will not
happen. Therefore it is vital that extra copies are made of important data. For important data a regular backup procedure should be
implemented. Backups should be kept away from the computer room so that they will not be damaged by fires / floods etc. There is no
point in keeping a backup if it is likely to get damaged when the original data gets damaged. The type of backups that are kept usually
depend on the type of processing being carried out:-
• Batch Processing systems use the Grandfather-Father-Son or Ancestral backup system.
• With Transaction Processing systems a regular backup of the master file is made. As transactions are carried out details of each
transaction are stored in a transaction log file. If the master file becomes corrupted the latest backup master file and the
transaction log file can be used to recreate it.
• In Real-Time systems there is often little point in keeping backups of data. However much backup hardware is used to reduce
the likelihood of the system failing. Sometimes backing up data to disk can be useful in real-time systems.
• Although this data could not be used to put the system back into its proper state, it could be used to analyse why a
system failed. e.g. an aeroplane "black box".
SSL:-
SSL stands for 'Secure Socket Layer'. It is a web browser security technology. SSL is built into a web browser. SSL allows confidential data
to safely pass from your web browser to a distant server via the Internet. The confidential data is 'encrypted' or scrambled so that only the
server can read it. For example, e-commerce shops use SSL to keep your credit card details secret. You can tell when SSL is being used as
a small padlock appears on the bottom right of the browser window. If you click on the padlock, a 'certificate' window appears that
confirms you are connected to the real server and not a fake one.

Accessing a website using SSL

Transport Layer Security (TLS):-


It is similar to SSL but is a more recent security system. TLS is a form of protocol that ensures the security and privacy of data between
devices and users when communicating over the internet. It is essentially designed to provide encryption, authentication and data
integrity in a more effective way than its predecessor SSL. TLS is formed of two layers:
• Record protocol: This part of the communication can be used with or without encryption (it contains the data being
transferred over the internet).
• Handshake protocol: This permits the website and the client (user) to authenticate each other and to make use of encryption
algorithms (a secure session between client and website is established)
Encryption:-
Encryption ensures that data being sent across a network is kept secure. Before data is sent, it will be encrypted to the point that it will
not be recognisable if intercepted during transmission. An algorithm is used to scramble the data and this is known as encoding. Once
the data gets to the destination system it must be decoded (unscrambled). For this system to work it is necessary to use encryption keys.
Encryption keys contain code that has been generated using an algorithm. This code is used to encrypt and decrypt data.

Hassan Zulfiqar Haider


[email protected]
0323414090 Page 4
CS 0478 Topic 1.4
There are two methods of key encryption:

• Symmetric key encryption using one secret key:-


Symmetric key encryption is an encryption system in which the sender and receiver of a message share a single,
common key that is used to encrypt and decrypt the message. The success of this method of encryption depends on the need to
keep the key secret and on the method for passing the key from one system to another. If the receiving system does not know
the secret key, then it cannot decrypt the message.

There is also a very big risk of interception. If the secret key is sent across a network and this key is intercepted, then a
hacker is able to decrypt the data as they have possession of the secret key.

Despite these issues, symmetric encryption is reliable and allows for fast decryption. It is still a very popular method of
encryption and is used by many large organisations to manage the transmission of online communication. Symmetric key
encryption is simple and fast but its main drawback is that the two parties must somehow exchange the key in a secure way.

This problem is overcome by using public and private key encryption to transfer the symmetric key before then using
the symmetric system to transfer data. In order to transfer the symmetric key securely, public and private key encryption is often
used.

• Public key (asymmetric) encryption using two keys - one public key and one private key:-
Public key encryption is used to transfer data but is actually often used to transfer the key needed to allow symmetric
encryption to take place. This is because symmetric encryption is a much faster method than using public and private keys.
Public keys are keys that are unique to a user profile on an operating system and are available to all systems trying to
communicate with the user’s computer.

If a message has to be sent to the user’s computer, then the public key that matches their profile is used to encrypt the
data. Private keys are also unique to a user profile when running an operating system but are not available to any other
computers and are not transferred from system to system. This means, with private keys there is no risk of interception. If an
operating system receives a public key, it needs to use its own private key to decrypt the data. If the public key it has received
was actually intended for another system, the private key will not be able to decode the data. If the public key it receives is its
own public key, then the private key will decode the data.

When system A wishes to send a secure message to system B, it will use system B’s public key to encrypt the data.
System B then uses its own private key to decrypt the data.

Using public and private keys to exchange symmetric keys securely is a very common occurrence. Symmetric keys are
then used to transfer the actual data.

Hassan Zulfiqar Haider


[email protected]
0323414090 Page 5
CS 0478 Topic 1.4

1.4.3 Need of keeping online systems safe


We need to keep online systems safe from attacks including
• denial of service attacks
• Phishing (already discussed section 1.5)
• Pharming (already discussed section 1.5)
Denial Of Service (DoS) Attacks:-
DoS stand for Denial of Service. A malicious hacker uses a DoS attack to make a computer resource (i.e. – website, application, e-mail,
voicemail, and network) stop responding to legitimate users. The malicious hacker does this by commanding a fleet of remotely-
controlled computers to send a flood of network traffic to the target. The target becomes so busy dealing with the attacker’s requests that
it doesn’t have time to respond to legitimate users’ requests. That can cause the target system to stop responding, resulting in long delays
and outages.
1.4.4 Internet Security for Real Life Scenarios
Online Banking:-
When you bank online, after you’ve logged in, you will notice that the http in the address bar has changed to https. This indicates that a
secure connection between your computer and the bank's computer has been established. Data sent between the two computers is
encrypted so that anyone trying to intercept your data will receive meaningless data. The data can only be decrypted into readable data by
using a key that is known only to the two computers - yours and the bank's.
Online Shopping:-
• Don't shop at a site if you're not comfortable with the website.
• Never click on links from spam emails to make purchases.
• Check the web address to make sure you are on the correct site.
• Check that the site is secure.
• Use a credit card or an online payment service.
• Do not use a public computer to shop online.
• Only use a secure connection when you place your order.
• Use strong passwords.

Hassan Zulfiqar Haider


[email protected]
0323414090 Page 6
CS 0478 Topic 1.5

What is Ethics?
Ethics is a set of moral principles that govern the behavior of a group or individual. Therefore, computer ethics is set of moral
principles that regulate the use of computers.
Some common issues of computer ethics include
• Intellectual property rights (such as copyrighted electronic content)
• Privacy concerns,
• How computers affect society.
For example, while it is easy to duplicate copyrighted electronic (or digital) content, computer ethics would suggest that it is wrong to do
so without the author's approval. And while it may be possible to access someone's personal information on a computer system,
computer ethics would advise that such an action is unethical.
Ethical behavior is not necessarily related to the law.
• For example, just because something is not against the law doesn't mean it is okay to do it.

Philosophers today usually divide ethical theories into three general subject areas:
• Met ethics:-
• Met ethics investigates where our ethical principles come from, and what they mean. Are they merely social
inventions?
• Normative ethics:-
• Normative ethics takes on a more practical task, which is to arrive at moral standards that regulate right and wrong
conduct.
• Applied ethics:-
• Finally, applied ethics involves examining specific controversial issues, such as abortion, infanticide, animal rights,
environmental concerns, etc.
(you do not have to memorise this…this is just for information)

Computer Ethics and Society:-


There are a number of laws enacted to protect society from illegal behavior unfortunately, computer systems also raise ethical issues and
yet they are not all part of the law. For example,
“Imagine a company that has employed a number of workers for years on their assembly line. Then a new computerised robot system becomes available
that will do the work of half of them. The new system will work 24 hours a day, without a break, without sick leave, absences or overtime. From a
business point of view it makes sense to install the new system. But ethically the company also has an obligation to the displaced workers. Of course,
there are employment laws to protect worker rights, but some companies may choose to go beyond those from an ethical point of view.”
Other ethical issues include:-
• Computing and privacy:- “who keeps what, when, for how long ?”
• Responsibility of computer professionals “being honourable engineers.”
• Computing and disability “need to include as many people as possible.”
• Computing and political freedom “ethics can raise some very tough questions”

Computer ethics is concerned with the procedures, values and practices that govern the process of consuming computing technology and
its respective disciplines without harming or violating the moral values and beliefs of any personal, organization or entity.

“Computer ethics can be understood as that branch of applied ethics which studies and analyzes social and ethical impact of
information technology.”

Hassan Zulfiqar Haider


[email protected]
0323414090 Page 1
CS 0478 Topic 1.5

The Ten Commandments of Computer Ethics:-


The Ten Commandments of Computer Ethics were created in 1992 by the Computer Ethics Institute. The commandments were
introduced in the paper "In Pursuit of a 'Ten Commandments' for Computer Ethics" by Ramon C. Barquin as a means to create "a set of
standards to guide and instruct people in the ethical use of computers.“ They follow Internet Advisory Board's memo on ethics from
1987. The Ten Commandments of Computer Ethics copies the archaic style of the Ten Commandments from the King James Bible.
(You do not have to memorise this…this is just for information)

The Ten Commandments:-


1. Thou shalt not use a computer to harm other people.
2. Thou shalt not interfere with other people's computer work.
3. Thou shalt not snoop around in other people's computer files.
4. Thou shalt not use a computer to steal.
5. Thou shalt not use a computer to bear false witness.
6. Thou shalt not copy or use proprietary software for which you have not paid (without permission).
7. Thou shalt not use other people's computer resources without authorization or proper compensation.
8. Thou shalt not appropriate other people's intellectual output.
9. Thou shalt think about the social consequences of the program you are writing or the system you are designing.
10. Thou shalt always use a computer in ways that ensure consideration and respect for your fellow humans.

Computer Ethics in an Engineering Perspective:-


Professional organisations such as the IEEE and the ACM recognise that engineers have an obligation to act in an ethical manner when
designing or developing computer systems. They have put together a set of 8 principles as a guide:-
PUBLIC:
Software engineers shall act consistently with the public interest.
CLIENT:
Software engineers shall act in a manner that is in the best interests of their client and employer, consistent with the public
interest.
PRODUCT:
Software engineers shall ensure that their products and related modifications meet the highest professional standards possible.
JUDGEMENT:
Software engineers shall maintain integrity and independence in their professional judgment.
MANAGEMENT:
Software engineering managers and leaders shall subscribe to and promote an ethical approach to the management of software
development and maintenance.
PROFESSION:
Software engineers shall advance the integrity and reputation of the profession consistent with the public interest.
COLLEAGUES:
Software engineers shall be fair to and supportive of their colleagues.
SELF:
Software engineers shall participate in lifelong learning regarding the practice of their profession and shall promote an ethical
approach to the practice of the profession.
Software Copyrights:-
Software copyright is used by proprietary software companies to prevent the unauthorized copying of their software. Free and open
source licenses also rely on copyright law to enforce their terms.
Copyright VS Copyleft:-
Copyleft is a form of licensing and can be used to maintain copyright conditions for works such as computer software, documents, and
art. In general, copyright law is used by an author to prohibit others from reproducing, adapting, or distributing copies of the author’s
work. In contrast, under copyleft, an author may give every person who receives a copy of a work permission to reproduce, adapt or
distribute it and require that any resulting copies or adaptations are also bound by the same licensing agreement. Copyleft licenses (for
software) require that information necessary for reproducing and modifying the work must be made available to recipients of the
executable. The source code files will usually contain a copy of the license terms and acknowledge the author(s).
Plagiarism:-
Plagiarism is passing off somebody else's work as your own. If someone is caught plagiarising, they automatically fail the course. Authors
don't mind being quoted, as long as their name is mentioned whenever they are quoted. The author should also be included in the
bibliography. Whenever you use words straight from a text, you should put quotation marks around them, and give a reference to show
where the text came from. If you don't include references for original text, you'll be guilty of plagiarism.

Hassan Zulfiqar Haider


[email protected]
0323414090 Page 2
CS 0478 Topic 1.5
Copyright Plagiarism
One who violets copyright breaks laws that protect the right of One who plagiarizes breaks a moral code by claiming credit for
the creator of an original work. the work of someone else.

Violation of copyright law may results in fines, imprisonment or Plagiarism may result in academic dismissal or loss of job.
both.
Freeware, Shareware and Free Software (Open Source):-

Open Source Software (Advantages):-


Cheaper than commercially According to studies, open source software collectively help business owners save around $60
marketed products. billion a year. This might seem unbelievable at first, but it’s not really surprising since these
programs are developed to be accessible to anyone (especially those who can’t afford to buy
commercial products).
Created by skillful and Large and well-established software companies have the financial capability to hire the best talent
talented people in the business to create their products. Because of this, many people opt to buy computer
programs from these firms because they think they’ll get great value for their money by doing so.
Highly reliable There are two main reasons why open source software are reliable. First of all, they’re developed
chiefly by skillful and talented experts who do their best to create high-quality programs. Second,
they’re worked on by tens or hundreds of people, which means there are numerous eyes that can
monitor for the presence of bugs and many pairs of hands that can fix these defects within the
shortest amount of time.
Help you become more Since you’re not tied to a proprietary product, you don’t need to abide by a specific design that
flexible. might require you to upgrade your software and even hardware often. Rather, you can mix and
match your software and create a unique setup that best suits your needs
Open Source Software (Disadvantages):-
Vulnerable to malicious Many people have access to the source code of open source software, but not all of them have
users. good intentions. While a lot of people utilize their access to spot defects and make
improvements to the program, others use this privilege to exploit the product’s vulnerabilities
and create bugs that can infect hardware, steal identities or just annoy other users.
Might not be as user-friendly This is not true for all open source software since many of them (such as LibreOffice, Mozilla
as commercial versions. Firefox and the Android operating system) are incredibly easy to use. However, there are several
programs which are created mainly to cater to the developer’s wishes and bring his ideas to life.
As a result, not much attention is given to the software’s user interface, making it difficult to use
especially for those who aren’t really tech-savvy.
Don’t come with extensive Those who favor commercially produced programs say that these software gives them peace of
support. mind. After all, since they know exactly who designed, created and distributed the product, they
have a clear idea of who they can hold liable if the program doesn’t function properly or causes
damage to their hardware. This isn’t exactly the case for open source software. Since it’s
developed by numerous people, users exactly don’t have a specific person or company they can
point a finger to.

Hassan Zulfiqar Haider


[email protected]
0323414090 Page 3
CS 0478 Topic 1.5
ETHICAL ISSUES OF ELECTRONIC COMMUNICATION:-
• We Will be discussing:-
• Hacking
• Cracking The following diagrams are
• Viruses
organised in this way
• Phishing
• Pharming
• Wardriving
• Spyware

Hacking:-

Types of Hackers:-
White Hat Hackers Grey Hat Hackers Black Hat Hackers
People who Specialise hacking to Exploit the systems security to gain People who break into networks and
check the system faults. the attention of the owners. harm to the network and property.
They are the good guys. Also known
as ethical hackers.

Hacking Vs Cracking:-
Note the difference between CRACKING and HACKING. Hacking is breaking into a computer system to steal personal data without
the owner’s consent or knowledge (e.g. to steal a password file). Cracking is where someone edits a program source code (i.e. looks for a
‘back door’ in the software so that the code can be exploited or changed for a specific purpose). This is usually done for a malicious
purpose (e.g. legitimate software could be altered by a cracker to perform a different task e.g. send a user to a specific website).
Essentially, hacking isn’t necessarily harmful whilst cracking is ALWAYS totally illegal and is potentially very damaging.

Hassan Zulfiqar Haider


[email protected]
0323414090 Page 4
CS 0478 Topic 1.5
Viruses:-

• A computer virus is a program that attaches itself to an application or "host file" and then spreads by making copies of it. Some
type of human action (e.g. opening an attachment) is always required for a virus to take effect. Once a virus gets onto your
computer it might modify, delete, or steal your files, make your system crash, or take over your machine.
• A computer worm is like a virus, but it infects other computers all by itself, without human action and without a host file. It
usually infects other computers by sending emails to all the names in your email address book.
• A Trojan horse is a program that tricks you into running it by appearing useful or harmless. However, once it is run, it damages
your computer, usually by providing "back door" access to the computer. This allows hackers to control or use your computer,
destroy or steal files, install viruses or spyware, or run arbitrary programs.
• A root kit is a program that allows an intruder to gain access to your system without your knowledge by hiding what it is doing
on the system. The intruder can then install difficult-to-detect back doors into your system to seize control.
Phishing:-

Hassan Zulfiqar Haider


[email protected]
0323414090 Page 5
CS 0478 Topic 1.5
Pharming:-

Wardriving:-

Spyware:-

Hassan Zulfiqar Haider


[email protected]
0323414090 Page 6
CS 0478 Topic 1.5
Best Practices:-

 Only perform file transfers from trusted sources:


This reduces your risk of downloading files infected with malware and introduces accountability, so that you have a better
chance of getting a response if you do have a problem.

 Scan all files that you receive through file transfer:


It is a good idea to scan the files that you receive from P2P networks with your anti-virus software to detect malware. This may
slow down the transfer, but it will help keep your computer safe.

 Check a corporate wireless network's security level before connecting:


Many corporate networks allow users to connect their wireless devices to the network. However, not all of these networks are
secured. In fact, it is quite easy for a user to connect his/her wireless device to a corporate network without getting permission
first. When this happens, the user may intentionally or unintentionally transfer viruses onto the company network, putting
everybody on the network at risk. You should make sure your corporate network is secure before connecting your own device. If
users can connect to your company’s network without getting permission or a password, it’s probably not a good idea to
connect to that network at all.
 Make sure the public network you connect to is secure:
Many public networks are not secure and do not even require you to identify yourself with a password. Not only do you run the
risk of being infected by malware from other users on such a network, you may unintentionally transmit malware to them as
well. Make sure you only connect to secured networks that ask users for a password.

Hassan Zulfiqar Haider


[email protected]
0323414090 Page 7
Logic Statements:-
You should understand the difference between Simple Logic, Complex Logic and Nested IF Statements.
PRINT “enter a positive number”
INPUT number This is a simple condition
If number > 0 In which case it is only determining is the
if number > 10 number is positive.
then
print “this number is greater than 10” This is a nested if statement as it is part
else if number>=5 and number<=10 of another if statement (i.e. number>0).
then
print “this number is between 5 and 10 (inclusive)” This is a complex condition as it is taking
else in account of two conditions.
print “this number is less then 5” (number>=5 and number<=10) and since
else there is an “and” operator in between the
print “this number is not positive” two condition, both sub-statements have
to be true for this statement to be true.
Case…OF…OTHERWISE…ENDCASE
input choice
case of choice A variable “choice” will hold some value which
1: print “Have fun” is to be investigated and only one statement is
2: print “good luck” to be executed based on the contents of choice.
3: print “good night” Of the input is among 1..4 then the
4: print “good bye” corresponding statement will execute.
otherwise: However, if anything else in the “choice” then
Print “you have not selected a valid option” the default condition will execute.
end case
Loops:-
We will be solving the following problem using different
types of loops:-
“take 10 numbers as input and output the largest
number”
FOR…TO…NEXT…ENDFOR REPEAT…UNTIL WHILE…DO…ENDWHILE

INPUT BiggestSoFar INPUT BiggestSoFar INPUT BiggestSoFar


FOR Counter ß 1 to 9 REPEAT WHILE Counter < 9
INPUT NextNumber INPUT NextNumber INPUT NextNumber
IF NextNumber>BiggestSoFar IF NextNumber>BiggestSoFar IF NextNumber>BiggestSoFar
THEN THEN THEN
BiggestSoFar ßNextNumber BiggestSoFar ßNextNumber BiggestSoFar ßNextNumber
END IF END IF END IF
NEXT Counter ß Counter + 1 Counter ß Counter + 1
END FOR UNTIL Counter = 10 END WHILE
PRINT BiggestSoFar PRINT BiggestSoFar
For Loop is an Unconditional Loop which Repeat Until loop is a Post Conditional While Loop is a Pre Conditional Loop.
means that is will run the defined number Loop. There are no defined number of steps There are no defined number of steps and
of time no matter what. i.e. 9 times (counter the loops terminates when the condition the loops terminates when the condition
1 to 9). tested after each step becomes true. In this tested before each step becomes false. i.e
The statements between FOR and ENDFOR case that condition is Counter = 9. In which Counter<9. In which case if we start counter
are to be repeated 9 times. case if we start counter at 0 this program will at 0 this program will run 10 times before
run 10 times before exiting loop. exiting loop.
A rogue value is a value used to terminate a sequence of values. The rogue value is of the same
data type but outside the range of normal expected values.

BiggestSoFar ß 0 This algorithm works even if the sequence consists


REPEAT of only one non-zero input. However, it will not
INPUT NextNumber work if the only input is 0.
IF NextNumber>BiggestSoFar
THEN
BiggestSoFar ßNextNumber
END IF
UNTIL NextNumber = 0
PRINT BiggestSoFar
If the rogue value is entered the
Repeat Until statement will still
execute its statements whereas the
While Loop will not as it tests its
condition before entering the loops
statements.
Working with Arrays:-
This 1D array is given an identifier, for example MyList, and each element within the
array is referred to using this identifier and its position (index) within the array. For
example, MyList[4] refers to the fourth element in the MyList array.

Arrays are data structures that store the same type of data usually in random order.

Temp ßMyList[6]
MyList[6]ßMyList[3]
MyList[3]ßTemp
Swapping two values in an array

PRINT MyList[1] //prints 25


INPUT MyList[5] // overwrites 41 with whatever is being input

FOR count 1 to 7
PRINT MyList[count]
NEXT
END FOR //index position changes from count 1 to 7
//and prints all elements in array. 25,34,98…
Step Wise Refinement refers to the process of splitting a problem into smaller sub problems. These sub problems are then divided into even
smaller sub problems until each problem represents just one element of the final program.
Sub problems can be referred to as “Sub Routines”. The Resulting diagram is known as Structure Chart.
Subroutine:-
A subroutine is a self-contained section of the program code that performs a specific task as part of the main program. Sub routines can be
either procedures (Null Function) or functions (Fruitful Function).

Consider the alarm app computer system for a


smart phone. This could be
divided into three sub-systems, setting the
alarm, checking for the alarm time, sounding
the alarm.
These sub-systems could then be further sub-
divided the structure diagram makes the
process clearer.

Library Routines:-
A LIBRARY ROUTINE is a set of programming instructions for a given task that is already available for use. It is pre-tested and usually
performs a task that is frequently required.
Test Data:-
To determine whether a solution is working as it should it needs to be tested. Both whole system and subsystems as well.
In order to be tested fully it needs to be worked through several times with different test data i.e SET OF TEST DATA. Test data needs to
be of the following types:-
• Normal Test Data:-
• Will result on normal execution of the program to produce results. The produced result should then be compared with the
“expected” results. If both achieved results and expected results are same then the codes is working as it should.
• For example the normal test data for percentages of exam results achieved can be
• 50,60,80,70,100
• the expected value when finding average of these percentages should be 72.
• Erroneous Or Abnormal Test Data:-
• Should be rejected by the program and appropriate expected steps should be executed (for example printing an error message).
• for percentages of marks the following data should result on errors:-
• -11 and eleven.
• Extreme Data:-
• The upper and lower limits of acceptable value (should be accepted)
• 0 and 100 are extreme values for exam percentages scenario.
• Boundary Data:-
• The data that lies beyond the acceptable range. (should be rejected)
• 101 or -1
Validation • Range Check
Is data • Only numbers in specified are accepted
Sensible? • Percentages should be between 0 and 100
• Length Check
• The number of characters should be a certain number.
• Passwords need to be at least 8 characters long.
• Type Check
• Data has to be a certain type.
• Number of brothers and sisters need to be whole numbers only. (integers values)
• Character Check
• String of characters should not include invalid characters
• A name should not have # or %
• Format Check
• The character should be of a pre defined pattern
• User ID should have 2 letters and then 4 numbers. AB1234
• Presence Check
• A field or data cannot be left empty.
• Email address must be entered.
• Check Digits
• Final digit in code is calculated with existing data. If the recalculation results in a different value then an error is identified.
• ISBN or Vehicle Identification numbers

Verification • Double Entry


Is data • Data is entered twice both entries are compared for differences (errors)
accurate • Screen Visual Check
according to • Manual check or entered data by displaying the entered information before continuing.
previously • Parity Check and Checksum
stored value? • Discussed in section 1.2
Dry Running and Trace Tables:-
We can check that an algorithm works as intended (or even for finding out what it does) by “dry-running” the algorithm and updating a trace
table with the test data. The trace table contains a column for each variable. The values that change in the table are then noted accordingly.
Furthermore, the following rules have to be kept in mind when working with trace tables:-
- Entries are only made in a cell when an assignment occurs.
- Values remain in variables until overwritten.
- If the cell is blank this indicates that the previous value remains.
- A new new ROW should be allocated for each new iteration (step in loop) in the Trace Table.
A B C X OUTPUT
0 9 9 9
1 7 7
2 3 3
3 12 12
4 6
5 4
6 15 15
7 2 2
8 8
9 15 2
SYNTAX Error is when you are have made a mistake in writing the program according to Programming Language Rules. The CODE
WILL NOT RUN.
Corrective Maintenance:-
Code Changes when the program is not working correctly due to a “logical” error or a “run time” error.
- usually such type of errors become evident early on during the development process.
- however under certain circumstances these errors may not be revealed immediately.
- for example the “bug” lies in a part of code that hasn’t been executed that often.
- or the program or part of program may have not been subjected “extreme” values before.
Adaptive Maintenance:-
Code Changes when program to enhance functionality or in response to changing specifications.
Finding Logical Errors:-
Finding Logical Errors:-
The best approach is always dry running the algorithm to find logical errors. Furthermore
you need to consider the following:-
• Line1:
• in such questions where you have to find the smallest or largest values you should
initialise the largest with 0 and smallest with an abnormally large number (as
nothing is smaller that 0, usually) that lies on the upper extreme of a valid inputs.
so in this case Large should be assigned with 0.
• Line 3:
• while loop (post condition) relies on the condition to be TRUE for it to resume.
Here we can see that the condition is already FALSE(as counter is already <30)
and hence the loop will never run. We will have to change the statement to
counter<30
• Line6:
• if we are comparing the largest number we need to see if the newly entered
number is larger that the existing largest number therefore the statement should
be “Num>Large”

• Line 7:-
• Our rogue value is the counter becoming more than 30. But here we can see that
the counter is not incrementing rather decrementing in each iteration (step). The
statement should be counter=counter+1
We have studied the use of basic constructs such as assignment, sequence, selection, iteration, input and output.
We will now study the Python Syntax for these basic constructs.
Some interesting details about Python:-
- Every statement must be on a separate line.
- Indentation is significant. This is known as the 'off-side rule’.
- Keywords are written in lower case.
- Python is case sensitive the identifier Number1 is seen as different from number1 or NUMBER1 .
- Programs are interpreted (refer to previous concepts about compilers, interpreters and assemblers).
- Python files have a .py extension
- Python files can be edited and created using IDLE (a Python editor).

A python file
where code is
written →

The same module


is run in the
Python shell

You will learn the application of the following in Python:-
1. Declaration of Variables.
2. Declaration of Constants.
3. Assignment of Variables.
4. Arithmetic Operations.
5. Output to Screen.
6. Writing Comments
7. Datatypes
8. Boolean
9. Selection
10. Loops
11. Arrays
Declaration of Variables:-
SYNTAX:-
DECLARE <Identifier> : <type>

EXAMPLES:-
DECLARE number : INTEGER
//number is declared as an integer
DECLARE name : STRING
//name is declared as string
DECLARE n1,n2,n3 : INTEGER
//three numbers n1,n2,n3 as integer
Variable Assignment:-
SYNTAX:-
<Identifier>  <value>
EXAMPLES:-
number  0
name  “Hassan”

Declaration of Constants
SYNTAX:-
CONSTANT <Identifier>  <value>
EXAMPLE:-
CONSTANT Pi = 3.142
Arithmatic Operators:- DECLARE num1,num2,sum,prod,divwhole,rem : INTEGER
DECLARE div2 : REAL

print “enter first number” //this is a prompt


input num1

input “enter the second number”, num2 // can be written in same line too
// say num1 is 5 and num2 is 2
sum = num1 + num2
//sum will be assigned 7
Operator precedence:- prod = num1*num2
1. Brackets. //prod will be assigned 10
2. Exponents. divwhole = num1 DIV num2
3. Multiplications. //divwhole will be assigned 2
4. Division. rem = num1 MOD num2
5. Addition. //rem will be assigned 1
6. Subtraction. div2 = num1 / num2
//div will 2.5
print “The Sum is=” , sum, “ The Product is =”, prod, “ The Whole Division is=”, divwhole,
“ The Remainder is=”, rem
// this is as example of printing “prompts” in line with variable values.
//will print in the following manner
//The Sum is=7 The Product is=10 The Whole Division is=2 The Remainder is=1
print “The division with decimal places is…”
print div2
//the variable type of div is real therefore it will have complete division as
Data Types in Python:-
Further Data Types →

Boolean Expressions:-
These expressions evaluate
to either TRUE or FALSE.

In Python there are no character types, however a character


type is considered as a string of length 1.
Logic Statements In Python:-
Implementing Simple Logic, Complex Logic and Nested The Python equivalent code will look like….
IF Statements.
In Python.
//considering our previous example

PRINT “enter a positive number”


INPUT number
If number > 0
if number > 10
then
print “this number is greater than 10”
else if number>=5 and number<=10
then When run in Shell it will result in the following…
print “this number is between 5 and 10 (inclusive)”
else
print “this number is less then 5”
else
print “this number is not positive”
// Consider the following CASE statement.

CASE of Grade
“A” : PRINT “you have achieved an A grade”
“F”, “U” : PRINT “you have failed”
“B”…“E”: PRINT “Passed”
OTHERWISE
PRINT “Invalid Grade”
END CASE

Since there is not alternate in Python for CASE statements


we will have to make us of Else…If structure. →
Working with Arrays:-
- In Python arrays are referred to as Lists
1 D Arrays are defined in Pseudocode using the following statements:-
DECLARE <arrayIdentifier>:ARRAY[<lowerbound>:<upperbound>] OF<datatype>
For Example:-
DECLARE Array1 : ARRAY[1:3] OF INTEGER //declares an array of type Integer of 3 elements
DECLARE Array2 : ARRAY[0:5] OF STRING //declares an array of type STRING of 6 elements.
//*Array2 ranges from value 0 to 5 so Array[1] is actually referring to the //2nd element
Accessing Data in 1D Array:-
<arrayidentifier>[index value]
For example:-
PRINT Array1[3] //Prints the 3rd element in the array
INPUT Array2[3] // takes an input from user and stores it in the 4th position of Array2*
2 Dimensional Array:-
DECLARE <identifier>: ARRAY [<LB1>:<UB1>,<LB2>:<UB2>] OF <datatype>
For example:
DECLARE My2DArray : ARRAY [1:3,1:3] OF INTEGER
//this code creates a 2 dimensional array of 3 rows and 3 columns of type integer.
Accessing data in a 2D Array:-
<arrayidentifier>[rowValue,columnValue]
For Example:-
PRINT My2DArray[2][3]
//for printing contents of row 2 and column 3
INPUT My2DArray[2][3]
//take input from user and store in row 2 and column 3
2D Arrays…
These Arrays can be of different data types all collected under one main array...for example
Working With Loops
THE FOR LOOP:-
FOR <counter variable>  <start value> TO <end value> STEP <step value>
// the step value is optional and it is by default 1

END FOR

FOR count  1 TO 10
PRINT count * 2
NEXT
END FOR
//the counter controlled loop will run 10 times.

THE WHILE LOOP (PRE CONDITIONAL)


WHILE <condion is true>
<do this>
END WHILE

WHILE num<>0
input num
total = total + num
END WHILE
More Python Built In Functions
Features of an IDE (Integrated Development - Prettyprinting:-
Environment):- - Colour coded
key words
- Context Sensitive Prompts:- - Indentation
- displays hints or a choice of keywords - Comments
appropriate for current insertion point of
code.

- Expanding and Collapsing Code blocks:- - Dynamic Syntax Checks:-


- if you are working on a program that has many lines of code you - Syntax is checked AS it is being typed and coder is
can save excessive scrolling by collapsing blocks of statements. alerted.
- Pycharm example - Pycharm example

You might also like