You are on page 1of 112
Computer Science (olgey Ne == ela laren ae NL Computer Science for CAPE® Examinations: UNIT 1 *Sclence is everything we understand well enough to explaln to 2 camputer. Everything else is Act.” David Keuth Jase-Omeileo L. West g ‘Computer Science for CAPE® Examinations: Unit © Jase-Omeleo L West, 2013 Is0N 9788764246219 f All rghts reserved. No part of ths publication may be reproduced, stored in a retrieval system, oF transmitted in any form oF by any means, without ‘the prior permission in welting ofthe author, ‘You must not circulate this B binding or cover and you condition onary acquirer CAPE? is a registered trade Examinations Couneil (CXC). Computer Science for CAPE® Exar Is an independent publication and authorized, sponsored or otherwise Oc, Ihave tried to trace and make aware tothe real ‘the sources of the information gathered inthis The author will not be held accountable for, injuries or losses incurred as a result of infor inthis text Printed in Kingston, Jamaica Introduction & Acknowledgments Computer Sclence fer CAPE* Examinations: UNIT 1 Is a book for Lower Sixth form students sitting Computer Science Unit 1 for CXC's CAPE Examination, The baok closely adheres to the 2009 Computer Science slbbus and to the reports given ‘by CKC forthe Computer Science Examinations since 2009. | would tke to extend gratitude to allthe people who ‘encouraged and motivated me te produce this book ‘Thanks to Miss Natalee Johnson for her continued support in making this vision of mine a reality. Gratitude is also extended to Mr. Alexander Nicholson for allowing me to use his photograph as the cover page & Mt. Travis Garnet for editing it. ‘hope this hook wilprove benefilal ty you sid that it will assist you in nat only achieving high marks in the CAPE Computer Sclence Unit 1 exam and the VA, bout elso in gaining an appreciation for Computer Science itself Jase-Omelleo L. West Contents Penna Computer systen Input & Ouput Devices Memory Types Memory Features Storage Devices Security Types of Computers Computer Architecture Logle Gates & Truth Tables Flip Flops Registers Counters Visit www. meetio2012.wik.cam/comselt for ‘additional rates, exam: questions, IA sample, ‘assistance from the author. Multiplexers Encaders & Decoders Data Representation Bits & Bytes Binary & Decimal Conversions Signed Magnitude, 1's & 2's Complement Floating Point (SEM) Octal, Hexadecimal, ASCII & EBCDIC 35 36 a 45 50 Computer Organization CPU Components Instruction Format Instruction Types Instruction Sets Instruction/Machine Cyele Cache Memory Tie? Pena oaks Problem Solving Problem Solving Process Algorithm Representing Algorithms Constructs in Structured Program Interpreting Algorithms Correcting Algorithms Developing Algorithes Programming Paradigms Programming Paradigms History of the Paradigms (2 —5" Gy) Procedural/inperative Paradigm Object-Oriented Paradigm (00°) Functional Paradigm Declarative Paradiam Aspect-Orlented Paradigm (AOP) Scripting Translation Process ‘Stages in the Translation Process Role of Preprecessors & Linkers Coding in Ubraries in Inputting & Outputting Conditional &. erative Constructs Arrays of type int ‘Arrays of type char Functions Records/Structures (struct) rue Making the Program Run! Developing Good Programming Style Assistance INDEX References a a3 20 az wa 2 128 336 128 140 at 146 1g 155 159 166 wi 7 13 190 195 MODULE 1 Computer Architecture & Organization Computer Architecture refers tothe structure of all ‘or part of a comautersystem and the details needed to make it functional. This takes inte consideration the design of system software, such asthe operating system, as well as the combination of hardware and basic software that links the machines on 2 computer network Computer architecture therefore covers computer systems, microprocessors, circuits, and_ system programs. A computer system is comprised of two main ‘components: 11. Hardware — tic refers to the equipment required for the functioning of the computer system. It entals any component that can be physically handed. 2. Software this fers to the setof instructions Fequired to maniaulate data in a computer system, Software governs the way hardware is Used. Without software, hardware would be useless, Page| 1 Computer System fn Input Device is a ‘only providing informat ‘of input devices are ‘An Output Device isa piece of ‘only receiving. information. Examples include printer, monitor An Input/Output Device is one providing information to a recelving Information from It. One & input/output device i disk drive, Port Connectivity refers to location system for passing data into and out such asa USB port for connecting periph eg printers. Speed refers to the rate at which infor transferred between a computer's CPU and af or output device. Quality of Output refers to the extent to whieh particular aspect of the output of an output devh meets the standards of a particular time peri Example, what was considered good q) resolution on a monitor ten years ago will be different than what {s considered good quality ‘ustput today. ‘Specialized Devices ae input or output devices with additional features rot pertaining to their main function, example, a printer that can fax. Computer Memory refers stores data for use by a ‘ay be capable of string the dl permanently and are therefore 40 1. Temporarily. These devices store the data up electricity supply to them is cut, after the data[s lost. This is known as being Random Access Memory (RAM) is RAM is roferred to a5 main memory a It primary memory used by the CPU processing information. The contents of canbe altered, thats, data can be read or old data can be erased to make oom ew data. Permanentiy, These devices store data even after power 10 them s cut. Read Only Memory (ROM) is non-volatile, ROM chips cantain information which connigt bbe modified or deleted. Information can only be read. ROM is used to store items that the computer needs to execute when it is first tumed on-A set of instructions called the basic: Iinput-output-system (8105) which is needed to start up the operating system is stared in ROM. Erasable Programmable Read Only Memory {€PROM) is also non-volatile. tt is used by hardware vendors to put variable or constantly changing code into a prototype system. EPROM ‘is similar to ROM but is however able to have its contents changed. This is done by ‘removing the EPROM chip from the computer, removing its rrotective covering and exposing the chip to utraviolet light. This erases the chip's contents Electrically Eresable Programmable Read Only ‘Memory (EEPROM) is similar to EPROM, but instead of removing the EEPROM chip from the computer to erase its contents, an electrical pulse is passes through it. There are certain attributes which can be differentiate one type of memory from These attributes include: 4. Speed ~ this refers to how fast dota ean retrieved from or accessed on a device, CPU is faster than cache which is faster RAM which s faster than the hard disk which is faster than any secondary storage device such, asa jumpedrive. Size - this refers to how many bits of data 8 memory device is capable of storing. A hard diskeanstore up to 1 TB; jump drive can store Up to 68 GB; 2 modern RAM chip can store Up t08 6B and a standard flopay disk can store up to 1.44 MB. 3. Word size - this describes the number of bits 8 Word contains. A word is the number of bits CPU can process in one instruction cycle Modern processors can process up to 64 bits in one cycle 4. Volatility ~ this refers tothe loss of data when ower to the memory device is cut, RAM isa ‘volatile memory while hard dskis aron= volatile memory. Storage devices are hardware components which ‘are used to deposit, retain or retrieve computer data. There are certain distinctive characteristics Which can be used to compare one storage device to another. These features include: A, Storage Capacity ~ this refers to how much data a device can store. This is measured in bbytes. Modern storage devices, such as jump drives, can store from 168 up to 6468, 2. ‘Access Speed this refers ta the time taken for 29 drive on the computer (haed drive, CD drive etc) to find 2 particular piece of data on a storage medium and send it to main memory it usually measured in nanoseconds (ns) for ‘main memory and milliseconds (ms). for secondary storage devices; main memory is foster than secondary storaue. 3. Access Method ~ this refers to how data is written or read from 2 particular place on a storage medium. There are three (3) access methods |. Sequential Access ~ in this scenario, 3 certain fiece of datum can only be accessed by reading all the data that portable but due to their minute sites, are ‘susceptible to misplacement! 4 to access a particular ‘without first having to ‘that comes before it. Exam ‘wanted to access the 35% wouldn't have to go through before it. However, tis usually to scan some [but not all of before the required one, The time it takes to access a datum is somewhat dependent om ‘mechanism involved. Random Access~ this method al 2 piece of datum to be accessed ‘anywhere on a storage medium without first having to read the preceding data The access time ie independent of the mechanism involved and itis the fastest access method ofthe three, 4. Portability ~ this refers to the ability of the storage device to be transported from one computer to another. Storage devices such as Jump drives, SD cards and micro-SD cards possess the advantage of being extremely Security devices are those hardware co Set up to protect the computer system, stored on it and also the computer users various security devices which computer hhave if they value their computer system data stored oni. 1. Surge Protector ~ this s piece of which is used to protect several \devices from power surges and spikes surge is an increase in voltage above the stipulated level in the electricity for 3 or more nanoseconds spike is similar, but only lasts 6 nanoseconds. High enough surges and sp voltage can cause severe damage to mid Even if the increased voltage immediately destroy the machine, itm excess strain on the sensitive cor ‘causing them te deteriorate overtime: AS protector works by routing any excess to ground Voltage Regulator ~ this sa device capable of automatically constant voltage level in an electrical die the input voltage is too low or too high adjust the output voltage to be the st voltage. Ifthe input voltage is too high above the stipulated veltage however, some voltage ‘egulators will prevent any further current from passing through, limit the amount of Current passing through or just simply cease function, Uninterruptable Power Supply (UPS) ~ this isa Piece of equipment which primarily protects 9 computer system from data loss resulting from power cuts. UPS's werk by running the computer system off power stared in its battery when there isa power cut. The UPS is always connected to the computer system, so ‘when the man power is terminated, it quickly ‘switches to its battery to supply power. UPS's also serve ther functions. They serve as voltage regulators, as surge protectors and as frequency repulators. A computer is a device ‘and store data and pr The size, computational power ‘expected use of the computer the type of the computer. ‘There are five (5) general types of co 31. Supercomputers are computers which the best technology available to per many mathematical caleulations in the possibie time so as to solve extremely, problems. Supercomputers, unlike other computers, | designed to devote all their resources 10 solving of single problem at atime, They hundreds of processing units which at together in parallel to allow for multig calculations to be performed simultangously. Due 20 the large amount of twat wereraled By Sunercomputers, they have to be equipped with special cooling devices. These computers are extremely lafge and expensive, costing millions of US dollars. They are used in weather and climate forecasting, designing aircrafts and spacecrafts, designit rrew drugs and chemical compounds and in military weapons and defense systems research Mainframes — are very large computers capable of supporting thousands of users iuttaneously. These computers are similarto supercomputersin power but utilize this power to execute a vast amount of programs concomitantly, These are used in businesses and industries where mukiple persons need to ‘contemporaneous gain access to information located on a server. They are used in banks, colleges and supermarkets . Microcomputers ~ otherwise called personal computers (PCs), are relatively. inexpensive ‘computers designed for general use by a single person, They come equipped with a single silicon chip microprocessor which serves as the Central pracesting unit. Microcomputers come In various sizes, ranging from relatively large desktop computers to smaller tablets Microcomputers are used to perform more commonplace tasks such as word processing, accounting, desktop publishing, running spreadsheet and database management applications, playing games and surfing the internet. screen. They ate powerful than PC being portable. They. batteries to power them, Personal Digital Assist hand-held computers which are’ electronically organize a user's information. PDAs are capable of taking? scheduling appointments, sending faxes ‘sending and receiving electronic mails. Most PDAs are capable of using. devices to write on a screen rathor utilizing @ keypad. When combined with cellular phone, they have the capability: ‘connecting to the internet and doing alm anything that a personal computer would capable of doing. Due to their small sime limited battery if, they aren't a replacement for laptops, Computer Architecture A Logic Gate is a minute digital switch which performs a logical operation on one or more logic inputs and produces a single logic output. Logic gates are used to construct microprocessors. The more logic gates that are packed onto a computer chip, the faster the computer can process data, Logie gates are represented by specifi symbols depending on their specific function: + AND Gate ‘Output is true only if both inputs are true, = oRGate Output is true fat least one input is true > = NoTGate Outputs the complement of the input >. (8060) + NAND Gate ‘Output is only true if at least one of the inputs is fase, a- = 8 (A.By or Q= (A.B) © NORGate ‘Output is true only if both of the inputs are false, a _ = (A+8y or a= (AB) 8 + BOR Gate Output i trueeniy if ane of the inputs is true, not both, A Q=(A.8')}(4’.8) or Ds + BCNOR Gate urput Is tue if both inputs are the same (true-true or flse-false), A A.B) + (8.87) oF % Q=(A@sy ‘ATTruth Table isa table used to specify the value of te cutput signal from a logle circut/gate or device The CAPE Computer Science Examination may — Se ees aso. + AND Gate -BMe fotiowsg example shows how such a oe eel A 8 ny] . eae St 5 eee are 2 ‘4s, so thot both inputs can be true and meet “fs Sore. > ? £ e [2 | 0 - | 0 € 71 ‘The CAPE Computer Science Examination may also present the student with a logic circuit and ask for truth table to be érawun up. ‘+ Qwill be either condition 1 or condition. therefore construct 2 AND Gates ‘connect them to an OR Gate, a QD, Me folosing example shows how such 0 Auestion sould be approached raw the truth table for the folowing togic cireult: * Place NOT Gotes ot appropriate positions ‘on either input tine to satisfy eoch condition; one condition should be dealt with on each AND Gate. » at * Drow 0 tuth table ond put in the generic inputs. a . a 1 1 1 a o 1 Cr) 2 ‘+ Troce what happens to each value in a combination as it passes through each logic gate and write the final output In the corresponding Q ce. AE [2 z o z o a o [a | 2 | o o ce * ln condition 1, the first AND gate received ‘ene high Input ond a Tow input which ‘resulted from the NOT gate filing the ‘itil high input; the condition of the AND. ete Is not met ond a low signal is produced. The second AND gate negated both high inputs, resulting in @ tow input being produced dy it. Two low inputs being provided to the OR gote sees to 0 low output being produced. Im condition 2, the first AND gate is Provided with two high inputs as the NOT ‘ate negated the low input af 8. This is ‘enough to cause the output ofthe OR gate tobe high Con you figure out why conditions 2 and 3 produced 0 and 1 respectively? Visit www meetio2012 wix.com/eomscil ‘and share your answers with me. TUTTO A Flip flop isa digkalcireutt with normally two input lines, two output lines and a clocking device. A flo. flop continuously checks its input signals and correspondingly changes its two output signals (one the normal value and the other the inverted \ariation/complement) at times specified by the clocking device, Input 1 ‘Output 1(Q) ‘locking Device Input 2 Output 2 (a) Alia flop is used te store one bit of information. By connecting several flipflops, data representing a binary value may be stored, There are two general types of fip flops, synchronous and edge-triggered, These categories are further broken down into other types: + SR Flip Flops Set-Reset Mp Lops + T Flip Flops Toggle flip flops * DFlipFlops ata fp flops +k Flip Flops Registers are high soeed memory locations within a ‘ictoprocessor which store information temporarily. Regsters have a particular storage capacity and usuilly serve one particular purpose. As registers are engineered to be faster than main memory (RAM), they are more expensive, Consequently, there are much fewer registers within 2 CPU thanthere are RAM chips Registers are constructed from flp flops. Registers are normally rated by the number of bits that they tan store, for example an B-bie raglater versus 2 32- Ditregister. Processors often contain several kinds of registers, which are classified according to the information that operate on them: 1. Accumulator ~ this stores a previously calculated value or a value lnaded from main ‘memory, 2. Instruction Register — thie stores the instruction which Is currently being executed or decoded 3. Memory Address Register (MAR) ~ this stores the memory address of the data that is to be fetched for processing or the memory address Page (2 to which the results ofp te, 4. Memory Data Register (MDR)— this the data that sto be etched for process the data that results asa result of processing, ‘A Counter/Program Counter is @ type of register which stores the address of the next instruction to be executed. When the counter passes the address of the instruction to be executed to the instruction. register, the value of the counter automatically ‘increments, resulting in the address of the next Insteuction being sored int. Counters keep track of each successive instruction ‘na program to ensure that the CPU is following the bragram’s instructons in the correct arder. A counter may be constructed from a number of connected J flipflops. The number corresponds to the maximum state that the counter must have Example, f the counter isto store 3 maximum value equivalent to the decimal number 15, then four JK flip flops must be used. Upon application of an input ‘pulse (clock signa) the counter will go through from 0 t0 15, that is, 0000, to 1112:. When the counter ecognizes that it has reached 11113, it will automatically resetitself to 00002, BIC | A Multiplexor is a digital device which selects between a setof input signals and producesa single Sutput signal on an output line. An electronic ‘multiplexor enables several signals to share one device instead of having a single device for each {input signal. Muitiplexors are used in some CCTVS, where there are sevoral CCTV cameras and only one. CCTV monitor; the viewer simply choses which, ‘Camera's feed he'd lke to see on the moniter. 4X2 multiplexor bas 4 input signals and 4 output signal, It also has 2 select Inputs which determing: whether the device is active or inactive, The following block diagram represents a 4X 1 ‘multiplexor: 2 . saa 24 The followingis alogic circuit ofa 4X multiploxor: sia sia ‘The following is the truth table for a 4X 4 smuttplexor: Inputs | Selectinpuis SH | siz ow po i vlale >| Oo] a Sir i[4 The select inputs are responsible for which input (A, 8, Cor D) is provided to the output gate, ‘An Encoders a dial circuit which changes set of signals Into a binary code. An encoder has 2" ip signals and output sigrals. Only one of the inp slgnals can be logc 1; all others must be 2ef0- utput ines produce the binary code equivalent to the active input The following is a block diagram of an & x 3 ‘encoder: c a o ‘ a 6 This particular encoders called an ectal to binary encoder. in this encoder, each of the eight inputs corresponds to an octal clgrt and the three outputs Produce the corresponding binary number. WANN i — The following logic circult represents an # X 3 encoder: ——— — Qe ——— T4s16H18 asst Lott +18 = SR a s+ == Iovl7+18 A Decoder isa dita circut which decodes an input following is the truth table to the 8 X 3 joetacatls ‘code, that is, it takes n inputs and produces 2" encoder: Sutputs. A decoder has m input lines, 2 output lines nae ‘ and an enable signal. The enable signal is responsible for making the decoder active or 8/7/6/6[4|B]2 nfo Inactive, If the enable signal is zero, then all she ahororoberetepat ‘ecoder’s output wil be zero, regardless of the ‘put signals. Wits signal is one, then the decoder ofolojolajclolsto will perform normally o[opo[ojopels|opo [| Os] 5 [omy] a] ee, The following is ablock diagram of a2 X 4 decoder; d[oopolafopo}olo efolo[ilo[ojojoli 2 o/o[a[opofopojofa a a 0[1/0[o]o]o|olola 8 a T[o[opofafolojals = ae See overieat> ‘The following logic circu represents a 2X 4 decoder without enable: | Pe Representation ‘The truth table below shows what is happening in this logic circuit, [out Ouapat J a B a O a | a ° 0 a] 90] 0 o op pe pa pepe 1 0 oO 0 1 0 1 1 0 0 ofa ees Abit binary digit) isthe smallest unit of information that i able to be stored in an electronic device. A bit is used to represent the state ofa transistor ina flip flop circuit, that 4s whether electricity is passing through it or not, 1s used to represent a transistor with electricity passing though it; It may also be called on, true or yes Oisused to represent transistor without electricity passing thraugh it; it may also be referred to as off, false or no. A byte Is a group of eight bits. A byte can store values ranging from 00000000, ~ 111111113 .. that |s, 0-255 in decimal Bytes are combined into groups of 1 ~ 8 bytes to form words. Modern technology allows for 32 and leven 64 bits to be processed together. & 64-bit [processor uses wordsthat are up to& bytes long (54 bits) Torepresent decinal numbers in signed magnitude, 1's complement o 2's comalement, one must fist know how to convert them to binary and vice versa ‘To convert from decimal to binary: 4. Draw up three columns anc! place the decimal ‘number in the top center cel, 2, Place 22 in the topmost eft call; this willbe the ‘number used to divide the decimal number to arrive at the binary equivalent. 2 3. Divide the decimal number by 2 and place the: while number results in the cell beneath the. decimal number and the remainder tothe right. of the whole number. [z 44. Repeat step 3 until the result of dividing the decimal number by 2&0. meee 9 0 2 2 2 6 a 1 oj 5. Write out the binary number as it would appear from bottom of the table to the top. eae 2 0 2 3 0 2 1 B 2 ri 6. Ifrequirec, represent the binary number using 8 bits by placing the required number of zeros before the binary numbers. 1110; ooop1110; To convert from decimal fractions to binary: 4. Draw up three columns and place the decimal fraction in the tap center cell, os || imal ji | 2, Place a2 inthe topmost left allthis willbe the ‘number used to multioly the decimal number toarrve at the binary equivalent. 2 [ os 3. Multiply the decimal number by 2 (2 * 0.75 = To.convert from binary to decimal: 415} and place the decimal fraction in the cell 1. Write out the binary number with adequate beneath the decimal number and the whole space between each digit ‘number to the right ofthe fraction. 00010110 2 | 025 — 2. Putthe place value of each digit overt ; Pl [F le [2 [2]2 [7] = 128 64/22/36| 8 | [2 [2 <— ofelo|sjolafaye 4. Repeat step 3 until t vd 3. Multiply each binary digit by its place value. a va] 64]32[16/ 6] «| 2/1 2 os olololialolifilo ° 2 ololofwlolal2|o 5: (itm: out the Binary rumibor = eal 4. Add the products to arrive at the decimal appear from tp of te tablet the bottom auhalet Tapa 9+0+0+16+014+240-22 2 | os Therefore, oomo1ao, «22 o | 4 See overtoats Page | 39 Page | 49 To convert from binary fractions to decimal: 1. Write out the binary number with adequate space between each digit 101.1102 2, Putthe place value of each digit over it 7?) /2/2 |) = tfofa]-fa[iaiiesfa 3. Multiply each binary ait by its place value 4 | 2[ 1 | [os [025 ]0.25 [006s t)e)a)-) 2) 25) enna 4/0/12) fosjo2s| o [0055 4. Add the producis to arrive at the decimal equivalent. 470717057025 + 0.0825=5.8125 Therefore, 101.12023= $.8125 4/2) 4) [os |o2s | 0.25 | 00625 | <— Signed Magnitide and 2's Complement are used in 8 computer system to represent negative numbers, This is because It is easier for the CPU to add a Aegative binary number to a positive binary number Father than to subtract a positive binary number from a positivebinary number, ‘To convert from decimal to signed magnitud 4, Representthe decimal number in binary. = 2 ] 2 | 2 ae 2 6 2 z 2 1 ie 1 a0C14; 2. Represent the binary equivalent as an 8.bit binary number. 5100110001; 3. fhe decimal number postive, the leftmost © & Adds tors number Bit shoud be zor (0) 11001111 Ifthe decimal numb smegative the eftnost en bit should be one (1). 11010000 51 10120011 Therefore the 7 complement eauiaent of ~ ase 11010000 Te convert from decimal 2's complement 1. Represent te decimal number nina. “8 ZL 2 | « fe a 0 2 6 | @ sale ee | iF 1 | ; 48= 110000 2. Represent the binary equivalent #3 an bi binary urbe 4a 0110000) 3. Perform Ys complement on the binary number; ths irwoles converting every 1100 sndeveryOto 2 Floating Point (SI A floating-point number is a number which is ‘expressed in scientific notation, In which the number is represented as a decimal number ‘multiplied by @ power of ten. This Is a convenient ‘way of expressing very large or very small numbers, {95 t compacts the size of thelr representation xarmple: 1, 000, 090, 000 = 1x 10° xomple: ~0.0000000023 =-2.3 X 10% Modern computers utilize floating-point processors hich use floating point numbers as opposed to fixed-point numbers. Fiied-point numbers are expressed explicitly but are restticted in how long. they can be in'a computer. They however allow for {est computation to occur. Floating-point numbers fon the other hand can represent very large values bbut arithmetic calculations involving them become lengthier and more complex. Floating-point processors added to a computer system will significantly Increase its math and ‘graphics capabilities. Floating point processors are also called coprocessors or Graphics Processing Units (GPU) due to their impressive ability at crunching the vast amount of numbers involved in producing graphics. A floating-point decimal number is represented by the following format: sign mantissa X_base = Where sign indicates whother the number is positive or negative, mantissa Is the fixed-point number, base is 10 and exponent dictates how ‘many decimal places to move to the left or right of the decimal position; ifthe exponent is negative, it Gictates how mary places to move to the left of the decimal position and if i s positive it cictates how many postions te mave to the right ee (Be) [rinks i A floating-point kinory number |s represented by the following format: sign exponent mantissa where sign indcates whether the number is positive or negative (0 indicates postive, 1 indicates hepotive), exponent is a 3-bit long representation which dictates the number of decimal places to move to the right of the leftmost digit in the ‘mantissa and mantissa isa binary fraction, 14 Note:The exponent may be represented using sign ‘and magnitude; the leftmost bit would then determine whether the exnonent is postive or negative. 0 would indwate a postive exponent ond 1 would indicate @ negative core orp: an 8 feng pat umber renting gonna on [ie] [Roonaan] [are] The following illustration shows the decimal value of each place value in a binary number. BPP EEE 32 sa za 0.0625 fe o[efero sista ieee a ‘To convert from SEM to decimal: 1. Identify each part ofthe number. out aig 2. Deduce the decimal value of the exponent. ou, =3 3. Normalize the mantissa aun *2=111,1 4 Deduce the decimal value of the value to the left ofthe decimal point ut 5. Dedlice the decimal value ofthe value to the Fight of the decimal point. 4205 6 Add the values obtained from steps 4 and 5 to iget the final zecimal value, TH05275 ‘See overleal> ‘To convert from dacimal to SE 1 Represent the sign of the whole number Nogative[- Positive (+) =0 Find the binary equivalent of the whole ‘umber, Ifthe number is negative, ignore the sian for now. 8-110 Find the binary equivalent of the decimal fraction. 025= 001: ‘Ad the values from steps Land ? to obtain the normalized binary value, 110,400; = 110.01; Move the decimal pointlett of the leftmost bit, Counting the number of bits skipped over; the value will represent the mar 11001, (2 bits skinned) Represent the numberof bits skipped as a3-bit Linary number; ths wil be the exponent. 3-01 . Puttogether the parts ta represent the decimal 4.2 floating point (SERA) numer, 6.25 = 1011111001 fEven though decimal Is the universal mode of ‘expressing, numbers, except in computers, there also. exists other ways, notably octal and hexadecimal, Wheteas the decimal system uses 10 1s Is base and tiebinary system uses 2 a6 its own, ‘the oetal system uses 8 and the hexadecimal system uses 16, Hexadecimal is 2 number system which uses the values Os through $510 represent Oi through 99in the decimal systemand Ax: through Firto represent 2049 through 15:9 Seeing that each hexadecimal Aigit represents fou bits in binary, it would take two (2) hexadecimal dats to represent a byte. Byte Values, which range from o0000000; = 111111313 (O1o ~ 255. are represented by two hexadecimal Gigts ranging from 04s to FF One primary use of the hexadecinnal number system isin representing computer memary addresses asi allows for programmers to more easily read and ‘work with code rearing to memory allocation ‘The following ilustration shows the value of each hexadecimal digit: eyo 2) 3 TP PEELS * | FER 4/5 6/7 8/3/10] u ‘To convert from binary to Hoxadecimal: 1. Split up the binary number into 4-it groups. 100111010: = 0001 0011 1910 2. Findthe decimal equivalent foreach araup of bits ‘0001 0011 1010 103 40 3. Find the hexadecimal equivalent for the decimal numbers in 2 above 130 1308 4, Write our the results from left to right and place the bate (16). 100111010; = 1341. conve rasta ty lets oi he Neda vai with ese inane resm it tide agi oh one 14 Be 3 2] | eT BL it out te A biary Yl or ech edocs mt | 0H a) ow eae wc ot bras emt ae tore ‘ntotoso.:coi, To convert from Hexadecimal to decimal: 1, Write out the hexadecimal valve with space between each digt £05 te 2. Putthe place value of each dit overt 16 ast [at | i8? [4096 256 16 r E 8 3 2 3. find the value of each hexadecimal dat 16° ae] ast |e 4035 256 16 1 [as nu 5 4. Multiply each digt by the place value above it ws | a6 | we | t it 5 7g as | a | 2 [ssa NT . 5, Add the values arrived at o obtain the decimal equivalent ofthe hexadecimal value. 57344 2815+ 80+2= 60242 B52, = 602429 Octal isa number system which uses the values Os through 75 to represent Oi» through Zuo in the decimal system. In binary, each octal digit is Fepresented by 3 bits. Therefore Sis would be 010012 (5e~ 101: | 1 —001,) and eor0101311005, would be 12745 (00»~ 4 | 0103 ~ 24 | 1122 ~75 | 100; 4) Octal was widely used in computer systems such as IBM mainframes which used 12-bit, 24-bit oF 36-bit ‘words which were cepable of being divided by three; this madeit easy to abbreviate the words, each octal digit representing tree bits, Modern computers however use 16-bit. 32-bit or 62-bit words which ‘cannot be evenly divided by three; this makes representing then in ottal undesirable, Hexadecimal is used in preference a: it exactly ‘represents a byte using two hexadecimal digits. The speakers of the Yuki language of California utilize ‘octal systems as instead of counting fingers, as we do in the decimal system, they count the spaces Page | 54 between their fingers (of which there are eight. go ahead, count them). ‘To convert from binary to Octal 1. Spit up the binary number into 3-bit groups. 101011010:0010; = 010 101 101 010.019 2. Find the octal equivalent to each group of 3 bits. 10 101 101 030 020 25 5 2 2 3. Write out the result fromleft to right and place the base (8). 10101101010010;=255220 See cverloat> ‘To.convert from O-tal to binary: A Write out the octal number with spaces between thesis 437 & 2. Write the 3-bi: binary equivalent for each digit above it. joo | on | a 3. Write out the binary values vbtained from left 10 right to obtain the binary equivalent ofthe octal value, 4376, = 100011121 See overleat> ‘To convert from Octal to decimal 4. Write out the octal value with space between each dint. 5752 2. Putthe place value of each digit over ft e | # aD oe T 5 7 Pinan 3. Multiply each sig by is pace value S12 wo] 8 7 5 7 5 2 1550 | acs | ao? 4 Add the values arrived at to obtain the decimal equivalent of the octal value. 2560+ 448+ 40+2 = 305 5752s 30500 See overleat> Page ASCII (American Standard Code for Information Exchange) fs a standardized coding scheme which assigns binary numbers to letters, numbers and other characters so that computers can efficiently Communicate with each other. Each characteris Assigned an 8-bit representation. Another system oF fopresenting characters is the EBCDIC (Extenced Binary Coded Decrmsl Interchange Code) scheme: EBCDIC is used in 18M computers only, whereas SCI is used in all other microcornauter systems To.convert from ASCII to binary’ 1. Identify the binary value of the given character; this is usuallygiven, Example: 8 = v0001050, 2 Determine ow many characters away the required character i lcated ‘om: Fis tow many characters way from ea I a ae 3 Find the bit binary equivalent to the ‘umber in part 2 above 4=00000108; 4. Add the binary number ar F =000011102 Computer Organization CPU Components A Central Processing Unit (CPU) isa silicon chip comprising of microscopic circuits and minuto electronic components whose principal function is to act as the information processor within a computer system. ‘The components making up the CPU are: 1. Arithmetic Logie Unit (ALU) ~ this is responsible for performing arithmetic Calculations such as adcition, multiplication tte and for performing logic/concitional tests fon data such as finding the larger of two umber 2, Bus — this is @ syster of electrical pathways used for the tansfer of data between the different components of the CPU. Buses are characterized by the nurnber of bits that they ‘ean carry ata single time and also the tyoe of data that they carry, The two general categories of bus are internal bus ané external bus. The Internal bus/system bus connects all the components on the mother board. The External Bus/Expansion Bus connects external devices, peripherals, expansion sits, /O ports and drive connections to the rest of the TNO Computer; itis usualy slower than the internal bus, These two categories are further subdivided nto separate categories to suit specific functions: * Address Bus/Memory Bus —transfers the address of data, Control us ~ carries commands from the €PU to devices (example, 9 print command toa printer) and returns status signals from the devices (example, an ‘out of nage" warning) © Data Bus ~ transfers data, 1 Control Unit [CU) — this is an electronic component which controls the flow of information trough the processor and coordinates the activities of the other Components within it. Some refer to the CU as, ‘the brain within the brain, as it controls what happens inside the processor. which ultimatnly controls the rest of the computer systen {nthe instruction cycle, the CU is responsible for: © Fetching te Instruction, Decoding te instruction, * Getting any data specified by the Instruction Coordinating the execution of the instruction, ‘+ Storing the results in a specfieed memory location, 4. CPU Clock ~ this is 2 creut that prroduces a fegular pulse so that each connected Component can be in sync with it. The CPU lock controls how fast a processexr makes caleulations. the time that passes from the startof one high pulse unt the stortoff the next Js referred to as a clock cycle. CPU Clocks are fated on how much pulse they can produce per second; this is measured in Hertz (He). Modern computers have clock speeds reaching 83 billion clock cycles per second, that is, 83 Gigaherts (8.3 GH2). Clock Speed relents to the ‘frequency with which a CPU clack vibrates. 5. Registers ~ high speed memory locations Within ¢ microprocessor which store Information temporariy. There are severa) type of reuters (Accumulator, Instruction Register, Memory Address Registers and Memory Data Registers) = ‘Ao Instruction is« code that directs a computer to ‘execute a porticuar task. An instruction contains Various fields whic contain information on how the Instruction isto be executed, ‘The diagram below depicts a typical instruction: [ERG [ Doseaionoroais | sonezorome Operane Instruction format describes what an instruction is ‘made up of. t describes the length ofan instruction, the felis present nan instruction, the positions of the fields inthe Insructions and the length of each field. Instruction formats may be fixed length ot Variable length Processors utiliing Reduced Instruction Set Architecture (RISC) ike MIPS and PowerPC use fixed length instructions. These instructions are relatively short and simple and are 4 bytes (22 bits) long. They allow for easy fetching and decoding to be done and they simplify pipelining and parallelism, The format of RISC instructions is usualy fixed, having either 3 fields: an op-code teld and two separate operand fields (two-address instruction format) of 2 fields: ‘an op-code field and one operand field (one-address instruction format). In some instcuctions using the one-address instruction format, the operand is ‘obtained from RAM and placed in an accumulator where itis operated on and the result consequently Stored in the said accumulator. n instructions using the two-address instruction format, the operands may be obtained from an intemal RAM location, an ‘external RAM location, an accumulator ora register ‘nd the result of whatover operation (addition, compatson, transfer ete, stored in an accumulator, special function register or a register Processors utilizing Complex instruction Set Architecture [CISC] like x86 and VAX use variable length instructions. As the name implies thereis no set slze of the instructions or the number of addresses, Variable length instructions tend to have _more expressive formats that give more information about the execution of the instruction. as a result, ‘decoding the instruction becomes comiplicater and therefore lengthens the time of the instruction cycle, Pipelining multiple variable length instructions is also dificult because of the varying, lengtis of the instructions, Despite» these disadvantages, variable length instructions have the bbeneficof allowing for memory tobe saved since the instructions are only as long as they need tobe, -2 An instruction within a computer is comprised of an eration code (op-code) followed by zero, one oF two bytes of operands. The op-code is the part of the instruction which recognizes the type of ‘operation to be performed such as ADD, MINUS oF MOV, while the operand isthe part that identifies the source and the destination of the data which wil bbe operated on. The operand may be a data value Itself,» CPU register, a location in memory or an Inputfoutput por. Five (5) common te of instructions re 1 Arithmetic tetracions — these pete arithmetic operatont such as alton, subtraction, increment, decrement, vision an mlpliston Example: (a ae (Add the content = ae register to the accumulator; leave the result in the accumulator) Lae (Decrement the value stored inthe accumulator by 2; store the result in the accumulater,) 2. Lala! Insrucons~ thee perform Booean operations sch es AND, NO, OR and XOR on dates on abity it bas Sane (aie a [an {Compare te conten aie 204 oat fa th the contents of the accumulator Usingthe AND operator sore the reat the secumulter) [one paaae {Compares the contents of the R2 register with the contents ofthe actor using the OR pert store heres nthe accumulator) 13. Dats Transfer Instructions - these are used to transter data between an internal RAM location and a Special Function Register (SFR) without going through the accumulator gt between an internal RAM location and an external RAM location by using. indinect sessing Sample wor [ao [ea] {Transfer the contents of the 234 location in ARM to the RO resister.) 2 AR 5. Program Branching (Push stack member into 20H location of RAM.) 4, Boolean Variable instructions —these are used to perform Boolean operations such as set, clear, AND, OR, NOT and conditional jump operations or single bit. Direct addressing is used, Example: [har Pa, (WF Port 2 has a value of OCH (11011100), this Operation leaves the port set to SCH (01021100) Le = Lo INe ‘ARRAY [wey a 7208 (lump if value of A>=RO, else continue to MOV Instruction) Instructions ~ these are Used to control the flow of execution ina rogram, Some instructions provide decision- ‘making capabiltios before transfering control {0 other parts of the program {conditional ane ‘unconditional tranches). Example [Tae FAR ADR (loads program counter with FAR_ADR address.) pi 30H wa [Branch to LOC2 as [30H] = SH; [30H = 00H}) ‘The above Instructions may be placed inta the following categories: 1. Data Processing Instructions: these operateon data by performing some caleulation on it, ‘example arithmetic instructions 2, Data Movement Instructions: these transfer data from one memory lacation to another, example data transfer instructions 3. Data Storage Instructions: these store Instructions that have moved from another location oF operated on, example arithmetic Instructions and logis! instructions 4, Data Control Instructions: these clvect the flow of Instructions in a program, example programm branching instructions How the operans byte(s) are selected is determined bythe Addressing Mode used, The most common addressing modes are: 1. Absolute Addressing this mode allows for ‘perations to be performed directly on data in | memory location as the address field Contains the actual address of such data, that i, ts absolute addeess. Example: [see [ee 2 Relative Addressing — when using this mode, the address ofan instruction to be arived ats Feached by adding an offset to the current Address in the program counter. The offsct is Usually signed (postive or negative) to allow an address before the current address or an address after it ta be arrived at. Relative addressing alows some jump instructions such 4 SIMP (short jump) and conditional jumps Stich a8 NZ te transfer control from one part of 4 program to another. 3, Direct Addressing ~ this mode allows for the operand to be specified by giving its actual memory address (usually specified in hexadecimal notation) or its abbreviated ame, Example: [mow a | Hoar (Transfer the contents of location 20H in RAM, tothe aceumulator | 1 Indract Aresing~a Ro, 82 or=TR reper ited ttre the addres ofthe operand The regstar contig the memory asiress is Caled» pointer reste a I does contain the data but ony Rs address RO and RL reper store Bit addresses, whereas FR regstrsstore lb adresses Bane [wove r oom (Move te contents from the memory lcadon pointe toy DPTR inte the cert 26 bitadress,1234H, cou be stored PTR) . Indexed Addressing — this mode allows for data to be retrieved from a look-up table (a table containing terms or values within a system), A 15-bit pointer register holds the toate address and the accumulator noios an 8 bit index vaive; the sum of the twa registers ultimately forms the actual address for 3 IMP for MOVC instruction, Immediate Addressing ~ this mode uses an 8- bit or 16-it constant value as the source ‘operand, which is specified in the insuetion . Register Addressing rather than in a register or memory location. The destination register should have the same ata sie asthe souree operand, Example: [Mor oer | ara) (Move 16-bit data constant FEOOH into the 16. bitditagointar register) this mode involves the transfer of information from one register to another. Example: (ov co A I Es (Fronsfer content of accumulator into RO register) Long Addressing - this made used withthe bite LCALL Jong cl) and UMP ong jump) instructions. It these Instructions, the last 2 bytes specy 2 16: destination location eve ne pruram branche Baamale (ea | er (26-bit adress of TMER INT i specied as the operand This i 2 function cal mC Timer) eee An instruction set, instruction set architecture (ISA) for command set is the basic set of commands or Instructions understood by a computer's microprocessor. Fach microprocessor has its own Instruction set. As it relates to Instruction set architecture, there are twe types of processors: 4. Reduced Instruction Set Computer (RISC) This ype of processor uses a small number of simple bult-n instructions, but seas to it that these instructions are executed quickly, typically within single clock oycle. RISC procestors therefore have a sail instruction Set. Popular RISC chips include MIPS, Alpha ‘AXP, SPARC and PoworPC 2. Complex Instruction Set Computer (CISC) This type of processor uses a wider array of instructions which are complex and. very powerful. These CISC instructions are usvally 20 amalgamation of several other simpler Instcuctions. This allows for complicated and flexible methods to be used to calculate elements such as memory addresses, Each CISC Instruction generally requires multiple clock ‘ycles to be executed, CSC processors therefore have large instruction sets erent loro Ay he *tnstruction cycle/Machine cycle isthe Sequence of steps that the processor uses to ‘execute an instruction, The cycles managed by the Gontro! Unit (CU) The following steps outline what happens in @ Atypical instruction eyele A, The CU fetches the instruction to be executed, The Instructon travels along a data bus from a memory location, where it then stored in an Instruction register. the counter/orogram ‘counter subsequently increments s0 that it Contains the address ofthe next instruction, 2, The CU decedes the instruction. A decoder it the CU analyses the Instruction and figures cut what itis asking to be done. The CU then retreves any data that the instruction needs via a data bus and then stores it in & ‘memory data register (MOR), 3. The CU coordinates the execution of the Instruction, Hfthe instruction calls for calculation tobe done ‘on data it specifies, the data is retrieved fram the MOA and sant to the ALU. The ALU then ‘ade, multiplies, subtracts, compares ete. the values it was presented with ‘The results ofthe exeeution are stored. The CU stores the results of the execution In another memory date register, which may then be copied to another memory location, ‘example RAM. Cache Memory is a high sped memory location lised to store the most frequently used data or data that will most likey be requested next by the CPU ache memory may either be a reserved portion of WAM or @ separate high-speed storage device. The Aechnology used to make cache memory faster than, AM also causes itto be more expensive. Asa result, Ahere is far less cache memory than mala memory (modlern RAM size for personal computers goes up ADEAGB whereas Cache memory goes up to 4M} Hiogardies, this small amount of cache memory Bgniflantly speeds up the instruction cycle “There are two types of caching A Memory Caching This involves using memary caches. A memory cache/RAM cachefcache store is 4 section of RAM that is mado of high-speed Static RAM. (WAM) rather than the slower Dymamic RAM (ORAM) whick makes up RAM. This type of ‘aching is effective as mast programs tend to fceess the same data or instructions repeatedly. By keeping as much of these frequently required instructions ar data in the high-speed SRAM, the CPU does not have to go 10 the slawer DRAM of main memory; the speed of the instruction cycle is consequently Increased, 2. Disk Caching This involves using disk caches, A disk cache is 4 section of RAM that uses the same Dynamic RAM (DRAM) as the rest of it. In ths type of caching, the disk cache stores information that ther has recently been requested from the hard disk or has previously been written to the harddisk. Example, a PC gamer playing Halo 4 repeatedly uses the right mouse button to shoot his oppanent; the code forthe rightclick funeion would be stored in a disk cache. This ‘consequently reduces the time the game has te ‘walt for the rightclick function to reach it so that the player can shoot. Disk caches do not store entire program files, ‘but only the portion that has been recently used. In the abovementioned example, the entire fle would have been the mouse software. whereas the rightclick function Is the recently used portion of the mouse software. Without clsk caches, programs Would have to wait for the dik-drive mechanism to fetch the required information from the hard disk every time itis needed MODULE 2 Problem Solving With Computers Ih today’s society, more and more of our prablems fe being solved with the aid of computers. Gomputers make the job easier as they too know About the problemanc how to get it done fully o° to sertain extent. How do they know? Well, they have #81014 how to solve the problem in the fist place they know how to solve the problem the hurvan instructing them must frst “Mave We must know how to sabe the problem ng the problem-solving process. -svetlon Is dedicated to getting you the student future programmer! to understand the rable soi ces. By the copter end you on appreciation ofthe role ofthe algorithm Bsc nsane ee cltimately Understand the process of developing algorithms, Which wil be crucial in determining how goad of a Programmer you become, 50, open your minds and prepare yourself to indulge Inte the world of resolving conundrums! Problem Solving NOUN HY ~~ Computers are designed to solve prabloms far the user by following a setof finite and clear instructions ‘ven to it by the programmer. Before a computer program can be written however, the Problem Solving Process must be used, ‘This process involves various stops: 4. Identify & Define the Problem, This involves recognizing the problem and then describing it explicitly. Analyze the Froblem, This Involves examining the problem in great detain term: ofthe input, the output and the Drocessing, steps required to produce the ‘output. A defning diagram/IPO diagram may bbe used. the arablem may ako be broken up Into smaller subtasks 50 as to simply it Gonerate Posible Solutions This involves coming up with all the possible Solutions to the defined problem. Every Potential soluton should be considered at this tage and none should be discarded; new otentiai solitions can be created by Amalgarmating, ideas from other poten solutions Select & Develop the Best Solution into an Algorithm, The best solution should then be developed Into an algorthr, The algorithm may be tepresented by flowshait vr « pseudorod® algorthen, 3. Test Algorithm for Correctness. This involves uilaing a trace table to identify and correct tte logical errors found in the algorithm. A tiace table is a ciagram which allows for yau to s2e the state ofan algorithm ateach step oft 6. Implement & Revievr the Solution. ‘After aflawiess algorithm has been generated, the solution may now be entered Into a computer where it can become useful. The algorithm is fist trarslated into @ specified programming language. The source code Ts then compiled and then ran. The program, now fit to solve the initial problem, must be feviewed and maintained. This ineolves Updating the source code to address any new problem(s) that may arise. Ths ties the final step ofthe process to the first step. MV Ap gorithm sa sequence of instructions writtento Holve a problem in finke number of unambiguous laps. Algorithms play a key role in the problem Solving process as they provide a clear-cut way by Intich the problem can be solved. Also, the use of Algorithms in the process ie beneficial to a Dronrammer as algerithms do not fallow the syatax Df any particular pregramming language. ‘The properties of a well-designed algorithm are: 1. tis. general sslution toa problem, 2, Iehas clearly defined and unambiguous steps. Ithas a finize numberof steps There is flow of control from one process to another, The instructions from the algorithm are put in their corresponding symbols. @) M2 following example shows how to DS represent on algorithm by using @ flowchart Use a flowchart to represent an olgerithm which accepts 2 numbers from a user and calculates the sum. The User should then be asked if they would like ta see the sum if yes, the sum is printed. ia fool bark 0 poe zg ba Naor may be represented using structured they santations such as flowcharts, pseudocodes baer howsiege = auton Oe tei (Georel to tora’ fete the sare been ee re foc ik oczrng tu oath 1 ‘Symbol Meaning @ start/stop, — | ‘cessing Example, sum =a + Input/Output Example, write “Hell!” SCO esto Example, Is num<5? Flow of Execution ° Connector no, yes, 2. Pseudocode — a pseudocode is a step by step solution to a problem which Is written using Englishlike statements and mathematical ftations to explain the logies in solving a problem. Pseudacades do not adhere to any particular programming language's syntax; they must however, be written in such a way as to allow them to be translated fine by line into source code, Pseudocodes must have 2 heading indicating the name of the algorithm land a succinct description of what it does _@)* Plowing exerte shows how to represent the obove algorithm by using ‘6 pseuocode algorithm. ‘Sum:Finding Algorithm This aigarithm accepts two numbers, finds the sum ad ifthe user so desires, ‘prints the sum, svat Declore Sum, num1, num2 os integers Dectere ans 0s character sum €0 Write "Eoter 2 numbers” Read nuent, num2 ‘Sum = num + num? Write “Would you like to view the sure (vf WNfors =") then Write “The sum is’, Sum enalp stop 3. Narratives ~ a narative ic 2 detailed worded ‘representation of an algorithm. I is explet in Its depietion ofthe steps that must he followed ta pretuce thedesired results) 5) The following example shows how to represent the cbave algorithm by using BEGIN Set Sum to 2er0 Prompt the user to enter two. nambers Accept the numbers Store the numbers in 2 variables called nud and num? respectively ‘Add num’ end aum2 Stove the eset in Sum ‘Ask the userf they'd lke to view the sum of the eumbers Accept the answer Store the onswer in voriable coed Check f the value of ens ¥ 1fs0, the user should be informed of {the sum ofthe two numbers END ivecmesuratie bac MW Computer Scierce, constructs are systemmic Methods which determine how datas handled in an Algorithm oF computer program, ‘The four (4) constructs are: 4, Output Statement this allows a program to ‘communicate with the user by outputting Information ze them. Commands such 3s print, write, output or display may be used in algorithms, Exomple: Print “What is your name?” 2. Input Statement — this allows for the ucer to Interact with the program by allowing them to fenter data inta it. Commands such as read or Input may be used in algorithms Example: Read student_name 3. Assienment Statement ~ thie used to stare data in avariatle or constant or to change data in a variable. When assigning a value to 3 variable, the equal sign is used, Example, nummber= 200. When initializing a variable however, the let: pointing arrow () is used. Example, sum € 0. 4, Control Structures — these are used to determine how the instructions in the algorithm/program are executed. The three control structures are: :L Sequencing —this structure sees tit that instiuctions are executed line by line, one ster the other, in the order which they were written, Example, in the following elgorithen, lnstauctions are executed one line after the other. 1. Write “What i your nome? 2. Read name 3. Write “Hello there", name 2. Selection — this structure sees ta it that fone set of instructions is executed if a particular erterion is met; otherwise, that set of instructions is bypassed or another set of instructions is executed, Exompiel: Age =35 Pads sshtee White “Wow! You ore 35?” Write "You must be very experienced” Enaip (since Age 15 equa} t0 35, the block of Instructions is executed) Example: Age=13 (age =35) then Write Wee! You are 357” Waite “You must be very experienced” Enaif (Seeing that age Is not equal to 35, the block of nstrucions is nat executed) Examples: Age = 13 If (Age =35) then Write “Wow! You are 35° Write “You must be very experienced” tse Write Tsk? Tak Child” Write “You have along way to 90" enaif (The criterion wos not met and aca result, the second set of instructions was executed; eration Repetition — this structure etermines the number of times. 3 particular instruction or block of, instructions is executed, based on one or more consitions, They ave also refarrod ta 2s loops. Present ae the: 1. For Loop ~ This loop allows for an Instruction or block of nstructions to be repeated fora specified number 3. Repeat..Untll Loop ~ inthis loop, an of times. It is therefore called 2 Instruction or block of instructions is eoundes loop a¢ the number of executed untila condition met times itil be executed is fixed, xample Example: sun=0 Farcounter= 1 to 10 do Reveot Waite “Enter name #”, counter Write “Enter @ number ead name feounter) Read aur endfor Sumy = Sum + num Write “Do you want to enter 2. While Loop —inthisloop,acondition ‘another number? Y/N" Is set and then an instruction of Read ons block of instructions is executed if Uni ans =" the condition is met. If tae precise (Urtounded loop; the loop is moment when the loop will end Is ‘repeated untl the vser enters ¥) known, the loop Is conskdered a bounded loop. if the precise moment isnot known however, i ‘considered an unbounded loop, Example: xet While X<=5 do. waite x exer Endwhile (Bounded loop; the oop will repeat five times) Ree Interpreting an algorithm not only involves understanding what each line of instruction is commanding to be done, but also having an Understanding of how each instruction relatesto the other. The CAPE Computer Science Examination tests how well students understand algorithms by allowing them to write the output from a code and/or allowing them to trace theough an algorithm and literally draw the output Before tracing through an alzorithen instructing the student to draw the output, the instructions on how to use keywords should be carefully examined and Understood. Such algorithms always produce an easily identifiable shape. Therefore, if you are halfway through drawing. the output and no identiable shape is being formed, recheck quickly tosee that you have been following the instrutions explicitly Example: trace through the execution of following ‘algorithm end drow the output. Nate the folowing ‘= printSpaceste) prints m spaces from the curtent cursor position Adash(-)is tobe used torepresenta space. printing) contiues output on the current line from the current position of the cursor but ‘ny subseruent output is printed on a nev. Ine. © print) continues output on the current tine from the current cursor positon, maG-0 star x=MAG+4 for (count =1 0 (2*10)) print (*) prion while bx< 4) printSpaces () print (*) y=(@=x01)*2 Wyo) printSeaces (y) ring () +4 endveile stop The output for this algorithm would look ike this Une aderaudiveesensanns Line 2 7 Mii aspect of te sylabus tests the student's ablity fees Ho find errors within an algorithm and implement BpHOpFate corrective measures. The errors maybe Linea -t Hla semantic, ological in nature. Lines tines a he CAPE Comsuter Science Examination provides oie . Wie student with questions which instruers them to enity te ines nan. algorithm which containg Lines > aaaeee IOI, identity tive exact errors, and also correct Lines b They mar also provide the student with an Line 10 Which generates a particular output anc Bik the student to modify i to produce anether Dutpit, which they wil state ‘see overteat> Sxample: The garth below ts designed (0 j ana generate print and count the ede numbers between Voriabienome| bata Results 1 lincusive) and 99 (ncusve. There ore however = errors in the algoith, ° ; : Line Begin 7 si Une2 = Ber lines ent a ante2-o A Lines white (999) sgeeg | Lines pring @ F tunes a=ae2 fi Line 7 cxctt [ Line ence ‘ = tines print (“c= <) tine10 print "a=", 4) 4 = bine én e a |a-s8e2=100| 9-100 What are the final values in the variables © and es SRerr omen Gaee. {atthe end of the algerishmn? Usea trace table to traverse the olgocthrn The fino! values of ¢ and q at the end of the ‘algorithm are 190 and 50 respectively Seo overleafs 1, Identify and comet the trrars in the algorithm, Wirlte the line number fo: each error in braces. Une 2/4. Line 3/e=0 ne | while fo <= 99) Yorioble Name W has been evidert over the years that students © Using the corrected algorithm, give the volue of aca & variable q at the end of the execution. Developing Algorithms siting the CAPE Cemputer Science Unit 1 exam do poorly at questions requiring them to develop algorithms or write the source code for problems. It Is thought that the students have not acquired or have not owned the skils required to comprehend the question or te approach the answer te the question, e-. To successfully devalop an algorithm, one must fst Understand that algorithms are logically sequenced Instructions. To stat off with, the inputs, processes ‘and outputs must firs be identified. This can be done with the aid of an Input-Processing-Output =a ((P) chart. Newt, the appropriate contol structures | are identified Al algorithms wil require the ‘sequencing structu'e. Some algorthens wll require the selection structure if there are criteria that data reeds to meer anc/or one ofthe Reration sliuctures —4 + if a sat of commards needs to be executed more than ones After the identification of the different constructs, The value of q ct the end of the algorithm Is eu are ready to wrbe the algorithm. Choose « therefore to 3 structured representation (Pseudocode, narrative or flow chart) and eammence writing, Remember to always start your algorithms with the keyword START’ or ‘BEGIN’ and terminate i with “STOP or | 10 "END’. After your START keyword, declare all the variables you Intend to use, and initialize any Variables that will be used to store the results of Calculation to zero (0) Rafersing tothe 1PO chart and uctures identifieg, commence wrlting the ‘commands as they would most logically be carried out Exomple:& teacher of @ lass of 25 students wants to know each student's favorite colour, She wants to now how mony students favour bie, green, ced oF veliow. Cevelor an elgerithm to determine the ‘number of student who favour each colour and ‘output the results t the teacher. 4, Identify the inputs, processes and outputs. oe Processes | Outputs Increment tne | Number of fete loc [eae et the cotour the | liking each ‘each student | *M tee - student chose 2. Mentify the contro structures. + Sequencing Is required throvghout the algorithm, ‘+ IPther Else statements (Selection) wil be ‘equired to increment 0 counter for 0 perticular colour if « student chose that cofour, + A for oop (heration) wil be required to alow iret fram the 25 students 3. Choose @ stuctured representation of the algorithm. (A seudocode wil be used to represent the ‘oorithm) svaRT Declare cou (green_courter, ed_counter, yellow counter os integer Declare none, fave colour as string blue_eounter, blue counter 0 green_courter 0 red counter 0 yellow counter 0 For (counter = 1 t0 25) do Write "What is your name>” ead name Write none, * is your favourite colour blue, green, red ar yellow?” Read fave colour “blue then ‘lue_caunter~ blue counter +1 Ese if fore_colou ‘green counter = green counter 1 ‘green') then ls if (ove colour = red’) then red counter vd counters 1 se Gave_colour = yellow’) then yellow counter = yellow counter +1 Endif endfor Waite bloe_counter, “students lke blue” Write green_counter, “students ike green” Write red_courter, “students ike ced” Write yellow counter, “students like yellow” svop MODULE 3 Programming Programming % the designing of computer rogram. Programs are a ist of instructions which Ate provided to acomputer to instruct to carryout 1 task automaticaly, Programming is much a science as itis an art. There fre defined vaysin which one may go about solving B problem, templates if you may. These templates called programming paradigms. Using programming languages based on one of these emplates will alow you to solve a problem in a Paiticular way versus a programming language Dpsed on another template. What you do with these Programming languages may however be beautiful, reative or thougnt-provokingl You might create something the world has never seen..something ‘new and original This section s dedicated to letting you appreciate the need for diffarent programming languages and ‘also the problem translation process. By chapto'’s fen, you will develop the ability to implement solutions to problems using the © programming language. Programming Paradigms ‘A programming paradigm is an approach to programming a computer to perform a task based ‘n 3Set of mathematical rules oF a set of consistent ang logical principles. Each paradigm supports a set of concepts that renders it ideal for a particular problem, Each programming longuage falls under ‘one or more of the many programming paradigms. Mf the language supports more than one programming paradigms, fi considered to be 2 ‘multiparadigm programming language. ‘The programming paradigms that willbe looked at 1. Procedural/Imperative Paradigm 2. Object-Oriented Paradigm (OOP) Funetional Paradigm Declarative Paradigm Aspect-Oriented Paradigm (AGP) Scripting Paradigm This Is by no means the exhaustive list of ‘programming paradigms, but only reflects what the CAPE Computer Science syllabus requires for the Unit 1 examination ieee elcome Inthe beginning, there was binary. The CPU was fed With cose in binary and that was the only thing it Understood. Binary was like nutrients. Now, they S| understand only binary... but now, they can be fed with 2 wider variety of foods (programing Tanguages). These focds however, have to be Hlgested into nutients (translated) before the Computer can use them. Lets look st the evolution fl the programminglanguages and how they fed the (CPU with informatien A, First Generaton Programming Language (ast) AGL is a machine-evel programming language which was writen in ’sand.0's. 161 is referred 0 as low-eval language. The code, being binary, could be understood and used directly bbya CPU asit isthe atte language ofthe CPU. Thie climinated the need for compilers or translators. Programs written in 1GL ran very fast and ffidently as thoy were directly ‘executed by the COU. Because everything had tobe specifiedin 1GLs and all ode was written in 1's anc 0's, these languages were very slificul to earn, Because ofthe plethora of 1's and 0's, it wes also difficult to detect and correct errors mn 1GL programs. 1GL programs were also machine dependent and as such were not portable, that I, they could only be executed on the computer they were written 2. Second Generation Programming Languages (sy) 2GL comprised of assembly languages which used code written using mnemonics to represent low-level machine operations, 2GLs are also referred to as low-level languages. The ‘code is symbolic and must consequently be translated to machine language so. the somputer can understand it, This is accomplished by using on assembler. Assembly language uses easy-to-remember symbols such ‘25 ADD, MOV and CALL and is therelore easier to lear. Source code written in assembly language is also easier to understand and ‘rors are more easly Identified than iy 1GL 2GL programs were only able to be transferred to other computers which had the same type ©} processor and eevironment; they were Partilly-portable. Due to the assembling process 2GL had to go through, they were not 95 fst a5 16L. They were however faster than their successors J. Third Generation Programming Languages (61) These are the successors to 2Gts. 361s are considered to be high-level languages as they are closer to human languages like English AGLs allow for Implementations of certain functions, tke which register to put Information in, to be hidden from the Programmer. | Programming time Consequently reduced, 3Gls are easier to code Jnthan 1GLand 26Ls, asthey utlize English ike statements to represent machine operations ‘They are consequently easier to understand land error-fnding and correction 's made less tedious: Programs written in 3GLs tend to be rected more slowly than their predecessors however, 2s they have to be preprocessed then translated before the instructions can be linderstood by the CPU. They are generally portable, teing able to be executed on different computer systems ence compiled, 4, Fourth Generation Programming Languages (ast) 4GLs are cansidered to be even higher level languages than 3Gis as they are even claser to any human language, like English. This proves particular advantageous to people who have Hite forma training in programming. They allow for more operations to be performed using lester commands than their predecessors. They improve upon the advantages discussed for 3Gls above and have the same disadvantages as well. 461 are used when develoging database querying systems, feport generators, GUI creators, report Renerators ete, Fifth Generation (561) 5GLs are considered to bein a totaly different lass from the other generations of Programming languages. This is because they take an entirely different approach to artving at the solution to a problem than the other Benerations, This approzch sees to problems being solved by specifying conditions and constraints to the program in a logical manner rather than by using a programmer-wrtten gorithm. SGLs are mainly used in artificial inteligence research. Logical and some declarative programming languages are SGLs, ogramming Languages edural/Imperative Paradigm The concept of the procedural oF imperative Paradigm is that commands are executed in the Act order as stated In a program. A [procedural/imperatve language tells a computer WoW {0 do something rather than what to do. The TOfder in which the commands are executed is Watyrmined by control structures (sequencing, election or resetitionl. This paradigm is Komparable to a recipe for 2 cake, as each Jnstrction in the recipe must be carried out in the Dose order that was stated in order for the cake Ap comme out eight (Gree +1017 ich ating dh etic aie preheat tea 30°F Whisk 10a 56 Samoan tgs ox ge ‘elt 1 se, gemma. mc ot 19, Wo together 9 ag an then carne them te rate to he Baling eh an et The procedurai/imperative paradigm utilizes the concept of proceduces (similar to functions). A procedure's @ sequence of commands which carries ‘outa single task and can be used repestedly Programming languages based on this paradigm are BASIC, Pascal, FORTRAN, Algol et. Disscneneckemrmee Object-Oriented Programming is currently one of he most popular approaches to developing ‘oftware programs its an approach in which focus Th placed on objects and their attributes and Object-oriented programming Involves creating « system of components which fnicapsulote data 2rd functions, inherit these things Hfom ether components and communicate via siessages with eack other. OOP isa modular type of programming The characteristics of Object Oriented Programming are 4, They have classes and objects. Object-Oriented Programming closely Fesembles the real world. In the real world there are things called objects with which we Interact. Those objects may be thought to be a part of something more general called a class. Example, a Berzis an object of the class cors In OOP, a class is the blueprint from which objects are created. ‘Asa rosul all objects of the class cars will have the same general attributes. So, all cars wi have a make, model and colour and will be able to accelerate, steer and stop. However, there might be several objects belonging tothe class cars with added attributes. There could he 2 BMW capable of Wi-Fi connectivity or an Audi Capable of self-parking, These are referred to 2&5 instances of the class cars. Objects are therefore instances or particular occurrences of a class. More specifically, objects are sel ‘contained entities which contain properties and methods to make a particular type of data Useful, Objects do not require additional attributes to. their innate attributes to be considered different from another object. They ‘must however be declared with 3 unique Objects have both state and behaviour, State refers to whatever is constant at a particular moment in time, for example, the state of a Benz may be parked. Behaviour refers to what the objectis cpable of doing, for example, the behaviours of a Sena are driving, braking and playing, music. An object's variables and data structures are responsible for storing its state and the procedures/methods are responsible for expressing its behavicur(s). Methods ‘operate on ar object's internal state and are the primary means by which objects communicate with each other, They allow for Abstraction This the practice of simplifying a problem by Creating. classes which are as general at Possible. the purpose of doing this to allow for the classes to be able to be used in other solutions without the need to create a new cass_which Is extremely similar. So, a generalized perentclast may be created and then child-classes created which focus on the details of the problem; these too must however be aseneralas possible }. They allow fortnheritance. This Is the ability of objects to acquire the attributes of their class and ako for classes to acquire the attributes of other classes Inbertance lows for attributes to be ‘2oquired, but does not bar the object or class which is Inheriting from having additional Unique attributes. In the case of classes, the dass which is inheriting attributes is called the subclass or cild-lass andthe class Fromm which the subclass/child-ciass is inheriting is called the superclass or parent cass, Subdlasses/child-classes are specialized versions of ther supercless/parent-clas. |. They allow for Data Encapsulation, This is the ability of objects to hide their implementation, that i, hide the complexity behind how they achieve their functionality, In objectoriented programming, hiding the implementation of an object can prevent other ‘objects from inheriting any attributes defined in the implementation. This must however be specified by, for example, decaring the ‘methods in the implernentation as private Declaring @ method as public is used in eases winere inheritance fs dea! 50, if a person were to use an object called Prepare chicken(, they would not be Interested in the other things that might have had to occur to let them have a chicken to Drepare. So when they want to use the prepare_chicken method, the kilLchicken(), ut_chicken(), defeather_chicken() and package_chicken() methods would be hidden from them. “The two reasons for encapsulation are: A. To provide a simple and comprehensible way to use objects without the need for the understanding of how it wos accomplished 2. To allow for change to the Implementation of 2 method to occur While no affecting the capabilities of the ‘method. 5. They allow for Polymorphism. ‘This the abitty to accomplish a task by using A variety of objects So, fone wanted to draw picture of a dog, they could use a pencil, @ [pen a markeror a crayon, Polymorphism may be implemented throush Subclasses. Ths entails using a parentclass or any of its chibl

You might also like