Computer Science Level 6 Learning Guide
Computer Science Level 6 Learning Guide
LEARNING GUIDE
FOR
COMPUTER SCIENCE
LEVEL 6
TVET CDACC
P.O. BOX 15745-00100
NAIROBI
First published 2020
Copyright TVET CDACC
All rights reserved. No part of this learning guide may be reproduced, distributed, or transmitted
in any form or by any means, including photocopying, recording, or other electronic or mechanical
methods without the prior written permission of the TVET CDACC, except in the case of brief
quotations embodied in critical reviews and certain other non-commercial uses permitted by
copyright law. For permission requests, write to the Council Secretary/CEO, at the address below:
Council Secretary/CEO
TVET Curriculum Development, Assessment and Certification Council
P.O. Box 15745–00100
Nairobi, Kenya
Email: [email protected]
i
FOREWORD
The provision of quality education and training is fundamental to the Government’s overall
strategy for social economic development. Quality education and training will contribute to
achievement of Kenya’s development blueprint and sustainable development goals. This can only
be addressed if the current skill gap in the world of work is critically taken into consideration.
Reforms in the education sector are necessary for the achievement of Kenya Vision 2030 and
meeting the provisions of the Constitution of Kenya 2010. The education sector has to be aligned
to the Constitution and this has triggered the formulation of the Policy Framework for Reforming
Education and Training (Sessional Paper No. 4 of 2016). A key provision of this policy is the
radical change in the design and delivery of the TVET training which is the key to unlocking the
country’s potential in industrialization. This policy document requires that training in TVET be
Competency Based, Curriculum development be industry led, certification be based on
demonstration and mastery of competence and mode of delivery allows for multiple entry and exit
in TVET programs.
These reforms demand that industry takes a leading role in TVET curriculum development to
ensure the curriculum addresses and responds to its competence needs. The learning guide in
Computer Science enhances a harmonized delivery the competency-based curriculum for
Computer Science Level 6.
It is my conviction that this learning guide will play a critical role towards supporting the
development of competent human resource for the Computer Science sector’s growth and
sustainable development.
PREFACE
Kenya Vision 2030 is anticipated to transform the country into a newly industrialized, “middle-
income country providing a high-quality life to all its citizens by the year 2030”. The Sustainable
ii
Development Goals (SDGs) further affirm that the manufacturing sector is an important driver to
economic development. The SDG nine that focuses on Building resilient infrastructures,
promoting sustainable industrialization and innovation can only be attained if the curriculum
focuses on skill acquisition and mastery. Kenya intends to create a globally competitive and
adaptive human resource base to meet the requirements of a rapidly industrializing economy
through life-long education and training. TVET has a responsibility of facilitating the process of
inculcating knowledge, skills and attitudes necessary for catapulting the nation to a globally
competitive country, hence the paradigm shift to embrace Competency Based Education and
Training (CBET). The Technical and Vocational Education and Training Act No. 29 of 2013 and
the Sessional Paper No. 4 of 2016 on Reforming Education and Training in Kenya, emphasized
the need to reform curriculum development, assessment and certification to respond to the unique
needs of the industry. This called for a shift to CBET to address the mismatch between skills
acquired through training and skills needed by industry as well as increase the global
competitiveness of Kenyan labor force.
The TVET Curriculum Development, Assessment and Certification Council (TVET CDACC), in
conjunction with TVET training institution trainers developed the Occupational Standards which
was the basis of developing competency-based curriculum and assessment of an individual for
competence certification for a Computer Science Level 6. The learning guide is geared towards
promoting efficiency in the delivery of curriculum.
The learning guide is designed and organized with clear and interactive learning activities for each
learning outcome of a unit of competency. The guide further provides information sheet, self-
assessment, tools, equipment’s, supplies, and materials and references.
I am grateful to the Council Members, Council Secretariat, Computer Science experts and all those
who participated in the development of this learning guide.
ACKNOWLEDGEMENT
This learning guide has been designed to support and enhance uniformity, standardization and
coherence in implementing TVET Competency Based Education and training in Kenya. In
developing the learning guide, significant involvement and support was received from various
organizations.
iii
I recognize with appreciation the critical role of the participants drawn from technical training
institutes, universities and private sector in ensuring that this learning guide is in-line with the
competencies required by the industry as stipulated in the occupational standards and curriculum.
I also thank all stakeholders in the Computer Science sector for their valuable input and all those
who participated in the process of developing this learning guide.
I am convinced that this learning guide will go a long way in ensuring that workers in Computer
Science sector acquire competencies that will enable them to perform their work more efficiently
and make them enjoy competitive advantage in the world of work
iv
ACRONYMS
v
TABLE OF CONTENTS
FOREWORD ................................................................................................................................ ii
PREFACE ..................................................................................................................................... ii
ACKNOWLEDGEMENT .......................................................................................................... iii
ACRONYMS ................................................................................................................................. v
TABLE OF CONTENTS ............................................................................................................ vi
LIST OF TABLES ........................................................................................................................ x
LIST OF FIGURES ..................................................................................................................... xi
LIST OF GRAPHS .................................................................................................................... xiv
CHAPTER 1: INTRODUCTION ............................................................................................. 1
1.1 Background Information ................................................................................................. 1
1.2 The Purpose of Developing the Trainee Guide............................................................... 1
1.3 Layout of the Learning Guide ......................................................................................... 1
CHAPTER 2: COMPUTER ORGANISATION AND ARCHITECTURE ............................ 4
2.1 Introduction ..................................................................................................................... 4
2.2 Performance Standard ..................................................................................................... 4
2.3 Learning Outcomes ......................................................................................................... 4
2.3.1 List of Learning Outcomes ......................................................................................... 4
2.3.2 Learning Outcome 1: Understand Principles of Computer Organization and Design5
2.3.3 Learning Outcome 2: Understand Central Processing Unit functions ..................... 13
2.3.4 Learning Outcome 3: Understand Computer Memory Organization .......................... 21
2.3.5 Learning Outcome 4: Understand Input-Output functions ....................................... 33
2.3.6 Learning Outcome 5: Understand computer arithmetic and logic ........................... 49
CHAPTER 3: OPERATING SYSTEMS ................................................................................. 70
3.1 Introduction ......................................................................................................................... 70
3.2 Performance Standard ......................................................................................................... 70
3.3. Learning Outcomes ............................................................................................................ 70
3.3.1. List of learning outcomes ............................................................................................ 70
3.3.2 Learning Outcome No 1: Understand fundamentals of operating systems .............. 71
3.3.3 Learning Outcome 2: Understand Process Management ......................................... 89
3.3.4 Learning Outcome 3: Understand Memory Management ......................................... 111
3.3.5 Learning Outcome 4: Understand Input and Output Management ....................... 126
3.3.6 Learning Outcome 5. Understand File Management and local policy settings ........ 158
CHAPTER 4: MATHEMATICS FOR COMPUTER SCIENCE ........................................ 170
4.1 Introduction ....................................................................................................................... 170
vi
4.2 Performance Standard ....................................................................................................... 170
4.3 Learning Outcomes ........................................................................................................... 170
4.3.1 List of Learning Outcomes ........................................................................................ 170
4.3.2 Learning Outcome 1: Understand Linear Algebra ..................................................... 172
4.3.3 Learning outcome 2: Understand Boolean Algebra ................................................... 183
4.3.4 Learning outcome 3: Understand Set Theory ............................................................ 192
4.3.5 Learning outcome 4: Understand Calculus ................................................................ 199
4.3.6 Learning outcome 5: Understand Probability and Statistics ...................................... 211
CHAPTER 5: FUNDAMENTALS OF PROGRAMMING .................................................. 222
5.1 Introduction ....................................................................................................................... 222
5.2 Performance Standard ....................................................................................................... 222
5.3 Learning Outcomes ....................................................................................................... 222
5.3.1 List of Learning Outcomes ........................................................................................ 222
5.3.2 Learning Outcome 1: Understand programming concepts ........................................ 223
5.3.3 Learning outcome 2: Understand the Java Environment ........................................... 227
5.3.4 Learning outcome 3: Perform Data Operations ........................................................ 241
5.3.5 Learning outcome 4: Use Control Statements ........................................................... 253
262
5.3.6 Learning Outcome 5: Use Methods .......................................................................... 263
5.3.7 Learning Outcome 6: Understand Object Oriented Programming ............................ 272
CHAPTER 6: DATABASE MANAGEMENT SKILLS ....................................................... 279
6.1 Introduction ....................................................................................................................... 279
6.2 Performance Standard ....................................................................................................... 279
6.3 Learning Outcomes ........................................................................................................... 279
6.3.1 List of Learning Outcomes ........................................................................................ 279
6.3.2 Learning Outcome 1: Understand database fundamentals ......................................... 280
6.3.3 Learning Outcome 2: Design a database.................................................................... 310
6.3.4 Learning Outcome 3: Use Structured Query Language (SQL).................................. 330
6.3.5 Learning Outcome 4: Understand design of object oriented databases ..................... 357
6.3.6 Learning Outcome 5: Understand indexing and hashing ........................................... 371
6.3.7 Learning Outcome 6: Understand Database applications .......................................... 377
CHAPTER 7: INFORMATION SYSTEMS .......................................................................... 392
7.1 Introduction ....................................................................................................................... 392
vii
7.2 Performance Standard ....................................................................................................... 392
7.3 Learning Outcomes ........................................................................................................... 392
7.3.1 List of Learning Outcomes ........................................................................................ 392
7.3.2 Learning Outcome 1: Understand fundamentals of Information Systems ................. 393
7.3.3 Learning outcome 2: Understand the Software Development Process ...................... 400
7.3.4 Learning outcome 3: Demonstrate Human Computer Interaction Principles ............ 412
7.3.5 Learning outcome 4: Understand the VB.NET programming environment .............. 417
7.3.6 Learning outcome 5: Develop and test a VB.NET application .................................. 427
CHAPTER 8: NETWORKING AND DISTRIBUTED SYSTEMS..................................... 448
8.1 Introduction ....................................................................................................................... 448
8.2 Performance Standard ....................................................................................................... 448
8.3 Learning Outcomes ........................................................................................................... 448
8.3.1 List of Learning Outcomes ........................................................................................ 448
8.3.2 Learning Outcome 1: Understand networking and distributed systems concepts ..... 449
8.3.3 Learning Outcome 2: Understand Distributed Systems Architectures ...................... 476
8.3.4 Learning Outcome 3: Understand Distributed Processing and File Management ..... 485
8.3.5 Learning Outcome 4: Set up a Network in a Distributed Environment ..................... 492
8.3.6 Learning Outcome 5: Understand Data Communication Standards and IP Addressing
............................................................................................................................................. 506
8.3.7 Learning Outcome 6: Troubleshoot a Network ......................................................... 517
CHAPTER 9: ARTIFICIAL INTELLIGENCE ................................................................... 530
9.1 Introduction ....................................................................................................................... 530
9.2 Performance Standard ....................................................................................................... 530
9.3 Learning Outcomes ........................................................................................................... 530
9.3.1 List of Learning Outcomes ............................................................................................ 530
9.3.2 Learning Outcome 1: Understand Artificial Intelligence fundamentals .................... 531
............................................................................................................................... 536
9.3.3 Learning outcome 2: Understand problem solving techniques .................................. 538
9.3.4 Learning outcome 3: Understand Python programming environment ....................... 549
9.3.5 Learning outcome 4: Develop Artificial Intelligence programs using Python .......... 574
CHAPTER 10: ALGORITHMS AND DATA STRUCTURES ........................................... 581
10.1 Introduction ................................................................................................................. 581
viii
10.2 Performance Standard ..................................................................................................... 581
10.3 Learning Outcomes ......................................................................................................... 581
10.3.1 List of Learning Outcomes ...................................................................................... 581
10.3.2 Learning outcome 1: Understand fundamental principles of algorithms ................. 582
10.3.3 Learning Outcome 2: Understand fundamental concepts of data structures ........ 589
10.3.4 Learning Outcome 3: Understand Linked lists ..................................................... 601
10.3.5 Learning Outcome 4: Understand Stacks and Queues .......................................... 610
10.3.6 Learning Outcome 5: Understand Search Techniques.......................................... 619
CHAPTER 11: WEB DESIGN SKILLS ................................................................................ 631
11.1 Introduction ................................................................................................................. 631
11.2 Performance Standard ................................................................................................. 631
11.3 Learning Outcomes ..................................................................................................... 631
11.3.1 List of Learning Outcomes ................................................................................... 631
11.3.2 Learning Outcome 1: Understand HTML basics .................................................. 632
11.3.3 Learning Outcome 2: Use HTML Elements ......................................................... 636
11.3.4 Learning Outcome 3: Demonstrate Web Page Formatting ................................... 641
11.3.5 Learning Outcome 4: Apply Styles....................................................................... 647
11.3.6 Learning Outcome 5: Understand JavaScript ....................................................... 651
11.3.7 Learning Outcome 6: Use JavaScript Data types ................................................. 658
11.3.8 Learning Outcome 7: Use JavaScript Functions ................................................... 666
11.3.9 Learning Outcome 8: Use JavaScript Libraries .................................................... 671
CHAPTER 12: GRAPHIC DESIGN ...................................................................................... 676
12.1 Introduction ..................................................................................................................... 676
12.2 Performance Standard: .................................................................................................... 676
12.3 Learning Outcomes ......................................................................................................... 676
12.3.1 List of Learning Outcomes ...................................................................................... 676
12.3.2 Learning Outcome 1: Understand Graphic Design Fundamentals .......................... 677
12.3.3 Learning Outcome 2: Understand elements and principles of graphic design ........ 681
12.3.4 Learning Outcome 3: Apply typography techniques ............................................... 691
12.3.5 Learning Outcome 4: Create and edit images .......................................................... 705
12.3.6 Learning Outcome 5: Perform layout design ........................................................... 716
12.3.7 Learning Outcome 6: Print Design .......................................................................... 726
ix
LIST OF TABLES
Table 1: Basic Units of Learning .................................................................................................... 2
Table 2: Common Units of Learning .............................................................................................. 2
Table 3: Core Units of Learning ..................................................................................................... 2
Table 4: Primary and secondary memory ..................................................................................... 26
Table 5: Differences between Cache Memory and Virtual Memory ............................................ 29
Table 6: Examples of input devices .............................................................................................. 34
Table 7: Examples of common output devices ............................................................................. 35
Table 8: Number System Relationship ......................................................................................... 51
Table 9: ASCII .............................................................................................................................. 53
Table 10: System requirements for installing Windows 10 .......................................................... 82
Table 11: Comparison among Schedulers .................................................................................... 96
Table 12: Boolean Laws, Theorems and Expressions ................................................................ 186
Table 13: Commo derivative functions ....................................................................................... 205
Table 14: Common Derivative Rules.......................................................................................... 205
Table 15: The techniques/rules of integration............................................................................. 208
Table 16: Java Arithmetic Operators .......................................................................................... 248
Table 17: SQL comparison keywords ......................................................................................... 340
x
LIST OF FIGURES
xi
Figure 42: Memory Address Translation .................................................................................... 115
Figure 43:Segmentation .............................................................................................................. 117
Figure 44:Virtual Memory .......................................................................................................... 118
Figure 45:Demand Paging .......................................................................................................... 119
Figure 46:Device Controllers ...................................................................................................... 127
Figure 47:Memory-mapped I/O .................................................................................................. 128
Figure 48: Windows Disk Manager ............................................................................................ 135
Figure 49:Disk Fragmentation .................................................................................................... 150
Figure 50: Windows Device Manager ........................................................................................ 153
Figure 51:Windows File explorer ............................................................................................... 163
Figure 52: Windows file sharing ................................................................................................. 164
Figure 53:Customising Files and directories using the File Explorer ......................................... 166
Figure 54:Configuring Local security policy .............................................................................. 168
Figure 55:Venn diagram ............................................................................................................. 194
Figure 56:Intersection of two sets ............................................................................................... 195
Figure 57:Complement of a set ................................................................................................... 195
Figure 58:Universal set ............................................................................................................... 196
Figure 59: MSAccess Database Sample ..................................................................................... 280
Figure 60:: MSAccess Table Sample ......................................................................................... 281
Figure 61: : MSAccess Table Records Sample ........................................................................... 281
Figure 62:: MSAccess Table Fields Sample. .............................................................................. 282
Figure 63:: MSSQL Server Interface .......................................................................................... 298
Figure 64: Database Data Modelling .......................................................................................... 310
Figure 65: Demonstrating Conceptual Data Model .................................................................... 311
Figure 66:Logical data Modelling............................................................................................... 312
Figure 67:Physical Data Modelling ............................................................................................ 313
Figure 68:Demonstrating an Entity ............................................................................................. 314
Figure 69:Entity Relationships.................................................................................................... 316
Figure 70:ER diagram with basic objects ................................................................................... 316
Figure 71: Elements in ER diagrams .......................................................................................... 317
Figure 72:Binary relationship ..................................................................................................... 318
Figure 73:Ternary relationship.................................................................................................... 318
Figure 74:Quaternary relationship .............................................................................................. 319
Figure 75:Recursive relationship ................................................................................................ 319
Figure 76:Entities associated through two distinct relationships with role names ..................... 320
Figure 77:ER diagram of Staff and Branch entities and their attributes ..................................... 320
Figure 78:Hashing in a database ................................................................................................. 373
Figure 79: Horizontal database fragmentation ............................................................................ 380
Figure 80:Vertical database fragmentation ................................................................................. 380
Figure 81:Hybrid database fragmentation.................................................................................. 380
Figure 82:Star Schema ................................................................................................................ 386
Figure 83:Snowflake Schema ..................................................................................................... 387
Figure 84:Fact Constellation Schema ......................................................................................... 387
xii
Figure 85:The Information Security Triad: Confidentiality, Integrity, Availability (CIA) ........ 396
Figure 86:SDLC waterfall ........................................................................................................... 401
Figure 87:The RAD methodology .............................................................................................. 402
Figure 88:Data Flow Diagram .................................................................................................... 404
Figure 89:Entity Modeling notations .......................................................................................... 407
Figure 90:Visual Studio IDE....................................................................................................... 419
Figure 91:VB.NET - Windows Forms ........................................................................................ 424
Figure 92:ADO.Net Object Model.............................................................................................. 434
Figure 93: VB.NET DataSet objects ........................................................................................... 436
Figure 94:Network components .................................................................................................. 451
Figure 95:LAN ............................................................................................................................ 453
Figure 96:MAN ........................................................................................................................... 454
Figure 97:WAN........................................................................................................................... 454
Figure 98:PAN ............................................................................................................................ 455
Figure 99:Star topology .............................................................................................................. 455
Figure 100:Ring topology ........................................................................................................... 456
Figure 101:Mesh topology .......................................................................................................... 458
Figure 102:Bus Topology ........................................................................................................... 459
Figure 103: Client Server Distributed Model ............................................................................. 464
Figure 104:Peer-to-peer Distributed Model ................................................................................ 465
Figure 105:Client Server Interaction........................................................................................... 478
Figure 106: Edge servers............................................................................................................. 480
Figure 107:Data Network showing devices ................................................................................ 493
Figure 108:Hub ........................................................................................................................... 495
Figure 109: How a switch works ................................................................................................ 497
Figure 110:How a bridge works.................................................................................................. 497
Figure 111:How a Wireless Access Point works ........................................................................ 498
Figure 112:Router ....................................................................................................................... 498
Figure 113: How a firewall works .............................................................................................. 499
Figure 114: OSI model layers ..................................................................................................... 506
Figure 115:Ping utility ................................................................................................................ 521
Figure 116:Tracert/traceroute utility ........................................................................................... 521
Figure 117:Netstat utility ............................................................................................................ 523
Figure 118:Pathping utility ......................................................................................................... 525
Figure 119:Mtr utility.................................................................................................................. 525
Figure 120: Networking Issues resolution .................................................................................. 525
Figure 121: AI related fields ....................................................................................................... 532
Figure 122:Intelligence agent...................................................................................................... 534
Figure 123: K-Nearest Neighbour-Image showing how similar data points typically exist close to
each other .................................................................................................................................... 575
xiii
LIST OF GRAPHS
xiv
CHAPTER 1: INTRODUCTION
This learning guide consists of interactive learning activities, content, self-assessment and relevant
and related references that enhance implementing of Computer Science level 6 qualification. It
enables the trainee to acquire the competencies that enable him/her to undertake the various
processes in Computer Science. The Guide further provides illustration, web links, case studies,
examples and resources on how to implement all the learning outcomes/elements described in the
Curriculum and occupational standards with a focus to a trainee level 6.
• Learning Activities
For each learning outcome, the learning activities are presented covering the performance criteria
statements and trainee’s demonstration of knowledge in relation to the range in the occupational
standard and content in the curriculum.
● Information Sheet
The information sheet is section under each learning outcome that provides the subject matter in
relation to definition of key terms, method, processes/procedures/guidelines, content, illustrations
(photographs, pictures, video, charts, plans, digital content, and simulation) and case studies.
1
• Self-Assessment
Self-assessment is to the performance criteria, required knowledge, skills and the range as stated
in the occupational standards. The section further provides questions and assignments in which
trainees demonstrate that they have acquired the required competences and an opportunity to
reflect on what they have acquired. It is expected that the trainer keeps a record of their plans, their
progress and the problems they encountered which will go in trainee’s portfolio. A portfolio
assessment consists of a selection of evidence that meets the pre-defined requirements of
complexity, authenticity and reliability. The portfolio starts at the beginning of the training and
will be the evidence for the development and acquisition of the competence (summative and
formative) by the student. It is important to note that Portfolio assessment is highly emphasized in
the learning guide
Finally, the guide presents tools, equipment’s, supplies and materials for each learning outcome as
guided by the performance criteria in occupational standards and content in curriculum.
References, relevant links and addendums are provided for further reading. The units of
competency comprising this qualification include the following common and core unit of learning:
2
Unit of Learning Code Unit of Learning Title Duration in Credit
Hours Factor
IT/CU/CS/CR/01/6/A Computer organization and 140 14
architecture
IT/CU/CS/CR/02/6/A Operating systems 130 13
IT/CU/CS/CR/03/6/A Mathematics for computer 140 14
science
IT/CU/CS/CR/04/6/A Fundamentals of programming 180 18
IT/CU/CS/CR/05/6/A Database management skills 160 16
IT/CU/CS/CR/06/6/A Information system 150 15
IT/CU/CS/CR/07/6/A Networking and distributed 210 21
systems
IT/CU/CS/CR/08/6/A Artificial intelligence 180 18
IT/CU/CS/CR/09/6/A Algorithms and data structures 170 17
IT/CU/CS/CR/10/6/A Web design skills 200 20
IT/CU/CS/CR/11/6/A Graphic design 170 17
Industrial attachment 480 48
Total 2310 231
Grand Total 2900 290
The total duration of the course is 2900 hours including 480 hours of industrial attachment.
3
CHAPTER 2: COMPUTER ORGANISATION AND ARCHITECTURE
2.1 Introduction
This unit covers the competencies required to understand Computer Organisation and
Architecture. It involves understanding principles of computer organisation and design,
understanding central processing unit functions, understanding computer memory organization,
understanding input-output functions and understanding computer arithmetic and logic.
4
2.3.2 Learning Outcome 1: Understand Principles of Computer Organization and Design
2.3.2.1 Learning Activities
Introduction
This learning outcome covers defining computer organisation, explaining and structure and
function of computer components and identifying hardware components.
Computer Architecture deals with giving operational attributes of the computer or Processor to
be specific. It deals with details like physical memory, ISA of the processor, the no of bits used to
represent the data types, Input Output mechanism and technique for addressing memories.
Examples are things that are transparent to the programmer:
● control signals
● interfaces between computer and peripherals
● the memory technology being used
It is basically a circuit board of a decent size, depending on the size of the computer we’re
dealing with. It facilitates the communication of the other components in the computer. There are
ports on the motherboard that face the outside of the computer, allowing you to plug in different
components into your computer and also to charge it.
Most motherboards also allow you to scale up by including slots that allow for expansion. You
could add in components like CPUs and RAMs, Video cards, and so on. You can also expand the
motherboard by adding more ports that allow you to connect even more auxiliary devices to your
computer. In other words, you have control over just what your computer’s capabilities are.
Apart from this, the motherboard plays other roles like storing some simple information when the
computer is off, such as the system time. That’s why your computer always tells you the correct
time, even when you turn it on after a long time
.
Figure 1:Motherboard
6
Power supply
As the name suggests, it powers all other components of the machine. It usually plugs into the
motherboard to power the other parts. The power supply connects to either an internal battery (on
a laptop) or a plug for an outlet (on a desktop).
They have different input voltage depending on the machine/computer specifications.
Since RAM is only temporary, it has a volatile nature. The minute you turn your computer off, all
of the memory that is stored in RAM is lost. That’s why you’re advised to keep saving the work
7
you do in applications as you go along to avoid losing all of it in case your computer suddenly
goes off.
The more RAM you have, the greater the number of programs that you can run simultaneously.
Figure 4: RAM
Solid state drives have the same kind of memory as the one on your phone or flash drive, also
known as flash memory. They cost more but are also faster and more efficient than traditional
hard drives.
8
The data stored in the hard drive does not disappear when you switch your computer off. It will
be there when you switch the computer back on. You are, however, advised to keep it far away
from magnets as they could damage it and cause you to lose your information.
Video Card
The video card is a dedicated unit for handling image output to be displayed by the monitor. They
come with their own RAM, dedicated to this singular purpose. If your work involves highly
visual work at very high definitions, then you should get yourself a video card to take the load off
your RAM.
Sometimes, the computer may have integrated graphics, where some of the RAM is borrowed for
graphics processing. This happens frequently on laptops, because there is a need to save space.
Using integrated graphics is much less expensive using a graphics card, but is not sufficient for
intense graphics functions.
Optical devices
These have become a lot less common today, with many machines doing away with them
altogether. An optical drive is used to read CDs and DVDs, which can be used to listen to music
or watch movies. They can also be used to install software, play games, or write new information
into a disk.
9
Figure 7: Optical device drive
In summary, here's the inside of a desktop computer with its parts labeled:
Conclusion
At the end of this learning outcome, the learner should be able to define computer organisation,
explain and structure and function of computer components and identify hardware components.
Further Reading
https://www.com/computer-organization-mcqs-basic-operational-concept/
2.3.2.3 Self-Assessment
Written Assessment
1. Which memory device is generally made of semiconductors?
a) RAM
10
b) Hard-disk
c) Floppy disk
d) CD ROM
2. The register which holds the address of the location to or from which data are to be transferred
is called
a) Instruction registers
b) Index register
c) Memory address
d) Memory data register
3. The device which is used to connect a peripheral to bus is called
a. Control Register
b. Interface
c. Communication Protocol
d. None of the above
4. Which of the following is not a form of memory?
a. Instruction cache
b. Instruction register
c. Instruction opcode
d. Both (a and b)
5. Which memory is difficult to interface with the processor?
a. Static memory
b. Dynamic memory
c. ROM
d. None of the Above
6. Which one of the following is an optical device?
a. DVD
b. Mouse
c. Desktop
d. Monitor.
7. What is computer hardware?
a. A medium for data communications
b. A physical device that is driven by data
c. A physical that is driven by software
d. All of the above
8. What does R in RAM stand for?
a. Re-write
b. Read
c. Readable
d. Random
9. DVD stands for?
a. Digital video data
b. Direct video
c. Digital versatile disk
11
d. Direct vertical disk
10. Which among the following storage devices is considered portable
a. Hard Disk
b. Magnetic Tape
c. Flash Drive
d. ROM
Oral Assessment
1. Differentiate functional and basic components.
2. Describe the functions of the RAM
3. What is a chipset?
Practical Assessment
You have been presented a set of hardware components. From the set, identify
• The hard disk
• Memory
• Power Supply
• An optical disk
2.3.2.5 References
1. https://mrcet.com/downloads/digital_notes/IT/COMPUTER%20ORGANIZATION%20(
R17A0510).pdf
2. The "History of Computing" assembled Society by the IEEE Computer in 1996.
12
2.3.3 Learning Outcome 2: Understand Central Processing Unit functions
2.3.3.1 Learning Activities
2.1 The Central Processing Unit is explained. Activities may be carried out in
2.2 CPU architecture is explained groups or as individual
2.3 Role of registers is explained
2.4 Instruction representation and execution is explained
2.5 CPU specifications are prescribed for a user
2.6 CPU specifications are verified for a given computer
Introduction
This learning outcome covers explaining the Central Processing Unit design, CPU architecture,
role of registers, instruction representation and execution, prescribing CPU specifications and
verifying CPU specifications for a given computer.
Definitions
❏ CPU is the electronic circuitry within a computer that carries out the instructions of a
computer program.
❏ Registers, a memory location within the actual processor that works at very fast speeds. It
stores instructions which are waiting to be decoded or executed.
CPU
It is s the electronic circuitry within a computer that carries out the instructions of a computer
program by performing the basic arithmetic, logical, control and input/output (I/O) operations
specified by the instructions.
Types of Processors
There are 2 different types of processors. These include:
● Complex instruction set computers (CISC)
13
● Reduced instruction set computers (RISC)
CISC
These processors can do complex operations, which can be carried out in just one instruction.
They have many different addressing modes and a wide range of instructions that can be used.
For example, a CISC processor might have a 'complicated' instruction designed into the hardware
called 'POWER'. This can take one number from a register, find the power of that number, held in
a different register, and then store the result in yet a third register. So, 2 to the power 4 would be
calculated as 16 and this would be stored in a third register. This would all be done using one
complex instruction, which might take about 3 or 4 CPU clock cycles to complete.
RISC
There are also CPUs that are known as RISC (pronounced ‘risk’), or Reduced Instruction Set
Computers. RISC processors such as ultra-SPARC and ALPHA use a much smaller, simpler set
of instructions than CISC processors and so to carry out any particular programming task may
take many ‘fetch decode execute’ cycles. RISC processors, however, are much more efficient at
processing huge blocks of data than CISC.
Control Unit
This unit controls the operations of all parts of the computer but does not carry out any actual data
processing operations.
14
Functions of this unit are −
● It is responsible for controlling the transfer of data and instructions among other units of a
computer.
● It manages and coordinates all the units of the computer.
● It obtains the instructions from the memory, interprets them, and directs the operation of the
computer.
● It communicates with Input/output devices for transfer of data or results from storage.
● It does not process or store data.
Arithmetic Section
Function of the arithmetic section is to perform arithmetic operations like addition, subtraction,
multiplication, and division. All complex operations are done by making repetitive use of the
above operations.
Logic Section
Function of the logic section is to perform logic operations such as comparing, selecting, matching,
and merging of data.
Role of Registers
Processor register is a quickly accessible location available to a digital processor's central
processing unit.
The registers are an integral part of the CPU. They are a type of memory that can be accessed
very quickly compared to other types of memory. The pieces of information they hold are needed
by the CPU to run each program instruction during a 'fetch-decode-execute cycle' or can be used
to hold values that are generated as part of the ALU working on data. There are a number of very
special registers that do very specific jobs.
15
Buses
A BUS is a data connection between two or more devices connected to the computer. For
example, a bus enables a computer processor to communicate with the memory or a video card to
with the memory.
These buses carry different types of signals. The same types of buses carry only one type of
signal. These buses help to increase the efficiency and accuracy of working.
A computer consists of many components such as motherboard, memory, input/output devices.
These devices work with the help of buses. PC motherboards have buses for expansion and
external devices, all computers have three basic buses.
During the fetch execute cycle, the computer retrieves a program instruction from its memory. It
then establishes and carries out the actions that are required for that instruction.
16
The cycle of fetching, decoding, and executing an instruction is continually repeated by the CPU
whilst the computer is turned on.
1. Fetch
The first step the CPU carries out is to fetch some data and instructions (program) from main
memory then store them in its own internal temporary memory areas. These memory areas are
called 'registers'.
• For this to happen, the CPU makes use of a vital hardware path called the 'address bus'.
• The CPU places the address of the next item to be fetched on to the address bus.
• Data from this address then moves from main memory into the CPU by travelling along
another hardware path called the 'data bus'.
2. Decode
• The next step is for the CPU to make sense of the instruction it has just fetched. This
process is called 'decode'.
• The CPU is designed to understand a specific set of commands. These are called the
'instruction set' of the CPU. Each make of CPU has a different instruction set.
• The CPU decodes the instruction and prepares various areas within the chip in readiness
of the next step.
3. Execute
This is the part of the cycle when data processing actually takes place. The instruction is carried
out upon the data (executed). The result of this processing is stored in yet another register.
Once the execute stage is complete, the CPU sets itself up to begin another cycle once more.
Instruction Set
Instruction sets are instruction codes to perform some task. It is classified into five categories.
17
The instruction set, also called ISA (instruction set architecture) is part of a computer that pertains
to programming, which is basically machine language. The instruction set provides commands to
the processor, to tell it what it needs to do. The instruction set consists of addressing modes,
instructions, native data types, registers, memory architecture, interrupt, and exception handling,
and external I/O.
An example of an instruction set is the x86 instruction set, which is common to find on computers
today. Different computer processors can use almost the same instruction set while still having
very different internal design.
Both the Intel Pentium and AMD Athlon processors use nearly the same x86 instruction set. An
instruction set can be built into the hardware of the processor, or it can be emulated in software,
using an interpreter. The hardware design is more efficient and faster for running programs than
the emulated software version.
Conclusion
At the end of this learning outcome, the learner should be able to explain the Central Processing
Unit design, the CPU architecture, the role of registers and instruction representation and
execution, prescribe CPU specifications and verify CPU specifications for a given computer.
Further Reading
1. https://www.tutorialspoint.com/computer_logical_organization/index.htm
2. https://www.javatpoint.com/computer-organization-and-architecture-tutorial
2.3.3.3 Self-Assessment
Written Assessment
1. A central processing unit (CPU) consists of two main parts:
a. Control unit and arithmetic logic unit.
b. Control unit and RAM.
c. Motherboard and arithmetic logic unit.
d. Control unit and motherboard.
18
2. The CPU control unit is responsible for
a. obtaining instructions
b. interpreting instructions
c. all logic functions
d. both A and B
3. DMA module can communicate with the CPU through
a. Interrupt
b. Cycle stealing
c. Branch instruction
d. None of the above
4. The ALU of a computer
a. Can perform addition, subtraction
b. Perform all types of arithmetic operation
c. Can perform AND OR and Multiplication
d. Contains number of counters
5. CPU gets the address of next instruction to be processed from
a. Instruction register
b. Memory address register
c. Index register
d. Program counter
6. Which one of the following devices is referred to as the ‘brain’ of the computer system?
a. CPU
b. CD-Rom
c. Mouse
d. Scanner
7. What is the other name for the Mother board
a. System processor
b. System platform
c. System unit
d. System board
8. What makes the computer to be an ‘electronic’ machine?
a. It works using electricity
b. It works without moving parts
c. It has a CPU
d. It has moving parts
9. What is the name given to devices designed to protect the computer from static electricity?
a. Anti-static devices
b. Power surge protectors
c. Personal equipment
d. Computer Hardware
Oral Assessment
Describe the role of buses.
19
Practical Assessment
Identify the following CPU specifications from your computer
• Clock Speed
• Manufacturer
• Generation
2.3.3.5 References
1. https://www.geeksforgeeks.org/computer-organization-and-architecture-tutorials/
2. https://tutorialspoint.dev/computer-science/computer-organization-and-architecture
20
2.3.4 Learning Outcome 3: Understand Computer Memory Organization
2.3.4.1 Learning Activities
Introduction
This learning outcome covers explaining memory organisation, various storage technologies,
cache and virtual memory, prescribing memory specifications for a user and verifying memory
specifications for a given computer.
• Cached memory
21
○ a small-sized type of volatile computer memory that provides high-speed
data access to a processor and stores frequently used computer programs,
applications and data
• Volatile Memory: This loses its data, when power is switched off.
• Non-Volatile Memory: This is a permanent storage and does not lose any data when
power is switched off.
The total memory capacity of a computer can be visualized by hierarchy of components. The
memory hierarchy system consists of all storage devices contained in a computer system from the
slow Auxiliary Memory to fast Main Memory and to smaller Cache memory.
Cache Memory
Cache memory is a very high speed semiconductor memory which can speed up the CPU.
It acts as a buffer between the CPU and the main memory. It is used to hold those parts of data and
program which are most frequently used by the CPU. The parts of data and programs are
transferred from the disk to cache memory by the operating system, from where the CPU can
access them.
22
Figure 13:Cache Memory
Cache deals with the tags so as to identify which block of main memory is present in each
cache slot
Advantages
The advantages of cache memory are as follows −
● Cache memory is faster than main memory.
● It consumes less access time as compared to main memory.
● It stores the program that can be executed within a short period of time.
● It stores data for temporary use.
Disadvantages
The disadvantages of cache memory are as follows −
● Cache memory has limited capacity.
● It is very expensive.
23
RAM (Random Access Memory)
Random access memory (RAM) is the best known form of computer memory. RAM is
considered "random access" because you can access any memory cell directly if you know
the row and column that intersect at that cell.
Types of RAM:-
● Static RAM (SRAM)
● Dynamic RAM (DRAM)
NVRAM:
❏ It is a category of Random Access Memory (RAM) that retains stored data even if
the power is switched off.
❏ NVRAM uses a tiny 24-pin dual inline package (DIP) integrated circuit chip, which
helps it to gain the power required to function from the CMOS battery on the
motherboard.
❏ NVRAM monitors several system parameters, such as Ethernet the MAC address,
serial number, date of manufacture, HOSTID, etc.
❏ NVRAM is a non-volatile memory type that provides the random access facility.
24
ROM: Read Only Memory
It is the memory from which we can only read but cannot write on it. This type of memory is non-
volatile.
ROM chips are not only used in the computer but also in other electronic items like washing
machine and microwave oven.
Secondary Memory
This type of memory is also known as external memory or non-volatile.
It is slower than the main memory. These are used for storing data/information permanently. The
CPU does not directly access these memories; instead they are accessed via input-output routines.
The contents of secondary memories are first transferred to the main memory, and then the CPU
can access it. For example, disk, CD-ROM, DVD, etc.
25
Figure 14:Secondary Memory
Nature The primary memory is categorized The secondary memory is always a non-
as volatile & nonvolatile memories. volatile memory.
Alias These memories are also called Secondary memory is known as a Backup
internal memory. memory or Additional memory or Auxiliary
memory.
Access Data is directly accessed by the Data cannot be accessed directly by the
processing unit. processor. It is first copied from secondary
memory to primary memory. Only then
CPU can access it.
26
Formation It's a volatile memory meaning data It's a non-volatile memory so that that data
cannot be retained in case of power can be retained even after power failure.
failure.
Storage It holds data or information that is It stores a substantial amount of data and
currently being used by the information. Capacity is generally from
processing unit. Capacity is usually 200GB to terabytes.
in 16 to 32 GB
Expense Primary memory is costlier than Secondary memory is cheaper than primary
secondary memory. memory.
Storage Devices
Form-factors and protocols such as SATA and SAS of traditional hard disk drive (HDD) may be
used by SSD, greatly simplifying usage of SSDs in computers.
New form factors such as the M.2 form factor, and new I/O protocols such as NVM Express have
been developed to address specific requirements of the Flash memory technology used in SSDs.
Characteristics
● There are no moving mechanical components in SSD. This makes them different
from conventional electromechanical drives such as hard disk drives (HDDs) or
floppy disks, which contain movable read/write heads and spinning disks.
● SSDs are typically more resistant to physical shock.
● Run silently, have quicker access time and lower latency compared to
electromechanical devices.
27
Optical storage devices
This is an electronic data storage medium that can be written to and read from using a low-
powered laser beam.
Optical storage devices save data as patterns of dots that can be read using light. A laser beam is
the usual light source.
The data on the storage medium is read by bouncing the laser beam off the surface of the
medium.
Dots can be created using the laser beam (for media that is writable such as CD-Rs). The beam is
used in a high-power mode to actually mark the surface of the medium, making a dot. This
process is known as ‘burning’ data onto a disc.
28
Magnetic Storage Device
A magnetic disk is a storage device that uses a magnetization process to write, rewrite and access
data. It is covered with a magnetic coating and stores data in the form of tracks, spots and sectors.
Hard disks and zip disks are common examples of magnetic disks.
Virtual Memory
Virtual Memory is a technique to increase the main memory capacity. It uses data swap
technology and hard disk area is used as virtual memory.
It is a technique that is implemented using both hardware and software. It maps memory
addresses used by a program, called virtual addresses, into physical addresses in computer
memory.
Following are the important differences between Cache Memory and Virtual Memory.
29
Key RAM specifications to consider
• Physical Size
RAM modules vary in physical size based on the type of computer they're used for and the number
of pins on the module. Dual Inline Memory Modules (DIMMs) with 168 pins are 5.25 inches long.
DIMMs with fewer pins are typically smaller, with more pins meaning a physically larger module.
DIMMs are commonly used in desktop computers, whereas laptops typically use Small Outline
Dual Inline Memory Modules (SODIMMs). SODIMMs use the same technology but they're
physically smaller, allowing them to fit in laptops.
• Amount of memory
The amount is another important specification to remember. Your computer can only hold so much
RAM and while going over the specified limit won't harm your computer, your PC will only use as
much of it as it was designed to use. Amount is commonly measured in gigabytes (GB), though
older or low-end computers may measure maximum RAM in megabytes (MB). Some computers
have two slots to install memory, others have four and some have even more.
• Type of memory
The memory type is important because this is where the majority of RAM's compatibility issues lie.
Multiple variations of Double Data Rate (DDR) memory technology are used in various computers.
DDR2 is faster than DDR memory, while DDR3 memory is faster than both. If your computer
requires DDR3 memory, DDR2 memory won't work.
• Memory Speed
Memory speed is frequently denoted by "PC-" followed by a number that denotes the peak transfer
rate and bandwidth of that type of memory. For example, PC-2400's peak transfer rate is around
2,400 megabytes per second (MB/s). The peak transfer rate basically denotes the best performance
possible for that memory. "PC2" and "PC3" simply refer to DDR2 and DDR3 memory,
respectively.
The specifications may list the memory under a name known as the "friendly name," which looks
something like "DDR3-1066." In this case, 1066 represents the data transfer rate in millions per
second. All together, the memory specification may read something like "2 GB PC3-6400 DDR3
SODIMM."
Note: For hard disk storage, the capacity, usually in Gigabytes is the key factor to consider.
Conclusion
At the end of this learning outcome, the learner should be able to explain memory organisation,
various storage technologies, cache and virtual memory, prescribe memory specifications for a
user and verify memory specifications for a given computer.
Further Reading
30
1. https://www.tutorialspoint.com/computer_logical_organization/index.htm
2. https://www.javatpoint.com/computer-organization-and-architecture-tutorial
2.3.4.3 Self-Assessment
Written Assessment
1. Cache memory is used in a computer system to
a. Ensure fast booting
b. Replace static memory
c. Replace hard disk
d. Speed up memory access
2. Virtual memory of a computer system may be
a. Of unlimited size.
b. As big as maximum addressing capability of the computer system.
c. Of size equivalent to total capacity of secondary storage plus size of RAM.
d. None of the above
3. Which of the following is not an advantage of Dynamic RAMs
a. High density
b. Low cost
c. High speed
d. No need of memory refresh
4. In the memory hierarchy the fastest memory
a. SRAM
b. Cache
c. Registers
d. DRAM
5. Cache memory is implemented using
a. Dynamic RAM
b. Static RAM
c. PROM
d. EPROM
6. Which one of the following is the odd one out?
a. Primary memory
b. Secondary memory
c. Tertiary memory
d. Cached memory
7. What makes SSD different from conventional electromechanical drives
a. they contain movable read/write heads
b. they have spinning disks
c. They do not have moving mechanical components
d. They are hard Disks
31
8. Which of the following Disks are more resistant to physical shock
a. SSDs
b. Floppy Disks
c. HDDs
d. None of the above
9. The following are all types of secondary memory except.
a. Hard drive
b. RAM
c. SSD
d. Flash
10. Which one of the following statements is true?
a. Primary memory is the main memory of the computer system.
b. Rom is part of the secondary memory
c. Secondary memory is not useful at all to the computer
d. Secondary memory is also called internal memory.
Oral Assessment
1. Describe DRAM
2. Differentiate between cache and virtual memory
Practical Assessment
1. Verify the memory and hard disk specifications of the computer provided.
2. Prescribe memory specifications for a user intending to install and use video and
graphics production software.
2.3.4.5 References
1. https://www.geeksforgeeks.org/computer-organization-and-architecture-tutorials/
2. https://tutorialspoint.dev/computer-science/computer-organization-and-architecture
3. https://www.techwalla.com/articles/random-access-memory-specifications
32
2.3.5 Learning Outcome 4: Understand Input-Output functions
2.3.5.1 Learning Activities
Introduction
This learning outcome covers the explaining categorizing the peripheral devices, explain
Input/output (I/O) processing, explain bus interface role in I/O and different modes of data
transfer. It also involves prescribing I/O specifications for a user and verifying I/O specifications
for a given computer.
• Bus: A bus is a subsystem that transfers data between computer components inside a
computer or between computers
Categories
We have different categories. These include;
● Input
● Output
● storage
33
Input Devices
A device that feeds data into a computer processor is called an input device.
Input can take a variety of forms, from commands you enter from the keyboard to data from
another computer or device.
34
Trackballs It is pointing devices and
contains a ball which can be
rotated in any direction. The
user spins the ball in a
different direction to move
the cursor on the screen.
Output Devices
A device that shows data from a computer processor is an output device.
Output can also appear in a variety of forms - text, video, graphics, and so on.
35
Plotters Plotters are generally used
with engineering
applications, for generating
a hard copy of a digitally
created design. In addition,
Plotters are also often used
by graphic artists,
architects, constructions
engineers etc
These devices allow the user to save data in a more permanent way than RAM so that data is not
lost and may be used at a later time.
Peripheral specifications
These specifications should match the user’s needs. If the user needs to save/store data, they will
need storage, a device categorized as storage will be ideal.
The user specification may entail a very long list of devices depending on the special purpose at
hand.
I/O Processing
I/O processor is a processor separate from the CPU designed to handle only input/output
processes for a device or the computer.
The I/O processor is capable of performing actions without interruption or intervention from the
CPU. The CPU only needs to initiate the I/O processor by telling it what activity to perform.
Once the necessary actions are performed, the I/O processor then provides the results to the CPU.
Doing these actions allow the I/O processor to act as a bus to the CPU, carrying out activities by
directly interacting with memory and other devices in the computer. A more advanced I/O
36
processor may also have memory built into it, allowing it to perform actions and activities more
quickly.
BUS: is a communication system that transfers data between components inside a computer, or
between computers
Interface: is a hardware circuitry between the microcomputer and the I/O devices. It provides all
the input/output transfer.
They connect/interface the computer and the peripherals.
Types of buses
Each bus defines its set of connectors to physically plug devices, cards or cables together. There are
two types of buses: internal and external. Internal buses are connections to various internal
components. External buses are connections to various external components. There are different kinds
of slots that internal and external devices can connect to.
Internal
Types of Slots
There are many different kinds of internal buses, but only a handful of popular ones. Different
computers come with different kinds and number of slots. It is important to know what kind and
number of slots you have on your computer before you go out and by a card that matches up to a
slot you don’t have.
PCI
PCI (Peripheral Component Interconnect) is common in modern PCs. This kind of bus is being
succeeded by PCI Express. Typical PCI cards used in PCs include: network cards, sound cards,
37
modems, extra ports such as USB or serial, TV tuner cards and disk controllers. Video cards have
outgrown the capabilities of PCI because of their higher bandwidth requirements.
PCI Express
PCI Express was introduced by Intel in 2004. It was designed to replace the general-purpose PCI
expansion bus and the AGP graphics card interface.
PCI express is not a bus but instead a point-to-point connection of serial links called lanes. PCI
Express cards have faster bandwidth then PCI cards which make them more ideal for high-end
video cards.
PCMCIA
PCMCIA (also referred to as PC Card) is the type of bus used for laptop computers. The name
PCMCIA comes from the group who developed the standard: Personal Computer Memory Card
International Association.
PCMCIA was originally designed for computer memory expansion, but the existence of a usable
general standard for notebook peripherals led to many kinds of devices being made available in this
form. Typical devices include network cards, modems, and hard disks.
AGP
AGP (Accelerated Graphics Port) is a high-speed point-to-point channel for attaching a graphics
card to a computer’s motherboard, primarily to assist in the acceleration of 3D computer graphics.
AGP has been replaced over the past couple years by PCI Express. AGP cards and motherboards
are still available to buy, but they are becoming less common.
38
Figure 17:AGP Slot
Types of Cards
Video Card
A video card (also known as graphics card) is an expansion card whose function is to generate and
output images to a display. Some video cards offer added functions, such as video capture, TV
tuner adapter, ability to connect multiple monitors, and others. Most video cards all share similar
components.
They include a graphics processing unit (GPU) which is a dedicated microprocessor optimized for
3D graphics rendering. It also includes video BIOS that contains the basic program that governs
the video card’s operations and provides the instructions that allow the computer and software to
interface with the card. If the video card is integrated in the motherboard, it may use the computer
RAM memory. If not, it will have its own video memory called Video RAM.
This kind of memory can range from 128MB to 2GB. A video card also has a RAMDAC (Random
Access Memory Digital-to-Analog Converter) which takes responsibility for turning the digital
signals produced by the computer processor into an analog signal which can be understood by the
computer display. Lastly, they all have outputs such as an HD-15 connector (standard monitor
cable), DVI connector, S-Video, composite video or component video.
Sound Card
A sound card is an expansion card that facilitates the input and output of audio signals to/from a
computer under control of computer programs. Typical uses for sound cards include providing the
audio component for multimedia applications such as music composition, editing video or audio,
presentation/education, and entertainment. Many computers have sound capabilities built in, while
others require additional expansion cards to provide for audio capability.
Network Card
A network card is an expansion card that allows computers to communicate over a computer
network. It allows users to connect to each other either by using cables or wirelessly. Although
other network technologies exist, Ethernet has achieved near-ubiquity for a while now. Every
Ethernet network card has a unique 48-bit serial number called a MAC address, which is stored in
ROM carried on the card.
39
Figure 19:Network Card
External
Types of Connections
USB
USB (Universal Serial Bus) is a serial bus standard to interface devices. USB was designed to allow
many peripherals to be connected using a single standardized interface socket and to improve the
plug-and-play capabilities by allowing devices to be connected and disconnected without rebooting
the computer.
Other convenient features include providing power to low-consumption devices without the need
for an external power supply and allowing many devices to be used without requiring manufacturer
specific, individual device drivers to be installed. USB is by far the dominating bus for connecting
external devices to your computer.
Firewire
Firewire (technically known as IEEE 1394 and also known as i.LINK for Sony) is a serial bus
interface standard for high-speed communications and isochronous real-time data transfer,
frequently used in a personal computer. Firewire has replaced Parallel ports in many applications.
It has been adopted as the High Definition Audio-Video Network Alliance (HANA) standard
connection interface for A/V (audio/visual) component communication and control. Almost all
modern digital camcorders have included this connection.
40
Figure 21:Firewire Cable
PS/2
The PS/2 connector is used for connecting some keyboards and mice to a PC compatible computer
system. The keyboard and mouse interfaces are electrically similar with the main difference being
that open collector outputs are required on both ends of the keyboard interface to allow bidirectional
communication. If a PS/2 mouse is connected to a PS/2 keyboard port, the mouse may not be
recognized by the computer depending on configuration.
Programmed I/O
Programmable I/O is one of the I/O techniques other than the interrupt-driven I/O and direct
memory access (DMA). The programmed I/O is the simplest type of I/O technique for the
exchanges of data or any types of communication between the processor and the external
devices. With programmed I/O, data is exchanged between the processor and the I/O module.
The processor executes a program that gives it direct control of the I/O operation, including
sensing device status, sending a read or write command, and transferring the data. When the
processor issues a command to the I/O module, it must wait until the I/O operation is complete.
If the processor is faster than the I/O module, this is wasteful of processor time.
I/O Commands
Figure 23:Programmed I/O Mode Input Data Transfer
To execute an I/O-related instruction, the processor issues an address, specifying the particular
I/O module and external device, and an I/O command. There are four types of I/O commands that
an I/O module may receive when it is addressed by a processor:
● Control: Used to activate a peripheral and tell it what to do. For example, a magnetic-tape
unit may be instructed to rewind or to move forward one record. These commands are
tailored to the particular type of peripheral device.
● Test: Used to test various status conditions associated with an I/O module and its
peripherals. The processor will want to know that the peripheral of interest is powered on
and available for use. It will also want to know if the most recent I/O operation is completed
and if any errors occurred.
● Read: Causes the I/O module to obtain an item of data from the peripheral and place it in an
internal buffer. The processor can then obtain the data item by requesting that the I/O
module place it on the data bus.
● Write: Causes the I/O module to take an item of data (byte or word) from the data bus and
subsequently transmit that data item to the peripheral.
Relative to the total interrupt system, the processors enter an interrupt service routine. The
function of the routine will depend upon the system of interrupt levels and priorities that is
implemented in the processor. The interrupt technique requires more complex hardware and
software, but makes far more efficient use of the computer’s time and capacities.
43
For input, the device interrupts the CPU when new data has arrived and is ready to be retrieved by the
system processor. The actual actions to perform depend on whether the device uses I/O ports or memory
mapping.
For output, the device delivers an interrupt either when it is ready to accept new data or to acknowledge
a successful data transfer. Memory-mapped and DMA-capable devices usually generate interrupts to tell
the system they are done with the buffer.
Here the CPU works on its given tasks continuously. When an input is available, such as when someone
types a key on the keyboard, then the CPU is interrupted from its work to take care of the input data.
The CPU can work continuously on a task without checking the input devices, allowing the devices
themselves to interrupt it as necessary.
Interrupt Processing
44
Figure 25:Interrupt Processing
It is a way to improve processor activity and I/O transfer rate by taking-over the job of
transferring data from the processor, and letting the processor do other tasks.
This technique overcomes the drawbacks of other two I/O techniques which are the time
consuming process when issuing command for data transfer and tie-up the processor in data
45
transfer while the data processing is neglected. It is more efficient to use the DMA method when
large volumes of data has to be transferred.
For DMA to be implemented, the processor has to share its’ system bus with the DMA module.
Therefore, the DMA module must use the bus only when the processor does not need it, or it
must force the processor to suspend operation temporarily. The latter technique is more common
to be used and it is referred to as cycle stealing.
46
Figure 27:Typical DMA Block Diagram
After the information is sent, the processor continues with other work. The DMA module then
transfers the entire block of data directly to or from memory without going through the processor.
When the transfer is complete, the DMA module sends an interrupt signal to the processor to
inform that it has finished using the system bus.
Conclusion
At the end of this learning outcome, the learner should be able to explain and categorizing the
peripheral devices, explain Input/output (I/O) processing, explain the bus interface role in I/O and
different modes of data transfer. The learner should also able to prescribe I/O specifications for a
user and verify I/O specifications for a given computer.
6.3.5.3 Self-Assessment
Written Assessment
1. What is a peripheral device?
2. What is the purpose of the Bus Interface Unit?
3. Which specifications are important for a monitor?
4. How is an interrupt processed?
5. What type of devices are computer speakers or headphones?
a. Input
b. Input/output
c. Software
d. Output
Oral Assessment
1. Distinguish between programmed and Interrupt driven I/O.
2. How does DMA process I/O requests?
Practical Assessment
1. Verify the various I/O ports in your PC.
2. Confirm the specifications of the I/O devices attached to your computer.
1. http://openbookproject.net/courses/intro2ict/hardware/peripherals.html
2. https://www.tutorialspoint.com/computer_fundamentals/computer_components.htm
48
2.3.6 Learning Outcome 5: Understand computer arithmetic and logic
2.3.6.1 Learning Activities
Learning Outcome 5: Understand computer arithmetic and logic
Learning Activities Special Instructions
2.3.6.2 Information Sheet No. 2/LO5: Understand computer arithmetic and logic
Introduction
This learning outcome involves explaining number systems, demonstrating Integer and floating
point representations according to IEEE standard, explaining integer and floating point
arithmetic, logic operators and logic operations and demonstrating methods of representing logic
operations.
Say we have three numbers – 734, 971 and 207. The value of 7 in all three numbers is different−
● In 734, value of 7 is 7 hundreds or 700 or 7 × 100 or 7 × 102
● In 971, value of 7 is 7 tens or 70 or 7 × 10 or 7 × 101
● In 207, value 0f 7 is 7 units or 7 or 7 × 1 or 7 × 100
In any binary number, the rightmost digit is called least significant bit (LSB) and leftmost digit is
called most significant bit (MSB).
And the decimal equivalent of this number is the sum of the product of each digit with its
positional value.
110102 = 1×24 + 1×23 + 0×22 + 1×21 + 0×20
= 16 + 8 + 0 + 2 + 0
= 2610
Computer memory is measured in terms of how many bits it can store. Here is a chart for memory
capacity conversion.
● 1 byte (B) = 8 bits
● 1 Kilobytes (KB) = 1024 bytes
● 1 Megabyte (MB) = 1024 KB
● 1 Gigabyte (GB) = 1024 MB
● 1 Terabyte (TB) = 1024 GB
● 1 Exabyte (EB) = 1024 PB
● 1 Zettabyte = 1024 EB
● 1 Yottabyte (YB) = 1024 ZB
50
Octal Number System
Octal number system has eight digits – 0, 1, 2, 3, 4, 5, 6 and 7.
Octal number system is also a positional value system with where each digit has its value
expressed in powers of 8, as shown here –
Decimal equivalent of any octal number is the sum of the product of each digit with its positional
value.
7268 = 7×82 + 2×81 + 6×80
= 448 + 16 + 6
= 47010
Decimal equivalent of any hexadecimal number is the sum of the product of each digit with its
positional value.
27FB16 = 2×163 + 7×162 + 15×161 + 10×160
= 8192 + 1792 + 240 +10
= 1023410
0 0 0 0000
51
1 1 1 0001
2 2 2 0010
3 3 3 0011
A 10 12 1010
B 11 13 1011
C 12 14 1100
ASCII
Besides numerical data, computers must be able to handle alphabets, punctuation marks,
mathematical operators, special symbols, etc. that form the complete character set of English
language. The complete set of characters or symbols are called alphanumeric codes. The complete
alphanumeric code typically includes –
Now a computer understands only numeric values, whatever the number system used. So all
characters must have a numeric equivalent called the alphanumeric code. The most widely used
alphanumeric code is American Standard Code for Information Interchange (ASCII). ASCII is a 7-
bit code that has 128 (27) possible codes.
52
Table 9: ASCII
Unicode
Unicode is an international coding system designed to be used with different language scripts.
Each character or symbol is assigned a unique numeric value, largely within the framework of
ASCII. Earlier, each script had its own encoding system, which could conflict with each other.
In contrast, this is what Unicode officially aims to do − Unicode provides a unique number for
every character, no matter what the platform, no matter what the program, no matter what the
language.
Decimal to Binary
Decimal numbers can be converted to binary by repeated division of the number by 2 while
recording the remainder.
Example:
53
The remainders are to be read from bottom to top to obtain the binary equivalent.
4310 = 1010112
Decimal to Octal
Decimal numbers can be converted to octal by repeated division of the number by 8 while
recording the remainder.
Example:
Decimal to Hexadecimal
Decimal numbers can be converted to octal by repeated division of the number by 16 while
recording the remainder.
Example:
54
● If there are one or two bits less in making the groups, 0s can be added after the most
significant bit
● Convert each group into its equivalent octal number
Example:
101100101012 = 26258
To convert an octal number to binary, each octal digit is converted to its 3-bit binary equivalent
according to this table.
Example:
Octal Digit 0 1 2 3 4 5 6 7
Binary Equivalent 00 00 01 01 10 10 11 11
0 1 0 1 0 1 0 1
546738 = 1011001101110112
Binary to Hexadecimal
To convert a binary number to hexadecimal number, these steps are followed −
● Starting from the least significant bit, make groups of four bits.
● If there is one or two bits less in making the groups, 0s can be added after the most
significant bit.
● Convert each group into its equivalent octal number.
Example:
55
101101101012 = DB516
To convert an octal number to binary, each octal digit is converted to its 3-bit binary equivalent.
Integers
An integer is a whole number (not a fraction) that can be positive, negative, or zero. Therefore,
the numbers 10, 0, -25, and 5,148 are all integers.
Integers are a commonly used data type in computer programming. For example, whenever a
number is being incremented, such as within a "for loop" or "while loop," an integer is used.
Integers are also used to determine an item's location within an array.
When two integers are added, subtracted, or multiplied, the result is also an integer. However,
when one integer is divided into another, the result may be an integer or a fraction. For example,
6 divided by 3 equals 2, which is an integer, but 6 divided by 4 equals 1.5, which contains a
fraction. Decimal numbers may either be rounded or truncated to produce an integer result.
Computers recognize real numbers that contain fractions as floating point numbers. When a
calculation includes a floating point number, it is called a "floating point calculation." Older
computers used to have a separate floating point unit (FPU) that handled these calculations, but
now the FPU is typically built into the computer's CPU.
Addition
Example on decimal value given in scientific notation:
3.25 x 10 ** 3
+ 2.63 x 10 ** -1
-----------------
First step: Align decimal points
56
3.25 x 10 ** 3
+ 0.000263 x 10 ** 3
--------------------
3.250263 x 10 ** 3
(Presumes use of infinite precision, without regard for accuracy)
We want to shift the mantissa right, because the bits that fall off the end should come from the
least significant end of the mantissa
-> Choose to shift the .25, since we want to increase its exponent.
-> Shift by 10000101
-01111101
---------
00001000 (8) places.
Step 2: Add (don't forget the hidden bit for the 100)
0 10000101 1.10010000000000000000000 (100)
+ 0 10000101 0.00000001000000000000000 (.25)
---------------------------------------
0 10000101 1.10010001000000000000000
Step 3: normalize the result (get the "hidden bit" to be a 1)
It already is for this example.
57
The result is
0 10000101 10010001000000000000000
Subtraction
Like addition as far as alignment of radix points then the algorithm for subtraction of sign mag.
numbers takes over.
Multiplication
Example on decimal values given in scientific notation:
3.0 x 10 ** 1
+ 0.5 x 10 ** 2
-----------------
Example in binary: Use a mantissa that is only 4 bits so that you don’t take long doing the
multiplication part.
0 10000100 0100
x 1 00111100 1100
-----------------
Mantissa multiplication: 1.0100
(don't forget hidden bit) x 1.1100
------
00000
00000
10100
10100
10100
---------
1000110000
becomes 10.00110000
Add exponents: Always add true exponents (otherwise the bias gets added in twice)
58
Biased:
10000100
+ 00111100
----------
10000100 01111111 (switch the order of the subtraction,
- 01111111 - 00111100 so that we can get a negative value)
---------- ----------
00000101 01000011
true exp true exp
is 5. is -67
Add true exponents 5 + (-67) is -62.
Re-bias exponent: -62 + 127 is 65.
1 01000001 10.00110000
becomes
1 01000010 1.000110000
Division
• Similar to multiplication.
• True division: do unsigned division on the mantissas (don't forget the hidden bit)
• Subtract TRUE exponents
The IEEE standard is very specific about how all this is done. Unfortunately, the hardware to
do all this is very slow.
59
There is a faster way to do division. It’s called division by reciprocal approximation. It takes
about the same time as a fl. pt. multiply. Unfortunately, the results are not always the same as
with true division.
Rounding
Arithmetic operations on fl. pt. values compute results that cannot be represented in the given
amount of precision. So, we must round results.
There are MANY ways of rounding. They each have "correct" uses, and exist for different
reasons. The goal in a computation is to have the computer round such that the end result is as
"correct" as possible.
Methods of rounding:
Round toward 0 -- also called truncation.
Figure out how many bits (digits) are available. Take that many bits (digits) for the result and
throw away the rest. This has the effect of making the value represented closer to 0.
Example:
.7783 If 3 decimal places available, .778
If 2 decimal places available, .77
Example:
1.23 If 2 decimal places, 1.3
-2.86 if 2 decimal places, -2.8
Example:
1.23 If 2 decimal places, 1.2
60
-2.86 if 2 decimal places, -2.9
1.1101
|
1.11 | 10.00
------
1.001
|
1.00 | 1.01
-----
Round toward zero (TRUNCATE) --
1.1101
|
1.11 | 10.00
------
1.001
|
1.00 | 1.01
-----
-1.1101
|
-10.00 | -1.11
------
-1.001
|
-1.01 | -1.00
-----
Round toward nearest --
ODD CASE:
61
If there is anything other than 1000 to the right of the number of digits to be kept, it is
rounded in IEEE standard such that the least significant bit (to be kept) is a zero.
1.1111
|
1.11 | 10.00
------
1.1101
|
1.11 | 10.00
------
1.001 (ODD CASE)
|
1.00 | 1.01
-----
-1.1101 (1/4 of the way between)
|
-10.00 | -1.11
------
-1.001 (ODD CASE)
|
-1.01 | -1.00
-----
Integer Representation and Arithmetic
Integer Representation
● Bit-- Binary Digit
○ 1 byte = 8 bits
○ 1 word = 2 bytes
● Integer takes up two bytes; can be signed or unsigned.
Unsigned Integers
● Can represent whole numbers from 0 to 65,535
○ (0 to 216 - 1).
● In binary, this is from
○ 02to 11111111111111112
● Internally, binary representation of decimal value is 16 bits.
Signed Integers
● Need to reserve one bit for the sign.
● Three ways:
○ Sign-Magnitude
○ 1's Complement
62
○ 2's Complement
Sign-Magnitude
● Uses the most significant bit of the word to represent the sign.
○ 0 - Positive
○ 1 - Negative.
● Rest of the number is encoded in magnitude part
37 = 00000000 00100101
-37 = 10000000 00100101
6712 = 00011010 00111000
-6712 = 10011010 00111000
● Can represent numbers from -32,767 to 32,767.
○ -215+1 .. 215-1
● But, two representations for zero:
0 = 00000000 00000000
● -0 = 10000000 00000000 Arithmetic can be cumbersome.
1's Complement
● Negative numbers are stored as bitwise complement of corresponding positive numbers.
● Leftmost bit of the positive number is 0. That of the negative number is 1.
196 = 00000000 11000100
-196 = 11111111 00111011
● Can represent numbers from -32,767 to 32,767.
○ -215+1 .. 215-1
● Arithmetic is easier than sign-magnitude.
● But, still have two representations for zero:
0 = 00000000 00000000
-0 = 11111111 11111111
2's Complement
● Modern Method: Positive number represented in same way as other two methods
● Negative number obtained by taking 1's Complement of positive number and adding 1.
6713 = 00011000 00011101
1's Comp = 11100111 11100010
2's Comp = 11100111 11100011
● Word integers can represent numbers from -32,768 to 32,767.
○ -215 .. 215-1
● Byte integers can represent numbers from -128 to 127.
○ -27 .. 27-1
● One version of zero:
00000000 00000000
63
● Copy sign bit of the byte into all the bits of the upper byte of the word.
37 = 00100101 -> 00000000 00100101
● -37 = 11011011 -> 11111111 11011011 cbw
○ converts the signed byte in AL to a word in AX
We have a range of the logic operators which include OR, AND, NOT, NOR, XOR and XNOR.
64
OR
The OR logic operation returns True if either its inputs are True. If all inputs are false, the output
is also false. In computer programming, the OR operation is usually written as || (two vertical
bars). In Boolean algebra, the OR value of two inputs A and B can be written as A+B.
Note Do not mistake the OR operation for arithmetic addition, even though they both use the "+"
symbol. They are distinct operations.
OR logic gate
AND
The AND logic operation returns True only if either of its inputs are True. If either of the inputs
is False the output is also false. In computer programming, the AND operation is usually written
as && (two ampersands). In Boolean algebra, the AND operation of two inputs A and B can be
written as AB.
OR logic gate
NOT
The NOT logic operation returns True if its input is False, and False if its input is True. In
computer programming, the NOT operation is usually written as ! (an exclamation mark). In
Boolean algebra, the NOT value of an input A can be written as A̅ (A with an overscore).
NOR
65
The NOR logic operation “stands for NOT OR” returns true if either of its inputs are false, and
false if either of its inputs are true. In Boolean algebra, the NOR value of two inputs A and B can
be written as (A+B with an overscore). NOR has the distinction of being one of two
"universal" logic gates, because any other logic operation can be created using only NOR gates.
(The other universal logic gate is NAND.)
XOR
The XOR logic operation (which stands for "Exclusive OR" returns true if either of its inputs
differ, and false if they are all the same. In other words, if its inputs are a combination of true and
false, the output of XOR is true. If its inputs are all true or all false, the output of XOR is false. In
Boolean algebra, the XOR value of two inputs A and B can be written as A⊕B (the XOR
symbol, resembles a plus sign inside a circle).
Exclusive OR gate
XNOR
The XNOR logic operation (which stands for "Exclusive NOT OR" returns true if either of its
inputs are the same, and false if either of them differ. In other words, if its inputs are a
combination of true and false, the output of XNOR is false. If its inputs are all true or all false,
the output of XNOR is true. In Boolean algebra, the XNOR value of two inputs A and B can be
written as (the XOR symbol ⊕, resembles a plus sign inside a circle with a line over
everything).
66
Karnaugh map
A Karnaugh map provides a pictorial method of grouping together expressions with common
factors and therefore eliminating unwanted variables. The Karnaugh map can also be described as
a special arrangement of a truth table.
The diagram below illustrates the correspondence between the Karnaugh map and the truth table
for the general case of a two variable problem.
The values inside the squares are copied from the output column of the truth table, therefore there
is one square in the map for every row in the truth table. Around the edge of the Karnaugh map
are the values of the two input variable. A is along the top and B is down the left hand side. The
diagram below explains this:
The values around the edge of the map can be thought of as coordinates. So as an example, the
square on the top right hand corner of the map in the above diagram has coordinates A=1 and
B=0. This square corresponds to the row in the truth table where A=1 and B=0 and F=1. Note
that the value in the F column represents a particular function to which the Karnaugh map
corresponds.
Conclusion
At the end of this learning outcome, the learner should be able to explain number systems,
demonstrate integer and floating point representations according to IEEE standard explain
67
integer and floating point arithmetic, logic operators and logic operations and demonstrate
methods of representing logic operations.
Further Reading
1. https://www.tutorialspoint.com/fixed-point-and-floating-point-number-representations
2. https://www.tutorialspoint.com/computer_logical_organization/boolean_algebra.htm
2.3.6.3 Self-Assessment
Written Assessment
1. Which of the following is not a logical operator?
a. And
b. OR
c. Else
d. NOT
2. Boolean operator which combines search terms so that each search result contains all of
terms, is
a. and operator
b. not operator
c. or operator
d. nor operator
3. The sign magnitude representation of -1 is?
a. 1001
b. 1000
c. 0001
d. 1110
4. The ALU gives the output of the operations and the output is stored in the?
a. Memory devices
b. Registers
c. Flags
d. Output Unit
5. The bitwise complement of 0 is?
a. 00000001
b. 11111111
c. 11111110
d. 10000000
Oral Assessment
1. Describe the logical operators
2. Describe with illustrations how to convert Decimal to binary
68
Practical Assessment
Research on the application areas of logic operations in computer science.
2.3.2.5 References
1. http://mathworld.wolfram.com/KarnaughMap.html
2. https://www.tutorialspoint.com/computer_logical_organization/boolean_algebra.htm
3. https://www.tutorialspoint.com/digital_circuits/digital_circuits_boolean_algebra.htm
69
CHAPTER 3: OPERATING SYSTEMS
3.1 Introduction
This unit covers the competencies required to understand operating systems. It involves
understanding fundamentals of operating systems, understanding process management,
understanding memory management, understanding input-output management and understanding
file management.
70
3.3.2 Learning Outcome No 1: Understand fundamentals of operating systems
3.3.2.1 Learning Activities
Learning Outcome 1: Understand fundamentals of operating systems
Learning Activities Special Instructions
Introduction
This learning outcome covers explaining computer software, explaining operating system, describing
structures of operating systems, explaining types of operating systems, outlining installation
requirements for Windows and demonstrating installation of Windows.
System Software: It is a collection of programs designed to operate, control, and extend the
processing capabilities of the computer itself. It is usually developed by the computer
manufacturers. Some examples of system software are Operating System, Compilers, Interpreter,
Assemblers, etc.
Definition
An operating System is a collection of system programs that together control the operations of a
computer system.
The operating system acts as an intermediary between a user of a computer and the computer
hardware.
71
Some examples of operating systems are UNIX, Microsoft Disk Operating System (MS-DOS),
Microsoft Windows (Simply called Windows), OS/2 and MacOS.
ii) Main-Memory
• Memory is a large array of words or bytes, each with its own address. It is a repository of
quickly accessible data shared by the CPU and I/O devices.
• The operating system is responsible for the following activities in connection with
memory management:
o Keep track of which parts of memory are currently being used and by whom.
o Decide which processes to load when memory space becomes available.
o Allocate and de-allocate memory space as needed.
v) Secondary-Storage Management
Since main memory (primary storage) is volatile and too small to accommodate all data and
programs permanently, the computer system must provide secondary storage to back up main
memory.
Most modern computer systems use disks as the principle on-line storage medium, for both
programs and data.
The operating system is responsible for the following activities in connection with disk
management:
• Free space management
• Storage allocation
• Disk scheduling
Layered architecture
74
In this architecture, the operating system is split into various layers and each of the layers have
different functionalities.
Each of the layers in the operating system can only interact with the layers that are above and below
it. The lowest layer handles the hardware and the uppermost layer deals with the user applications.
Layer Function
Hardware interacts with the system hardware and
coordinates with all the peripheral devices used
such as printer, mouse, keyboard, scanner etc
CPU Scheduling Deals with scheduling the processes for the
CPU. When the processes enter the system,
they are put into the job queue. The processes
that are ready to execute in the main memory
are kept in the ready queue.
Memory Management Moving of processes from disk to primary
memory for execution and back again.
Process Management Assigns the processor to a process at a time .
This is known as process scheduling.
I/O Buffer Handles the buffers for the I/O devices and
makes sure that they work correctly.
User Programs Deals with the many user programs and
applications that run in an operating system
such as word processors, games, browsers etc.
75
Virtual Architecture
The concept of a virtual machine is to provide an interface that looks like independent hardware,
to multiple different operating systems running simultaneously on the same physical hardware.
Each operating system believes that it has access to and control over its own CPU, RAM, I/O
devices, hard drives, etc.
One use for this system is for the development and testing of software that must run on multiple
platforms and/or operating systems. A key difficulty involves the sharing of hard drives, which
are generally partitioned into separate smaller virtual disks for each operating system.
77
In a distributed system, the different machines are connected in a network and each machine has
its own processor and own local memory.
In this systems, operating systems on all the machines work together to manage the collective
network resource.
A disk image is a copy of the entire contents of a storage device, such as a hard drive, DVD, or
CD. The disk image represents the content exactly as it is on the original storage device,
including both data and structure information.
Firmware is a specific class of computer software that provides the low-level control for the
device's specific hardware. Firmware can either provide a standardized operating environment for
the device's more complex software (allowing more hardware-independence), or, for less
complex devices, act as the device's complete operating system, performing all control,
monitoring and data manipulation functions.
78
Typical examples of devices containing firmware are embedded systems, consumer appliances,
computers, computer peripherals, and others. Almost all electronic devices beyond the simplest
contain some firmware.
Disk partitioning or disk slicing is the creation of one or more regions on secondary storage, so
that each region can be managed separately. These regions are called partitions.
Types of installations
Attended installation
On Windows systems, this is the most common form of installation. An installation process
usually needs a user who attends it to make choices, such as accepting or declining an end-user
license agreement (EULA), specifying preferences such as the installation location, supplying
passwords or assisting in product activation. In graphical environments, installers that offer a
wizard-based interface are common.
Attended installers may ask users to help mitigate the errors. For instance, if the disk in which the
computer program is being installed was full, the installer may ask the user to specify another
target path or clear enough space in the disk.
Silent installation
Installation that does not display messages or windows during its progress. "Silent installation" is
not the same as "unattended installation" (see below): All silent installations are unattended but
not all unattended installations are silent. The reason behind a silent installation may be
convenience or subterfuge. Malware is almost always installed silently
Unattended installation
Installation that is performed without user interaction during its progress or with no user present
at all. One of the reasons to use this approach is to automate the installation of a large number of
systems. An unattended installation either does not require the user to supply anything or has
received all necessary input prior to the start of installation. Such input may be in the form of
command line switches or an answer file, a file that contains all the necessary parameters.
Headless installation
79
Installation performed without using a computer monitor connected. In attended forms of
headless installation, another machine connects to the target machine (for instance, via a local
area network) and takes over the display output. Since a headless installation does not need a user
at the location of the target computer, unattended headless installers may be used to install a
program on multiple machines at the same time.
An operating system may automatically install a device driver for a device that the user connects.
(Plug and play.) Malware may also be installed automatically. For example, the infamous
Conficker was installed when the user plugged an infected device to their computer.
Network installation
Network installation, shortened netinstall, is an installation of a program from a shared network
resource that may be done by installing a minimal system before proceeding to download further
packages over the network. This may simply be a copy of the original media but software
publishers which offer site licenses for institutional customers may provide a version intended for
installation over a network.
i) Clean Installation
We can perform a clean installation on a new computer or in those cases where there is no
upgrade path between the current operating system and the new one. A new PC requires, of
course a clean installation. You can also do a clean install when the current operating system
installation has corrupted files or does not work properly.
Advantages of upgrading
• You do not have reformat your hard drive. The new operating system will simply replace
your previous installation, and you will be able to keep all of your files and programs.
• This process takes the least amount of time, as technically you are not required to do a
backup (though it's highly recommended you do).
• You are not prompted to enter a product key, at least for those users upgrading from
Windows 7 or Windows 8.1.
Disadvantages of upgrading
• Occasionally, upgrades have problems including errors caused by pre-existing issues in your
system.
• After the upgrade, there are chances that applications and peripherals may not work
correctly, and it could result on additional time trying to troubleshoot and fix the problems.
Note: If you are planning to upgrade, make sure to uninstall any security software, such as
antivirus, and software you do not need. Take the time and check online to verify your hardware
and software are compatible with Windows 10. Also, make sure to disconnect any peripherals, such
as printers, scanners, and USB devices to avoid possible errors.
iv) Virtualization
This is relative new technique that is often used on servers. With virtualization we can run
numerous copies of an operating system on a single set of hardware and create this way several
virtual machines. Every single virtual machine works like a separate computer. This technology
makes a single physical hardware resource to appear like multiple logical resources.
81
Pre-Installation actions
1. Make sure that all the hardware is certified to work with the new operating system.
2. Confirm that the hardware resources meet the minimum installation requirements.
3. Perform a virus scan before starting the installation and a complete full backup of all
your personal data.
One method that helps you protect your data is this: Create multiple partitions on the hard disk
and install a different OS on each partition. Then copy all your data inside an empty partition that
does not contain an OS. This way you can upgrade the operating system without the risk of losing
any data. Backup and recovery of data files is also easier with this design.
Each version of Microsoft Windows is installed on a computer using similar steps. While there
are steps in the installation process that can differ between versions of Windows, the following
general steps and guidelines will help you to install Windows on your computer.
82
If you are replacing the hard drive in your computer, you will need to reinstall Windows again.
If you are replacing the motherboard in your computer, you may need to purchase a new licensed
copy of Windows and install it. Microsoft has designed current versions of Windows to be tied to
the motherboard in the computer when Windows is installed. So if you change the motherboard,
the existing license, or product key, may no longer be valid.
Note: If you want to upgrade to a newer version of Windows on your computer, the steps on
outlinedher can help you with the upgrade process. The Windows installation process should
recognize if you have an older version of Windows already installed on the computer and ask if
you want to upgrade or perform a fresh install. The upgrade process will install the newer
Windows operating system files over top the old ones and preserve your files.
The steps below are for all recent versions of Windows including Windows 8, and Windows 10.
First, you will need a genuine copy of the Microsoft Windows operating system installation
CD, DVD, or USB thumb drive. A genuine Windows product key is included with the
installation disc, which is required to activate Windows after installation. If you have an OEM
computer, the product key for your version of Windows is also often on the back or side of the
computer.
If you have an OEM computer (e.g., Acer, Dell, HP, etc.), the computer will not have a genuine
Windows CD, DVD, or USB thumb drive. Instead, you would reinstall Windows and all the
software using a hidden partition or a set of restore discs. The steps mentioned here would still
work, but you'd need a copy of Windows.
Note: With early versions of Windows, you cannot download a copy of Windows to install on a
computer. You must purchase a physical copy of Windows. If you are installing Windows 10,
you can download the Windows 10 creation tool to create a bootable disc or USB thumb drive.
Warning: Microsoft has Windows 10 available for download only from their website. Any other
site that claims to have copies of other versions of Windows should not be trusted. These copies
of Windows are pirated software and could contain anything including spyware or malware.
Steps:
To start the Windows install or upgrade process, you will need to configure your computer to
boot from a CD or DVD before booting to the hard drive. Changing the boot process forces the
computer to look for the Windows installation disc before trying to boot from the hard drive.
83
1. Access the computer's BIOS setup.
2. Change the computer's boot order. Set the CD, DVD or disc drive as the first boot device if
you are trying to boot from a disc. Or, set the first boot device to your USB drive if you're trying
to boot from a USB thumb drive. If the drive is not shown, keep the disc is inserted and reboot
the computer. With the disc in the drive, BIOS should recognize and include it in the list.
4. Place the Windows disc in the CD/DVD drive or USB thumb drive into the back of the
computer.
5. Turn on or restart the computer. As the computer is starting up, it should see the installation
disc or drive and show a message similar to Press any key to boot from CD. Press any key on the
keyboard to have the computer boot from the Windows disc or drive.
6. After the Windows install begins, there are several prompts that you need to answer. Select
either Yes or the appropriate option to install Windows.
Install Note: Make sure you select the Full Install option and not the Repair or Upgrade option.
Upgrade Note: If you are upgrading to a newer version of Windows, select the Upgrade option
instead of the Full Install option.
7. When asked which partition to install Windows onto, select the main partition, which is
usually the C: drive or one labeled "Unallocated partition". If upgrading Windows, select the
existing installation of Windows on the hard drive.
8. You may be asked if you want to erase all contents on the hard drive, then install Windows.
It is recommended that you choose this option, as it will also properly format the hard drive to
allow the Windows operating system to be installed.
9. The computer may need to restart several times during the Windows install process. The
restarts are normal and if prompted to restart, select the Yes option.
10. When the install process is nearly complete, the Windows configuration option screens are
shown. On these screens, you may be asked to select the time zone you live in, your preferred
language, and the name of the account you use to access Windows. Select the appropriate options
and enter the appropriate information on each configuration screen.
The Windows install process will be complete when the computer prompts you to log in with the
account you created on the configuration screens, or when it loads directly into Windows.
84
Final Windows and computer configuration
After Windows is installed on the computer, you will need to install the drivers and related
software for the hardware in the computer. You can use the installation discs that came with the
hardware, or you can download the drivers from the hardware manufacturer's website.
Tip: If you cannot download drivers because your network card is not working after installing
Windows, you can download the drivers on another computer. Then, copy them to a USB thumb
drive, and move them over to your computer.
To determine which hardware needs drivers to be installed, check the Device Manager and look
for exclamation mark "!" next to hardware devices. The exclamation point means drivers are
needed for that device.
After installing the necessary hardware device drivers, install any software programs on the
computer that you want to use.
Finally, download and install any available Windows updates. Updating Windows can help
improve the performance of the operating system, the hardware in the computer, and software
programs you use. It can also improve security by fixing potential security holes and flaws in
Windows.
1. Right-click or tap on the date and time in the Windows Notification Area in the bottom right
corner of the screen.
2. Click Adjust date/time.
3. Make sure your Time zone is set properly if your computer is displaying the wrong time.
4. To manually adjust the time, turn off the Set time automatically option and then click the
Change button.
85
• In the remote connection window, type the computer address you want to remotely connect
to and the user name you want to use. For advanced options, like those shown below, click
Show Options at the bottom of the window.
Step 2
First, click Change Settings.
Step 3
Click Change button under Computer Name Tab.
Step 4
Type in the new name for your computer under Computer Name Field.
Once you complete Step 4 just click OK a few times. You will be prompted to reboot the
computer, and once your reboot is complete, your new computer name will be in effect.
If the activation process completes successfully, you'll get the "Windows is activated" message.
Alternatively, you can use change the product key using changepk.exe using the Command
Prompt as well. Here's how:
1. Open the Start menu.
2. Search for Command Prompt.
3. Right-click the result and select Run as administrator.
4. Type the following command using your 25-digit product key and press Enter:
86
changepk.exe /Product Key<enter your 25-digit product key here>
Conclusion
At the end of this learning outcome, the trainee should be able to explain an operating system,
describe structures of operating systems, explain types of operating systems and demonstrate
installation of Windows operating system.
Further reading
1. Deitel, Harvey M.; Deitel, Paul; Choffnes, David. Operating Systems. Pearson/Prentice
Hall. ISBN 978-0-13-092641-8.
2. https://www.wikihow.com/Install-an-Operating-System-on-a-Brand-New-Computer
3. https://www.windowscentral.com/how-change-product-key-windows-10
Written assessment
1. What is system software?
2. How do the functions of system software differ from those of application software?
3. When should one consider performing an upgrade of Windows over a clean installation?
4. Which three advantages can be associated with performing a clean installation?
5. What are the minimum processor, memory and hard drive requirements for installing Windows
10?
6. Why is it necessary to perform a backup of data and applications before installing Windows?
7. In which fields are real time operating systems used?
8. What advantage does the layered operating system structure introduce over the monolithic
structure?
9. What is a virtual machine?
87
10. Which role does the Shell play in an operating system?
Oral Assessment
1. Multiprocessor operating systems are increasingly becoming common for certain types of
tasks. Which kinds of tasks are these?
2. List and explain 5 types of windows desktop operating system installation
3. Briefly explain ,BIOS, Disk image, firmware, PrebooteXecution Environment (PXE)
Practical Assessment
Install and configure Windows 10 desktop operating system on a 500GB hard disk. Partition this
hard drive into two equal partitions.
3.3.2.5 References
88
3.3.3 Learning Outcome 2: Understand Process Management
3.3.3.1 Learning Activities
Learning Outcome 2: Understand Process Management
Learning Activities Special Instructions
Introduction
This learning outcome covers process management. It entails explaining process management,
managing computer resources, explaining process state and transitions, explaining process
scheduling, using the task manager and using the performance monitor tool.
Definition: A process is defined as an entity which represents the basic unit of work to be
implemented in the system.
To put it in simple terms, we write our computer programs in a text file and when we execute this
program, it becomes a process which performs all the tasks mentioned in the program.
When a program is loaded into the memory and it becomes a process, it can be divided into four
sections ─ stack, heap, text and data. The following image shows a simplified layout of a process
inside main memory −
89
Figure 31:Layout of a process inside main memory
1 Stack
The process Stack contains the temporary data such as method/function parameters,
return address and local variables.
2 Heap
This is dynamically allocated memory to a process during its run time.
3 Text
This includes the current activity represented by the value of Program Counter and
the contents of the processor's registers.
4 Data
This section contains the global and static variables.
Program Concept
A program is a piece of code which may be a single line or millions of lines. A computer program
is usually written by a computer programmer in a programming language. For example, here is a
simple program written in C programming language –
#include <stdio.h>
90
int main() {
printf("Hello, World! \n");
return 0;
}
A computer program is a collection of instructions that performs a specific task when executed by
a computer. When we compare a program with a process, we can conclude that a process is a
dynamic instance of a computer program.
Process Management
The process manager is the OS module that allocates resources to processes, enables processes to
share and exchange information, protect the resources of each process from other processes and
enable synchronization among processes.
Process States and Transition
When a process executes, it passes through different states. These stages may differ in different
operating systems, and the names of these states are also not standardized.
In general, a process can have one of the following five states at a time.
State & Description
1 Start
This is the initial state when a process is first started/created.
2 Ready
The process is waiting to be assigned to a processor. Ready processes are waiting
to have the processor allocated to them by the operating system so that they can
run. Process may come into this state after Start state or while running it by but
interrupted by the scheduler to assign CPU to some other process.
3 Running
Once the process has been assigned to a processor by the OS scheduler, the process
state is set to running and the processor executes its instructions.
4 Waiting
Process moves into the waiting state if it needs to wait for a resource, such as
waiting for user input, or waiting for a file to become available.
5 Terminated or Exit
Once the process finishes its execution, or it is terminated by the operating system,
it is moved to the terminated state where it waits to be removed from main
memory.
91
Figure 32:Process States and Transition
1 Process State
The current state of the process i.e., whether it is ready, running, waiting, or
whatever.
2 Process privileges
This is required to allow/disallow access to system resources.
3 Process ID
Unique identification for each of the process in the operating system.
4 Pointer
A pointer to parent process.
5 Program Counter
Program Counter is a pointer to the address of the next instruction to be executed
for this process.
6 CPU registers
Various CPU registers where process need to be stored for execution for running
state.
92
8 Memory management information
This includes the information of page table, memory limits, and Segment table
depending on memory used by the operating system.
9 Accounting information
This includes the amount of CPU used for process execution, time limits,
execution ID etc.
10 IO status information
This includes a list of I/O devices allocated to the process.
The architecture of a PCB is completely dependent on Operating System and may contain different
information in different operating systems. Here is a simplified diagram of a PCB −
The PCB is maintained for a process throughout its lifetime, and is deleted once the process
terminates.
Types of Processes
Processes can be described as either:
• I/O-bound process – spends more time doing I/O than computations, many short CPU
bursts.
93
• CPU-bound process – spends more time doing computations; few very long CPU bursts.
Process Scheduling
The process scheduling is the activity of the process manager that handles the removal of the
running process from the CPU and the selection of another process on the basis of a particular
strategy.
The Operating System maintains the following important process scheduling queues −
• Job queue − this queue keeps all the processes in the system.
• Ready queue − this queue keeps a set of all processes residing in main memory, ready and
waiting to execute. A new process is always put in this queue.
• Device queues − the processes which are blocked due to unavailability of an I/O device
constitute this queue.
The OS can use different policies to manage each queue (FIFO, Round Robin, Priority, etc.). The
OS scheduler determines how to move processes between the ready and run queues which can
only have one entry per processor core on the system; in the above diagram, it has been merged
with the CPU.
94
Two-State Process Model
Two-state process model refers to running and non-running states which are described below −
. State & Description
1 Running
When a new process is created, it enters into the system as in the running state.
2 Not Running
Processes that are not running are kept in queue, waiting for their turn to execute.
Each entry in the queue is a pointer to a particular process. Queue is implemented
by using linked list.
Schedulers
Schedulers are special system software which handle process scheduling in various ways. Their
main task is to select the jobs to be submitted into the system and to decide which process to run.
Schedulers are of three types −
• Long-Term Scheduler
• Short-Term Scheduler
• Medium-Term Scheduler
The primary objective of the job scheduler is to provide a balanced mix of jobs, such as I/O bound
and processor bound. It also controls the degree of multiprogramming. If the degree of
multiprogramming is stable, then the average rate of process creation must be equal to the average
departure rate of processes leaving the system.
On some systems, the long-term scheduler may not be available or minimal. Time-sharing
operating systems have no long term scheduler. When a process changes the state from new to
ready, then there is use of long-term scheduler.
95
process. CPU scheduler selects a process among the processes that are ready to execute and
allocates CPU to one of them.
Short-term schedulers, also known as dispatchers, make the decision of which process to execute
next. Short-term schedulers are faster than long-term schedulers.
A running process may become suspended if it makes an I/O request. A suspended processes
cannot make any progress towards completion. In this condition, to remove the process from
memory and make space for other processes, the suspended process is moved to the secondary
storage. This process is called swapping, and the process is said to be swapped out or rolled out.
Swapping may be necessary to improve the process mix.
96
Using this technique, a context switcher enables multiple processes to share a single CPU. Context
switching is an essential part of a multitasking operating system features.
When the scheduler switches the CPU from executing one process to execute another, the state
from the current running process is stored into the process control block. After this, the state for
the process to run next is loaded from its own PCB and used to set the PC, registers, etc. At that
point, the second process can start executing.
Context switches are computationally intensive since register and memory state must be saved and
restored. To avoid the amount of context switching time, some hardware systems employ two or
more sets of processor registers.
When the process is switched, the following information is stored for later use.
• Program Counter
• Scheduling information
• Base and limit register value
• Currently used register
• Changed State
• I/O State information
• Accounting information
97
Operating System scheduling algorithms
A Process Scheduler schedules different processes to be assigned to the CPU based on particular
scheduling algorithms.
98
P0 0-0=0
P1 5-1=4
P2 8-2=6
P3 16 - 3 = 13
Average Wait Time: (0+4+6+13) / 4 = 5.75
P0 0 5 0
P1 1 3 5
P2 2 8 14
P3 3 6 8
P0 0-0=0
P1 5-1=4
P2 14 - 2 = 12
P3 8-3=5
Average Wait Time: (0 + 4 + 12 + 5)/4 = 21 / 4 = 5.25
99
• Priority scheduling is a non-preemptive algorithm and one of the most common scheduling
algorithms in batch systems.
• Each process is assigned a priority. Process with highest priority is to be executed first and
so on.
• Processes with same priority are executed on first come first served basis.
• Priority can be decided based on memory requirements, time requirements or any other
resource requirement.
Given: Table of processes, and their Arrival time, Execution time, and priority. Here we are
considering 1 is the lowest priority.
Process Arrival Time Execution Time Priority Service Time
P0 0 5 1 0
P1 1 3 2 11
P2 2 8 1 14
P3 3 6 3 5
P0 0-0=0
P1 11 - 1 = 10
P2 14 - 2 = 12
P3 5-3=2
Average Wait Time: (0 + 10 + 12 + 2)/4 = 24 / 4 = 6
100
• Once a process is executed for a given time period, it is preempted and other process
executes for a given time period.
• Context switching is used to save states of preempted processes.
P0 (0 - 0) + (12 - 3) = 9
P1 (3 - 1) = 2
P3 (9 - 3) + (17 - 12) = 11
Average Wait Time: (9+2+12+11) / 4 = 8.5
The first time you launch the Task Manager, you’ll see a small, simple window.
101
Figure 36: Task Manager (Start window)
This window lists the visible applications running on your desktop, excluding background
applications. You can select an application here and click “End Task” to close it. This is useful if an
application isn’t responding—in other words, if it’s frozen—and you can’t close it the usual way.
You can also right-click an application in this window to access more options:
• Switch To: Switch to the application’s window, bringing it to the front of your desktop and
putting it in focus. This is useful if you’re not sure which window is associated with which
application.
• End Task: End the process. This works the same as the “End Task” button.
• Run New Task: Open the Create New Task window, where you can specify a program, folder,
document, or website address and Windows will open it.
• Always On Top: Make the Task Manager window itself “always on top” of other windows on
your desktop, letting you see it at all times.
• Open File Location: Open a File Explorer window showing the location of the program’s
.exe file.
• Search Online: Perform a Bing search for the program’s application name and file name. This
will help you see exactly what the program is and what it does.
• Properties: Open the Properties window for the program’s .exe file. Here you can tweak
compatibility options and see the program’s version number, for example.
102
Figure 37:Task Manager Details window
To see the Task Manager’s more advanced tools, click “More Details” at the bottom of the simple
view window.
You’ll see the full, tabbed interface appear. The Task Manager will remember your preference and
will open to the more advanced view in the future. If you want to get back to the simple view, click
“Fewer Details.”
With More Details selected, the Task Manager includes the following tabs:
• Processes: A list of running applications and background processes on your system along with
CPU, memory, disk, network, GPU, and other resource usage information.
• Performance: Real-time graphs showing total CPU, memory, disk, network, and GPU resource
usage for your system. You’ll find many other details here, too, from your computer’s IP
address to the model names of your computer’s CPU and GPU.
• App History: Information about how much CPU and network resources apps have used for your
current user account. This only applies to new Universal Windows Platform (UWP) apps—in
other words, Store apps—and not traditional Windows desktop apps (Win32 applications.)
• Startup: A list of your startup programs, which are the applications Windows automatically
starts when you sign into your user account. You can disable startup programs from here,
although you can also do that from Settings > Apps > Startup.
• Users: The user accounts currently signed into your PC, how much resources they’re using, and
what applications they’re running.
103
• Details: More detailed information about the processes running on your system. This is basically
the traditional “Processes” tab from the Task Manager on Windows 7.
• Services: Management of system services. This is the same information you’ll find in
services.msc, the Services management console.
Managing Processes
The Processes tab shows you a comprehensive list of processes running on your system. If you sort
it by name, the list is broken into three categories. The Apps group shows the same list of running
applications you’d see in the “Fewer details” simplified view. The other two categories are
background processes and Windows processes, and they show processes that don’t appear in the
standard simplified Task Manager view.
For example, tools like your antivirus program, background update processes, and hardware utilities
with notification area (system tray) icons appear in the background processes list.
Windows processes include various processes that are part of the Windows operating system,
although some of these appear under “Background processes” instead.
You can right-click a process to see actions you can perform. The options you’ll see in the context
menu are:
• Expand: Some applications, like Google Chrome, have multiple processes are grouped
here. Other applications have multiple windows that are part of a single process. You can select
expand, double-click the process, or click the arrow to its left to see the entire group of processes
individually. This option only appears when you right-click a group.
• Collapse: Collapse an expanded group.
• End task: End the process. You can also click the “End Task” button below the list.
• Restart: This option only appears when you right-click Windows Explorer. It lets you
restart explorer.exe instead of simply ending the task.
104
• Resource values: Lets you choose whether you want to see the percentage or precise values for
memory, disk, and network. In other words, you can choose whether you want to see the precise
amount of memory in MB or the percentage of your system’s memory applications are using.
• Create dump file: This is a debugging tool for programmers. It captures a snapshot of the
program’s memory and saves it to disk.
• Go to details: Go to the process on the Details tab so you can see more detailed technical
information.
• Open file location: Open File Explorer with the process’s .exe file selected.
• Search online: Search for the name of the process on Bing.
• Properties: View the Properties window of the .exe file associated with the process.
You should not end tasks unless you know what the task does. Many of these tasks are background
processes important to Windows itself.
There are also a few useful options in the Task Manager’s menu bar:
• File > Run New Task: Launch a program, folder, document, or network resource by providing
its address. You can also check “Create this task with administrative privileges” to launch the
program as Administrator.
• Options > Always on Top: The Task Manager window will always be on top of other windows
while this option is enabled.
• Options > Minimize on Use: The Task Manager will be minimized whenever you right-click a
process and select “Switch To.” Despite the odd name, that’s all this option does.
• Options > Hide When Minimized: The Task Manager will stay running in the notification area
(system tray) when you click the minimize button if you enable this option.
• View > Refresh Now: Immediately refresh the data displayed in the Task Manager.
105
• View > Update Speed: Choose how frequently the data displayed in the Task Manager is
updated: High, Medium, Low, or Paused. With Paused selected, the data isn’t updated until you
select a higher frequency or click “Refresh Now.”
• View > Group By Type: With this option enabled, processes on the Processes tab are grouped
into three categories: Apps, Background Processes, and Windows Processes. With this option
disabled, they’re shown mixed in the list.
• View > Expand All: Expand all the process groups in the list. For example, Google Chrome
uses multiple processes, and they’re shown combined into a “Google Chrome” group. You can
expand individual process groups by clicking the arrow to the left of their name, too.
• View > Collapse All: Collapse all the process groups in the list. For example, all Google
Chrome processes will just be shown under the Google Chrome category.
It could be as a result of problems with the hardware, apps or drivers poorly designed, the operating
system using excessive system resources, or even be a malware that infected your device.
In Windows 10, Performance Monitor is one of the most popular tools used to view and analyze
application and hardware data and to solve system performance related problems. You can also
customize what data to collect in log files, define alerts, generate reports, and replay collected
performance data in many ways.
106
Figure 38:Performance Monitor
On the left, you'll find the navigation pane with access to Performance Monitor, Data Collector
Sets, and Reports.
Switching to Performance Monitor, you'll see a screen with a single counter. This is typically the
"Processor Time" counter, which displays the processor load in the last 100 seconds. However, the
advantage of this tool is that you can add many other counters to monitor virtually anything on your
computer.
107
To add new counters to monitor applications and hardware performance on your computer, do the
following:
1. Click the green plus button above the Performance Monitor graph.
2. Select Local computer or the name of your computer from the drop-down menu.
3. Select and expand the category of the item you want to monitor. For example, for the purpose of
this guide, select the "Network Adapter" category.
4. Select the counters you want to monitor (e.g., Bytes Total/sec).
Quick Tip: If you're trying to add multiple counters, press and hold the Ctrl key and click to select
each item you want to add. Also, you can check the Show description option to get more
information about the counter you're selecting.
5. If applicable, select the instances you want to monitor. For example, on Network Adapter, you can
monitor one or multiple network adapters simultaneously.
6. Click the Add button.
108
Customizing Performance Monitor view
Once you have configured all the counters you want to monitor, you can also customize various
aspects of the data shown in the graph.
Quick Tip: If you're trying to change the properties for multiple counters, press and hold
the Ctrl key, select each item you want to customize, and change the available settings.
5. Click Apply.
6. Click OK.
In addition, you can also change the graph's style, simply click the "Change graph type" in the
toolbar and select one of the available views, including Line, Histogram bar, and Report.
Conclusion
At the end of this learning outcome, the learner should be able to explain process management,
manage computer resources, illustrate process state and transitions, explain process scheduling,
use the task manager and use the performance monitor tool.
Further Reading
109
• Gary D. Knott (1974) A proposal for certain process management and
intercommunication primitives ACM SIGOPS Operating Systems Review. Volume 8, Issue 4
(October 1974). pp. 7 – 44
Written Assessment
1. What is a process?
2. How does a program differ from a process?
3. What is the role of the process manager?
4. Which are the three schedulers used for transitioning jobs from disk to memory to the CPU?
5. What range of information is contained in the Process Control Block?
6. Which resources are involved in a multiprogramming environment?
7. Why is context switching considered undesirable in process scheduling?
8. Identify two tasks you can perform with the Task Manager in Windows.
9. What it the role of the Performance Monitor in Windows?
10. Under what circumstances is a new process created?
Oral Assessment
A blocked process is usually waiting for I/O. What are some of the I/O devices involved in the
blocked state?
.
Practical Assessment
Open the task manager and identify processes that are high CPU users and the idle processes.
3.3.2.5 References
1. Silberschatz, Abraham; Cagne, Greg; Galvin, Peter Baer (2004). "Chapter 4. Processes".
Operating system concepts with Java (Sixth Ed.). John Wiley & Sons. ISBN 0-471-48905-0.
2. Stallings, William (2005). Operating Systems: internals and design principles (5th Ed.).
Prentice Hall. ISBN 0-13-127837-1. (Particularly chapter 3, section 3.2, "process states",
including figure 3.9 "process state transition with suspend states")
4. https://www.tutorialspoint.com/operating_system
110
3.3.4 Learning Outcome 3: Understand Memory Management
3.3.4.1 Learning Activities
Learning Outcome 3: Understand Memory Management
Learning Activities Special Instructions
Introduction
This learning outcome covers memory management. It entails explaining management, explaining
memory management techniques and demonstrating virtual memory settings.
Memory management keeps track of each and every memory location, regardless of either it is
allocated to some process or it is free. It checks how much memory is to be allocated to processes.
It decides which process will get memory at what time. It tracks whenever some memory gets freed
or unallocated and correspondingly it updates the status.
The operating system takes care of mapping the logical addresses to physical addresses at the time
of memory allocation to the program. There are three types of addresses used in a program before
and after memory is allocated
Memory Addresses & Description
1 Symbolic addresses
111
The addresses used in a source code. The variable names, constants, and instruction
labels are the basic elements of the symbolic address space.
2 Relative addresses
At the time of compilation, a compiler converts symbolic addresses into relative
addresses.
3 Physical addresses
The loader generates these addresses at the time when a program is loaded into main
memory.
Virtual and physical addresses are the same in compile-time and load-time address-binding
schemes. Virtual and physical addresses differ in execution-time address-binding scheme.
The set of all logical addresses generated by a program is referred to as a logical address space.
The set of all physical addresses corresponding to these logical addresses is referred to as
a physical address space.
The runtime mapping from virtual to physical address is done by the memory management unit
(MMU) which is a hardware device.
Swapping
Swapping is a mechanism in which a process can be swapped temporarily out of main memory (or
move) to secondary storage (disk) and make that memory available to other processes. At some
later time, the system swaps back the process from the secondary storage to main memory.
Though performance is usually affected by swapping process but it helps in running multiple and
big processes in parallel and that's the reason swapping is also known as a technique for memory
compaction.
112
The total time taken by swapping process includes the time it takes to move the entire process to a
secondary disk and then to copy the process back to memory, as well as the time the process takes
to regain main memory.
Let us assume that the user process is of size 2048KB and on a standard hard disk where swapping
will take place has a data transfer rate around 1 MB per second. The actual transfer of the 1000K
process to or from memory will take
Now considering in and out time, it will take complete 4000 milliseconds plus other overhead
where the process competes to regain main memory.
Memory Allocation
Main memory usually has two partitions −
• Low Memory − Operating system resides in this memory.
• High Memory − User processes are held in high memory.
Fragmentation
As processes are loaded and removed from memory, the free memory space is broken into little
pieces. It happens after sometimes that processes cannot be allocated to memory blocks
considering their small size and memory blocks remains unused. This problem is known as
Fragmentation.
1 External fragmentation
Total memory space is enough to satisfy a request or to reside a process in it, but it
is not contiguous, so it cannot be used.
2 Internal fragmentation
Memory block assigned to process is bigger. Some portion of memory is left
unused, as it cannot be used by another process.
The following diagram shows how fragmentation can cause waste of memory and a compaction
technique can be used to create more free memory out of fragmented memory −
113
Figure 40: Memory fragmentation
External fragmentation can be reduced by compaction or shuffle memory contents to place all free
memory together in one large block. To make compaction feasible, relocation should be dynamic.
The internal fragmentation can be reduced by effectively assigning the smallest partition but large
enough for the process.
Paging is a memory management technique in which process address space is broken into blocks
of the same size called pages (size is power of 2, between 512 bytes and 8192 bytes). The size of
the process is measured in the number of pages.
Similarly, main memory is divided into small fixed-sized blocks of (physical) memory
called frames and the size of a frame is kept the same as that of a page to have optimum utilization
of the main memory and to avoid external fragmentation.
External fragmentation can be reduced by compaction or shuffle memory contents to place all free
memory together in one large block. To make compaction feasible, relocation should be dynamic.
114
The internal fragmentation can be reduced by effectively assigning the smallest partition but large
enough for the process.
Address Translation
• Page address is called logical address and represented by page number and the offset.
• Logical Address = Page number + page offset
• Frame address is called physical address and represented by a frame number and
the offset.
• Physical Address = Frame number + page offset
• A data structure called page map table is used to keep track of the relation between a page
of a process to a frame in physical memory.
When a process is to be executed, its corresponding pages are loaded into any available memory
frames. Suppose you have a program of 8Kb but your memory can accommodate only 5Kb at a
given point in time, then the paging concept will come into picture.
When a computer runs out of RAM, the operating system (OS) will move idle or unwanted pages
of memory to secondary memory to free up RAM for other processes and brings them back when
needed by the program.
This process continues during the whole execution of the program where the OS keeps removing
idle pages from the main memory and write them onto the secondary memory and bring them back
when required by the program.
Advantages of Paging
Here is a list of advantages and disadvantages of paging −
• Paging reduces external fragmentation, but still suffer from internal fragmentation.
• Paging is simple to implement and assumed as an efficient memory management technique.
• Due to equal size of the pages and frames, swapping becomes very easy.
Disadvantage of paging
• Page table requires extra memory space, so may not be good for a system having small
RAM.
Segmentation
Segmentation is a memory management technique in which each job is divided into several
segments of different sizes, one for each module that contains pieces that perform related
functions. Each segment is actually a different logical address space of the program.
When a process is to be executed, its corresponding segmentation are loaded into non-contiguous
memory though every segment is loaded into a contiguous block of available memory.
Segmentation memory management works very similar to paging but here segments are of
variable-length where as in paging pages are of fixed size.
A program segment contains the program's main function, utility functions, data structures, and so
on. The operating system maintains a segment map table for every process and a list of free
memory blocks along with segment numbers, their size and corresponding memory locations in
main memory.
For each segment, the table stores the starting address of the segment and the length of the
segment. A reference to a memory location includes a value that identifies a segment and an offset.
116
Figure 43:Segmentation
Virtual Memory
A computer can address more memory than the amount physically installed on the system. This
extra memory is actually called virtual memory and it is a section of a hard disk that's set up to
emulate the computer's RAM.
The main visible advantage of this scheme is that programs can be larger than physical memory.
Virtual memory serves two purposes. First, it allows us to extend the use of physical memory by
using disk. Second, it allows us to have memory protection, because each virtual address is
translated to a physical address.
Following are the situations, when entire program is not required to be loaded fully in main
memory.
• User written error handling routines are used only when an error occurred in the data or
computation.
• Certain options and features of a program may be used rarely.
• Many tables are assigned a fixed amount of address space even though only a small amount
of the table is actually used.
• The ability to execute a program that is only partially in memory would counter many
benefits.
• Less number of I/O would be needed to load or swap each user program into memory.
• A program would no longer be constrained by the amount of physical memory that is
available.
• Each user program could take less physical memory, more programs could be run the same
time, with a corresponding increase in CPU utilization and throughput.
117
Modern microprocessors intended for general-purpose use, a memory management unit, or MMU,
is built into the hardware. The MMU's job is to translate virtual addresses into physical addresses.
A basic example is given below −
Demand Paging
A demand paging system is quite similar to a paging system with swapping where processes reside
in secondary memory and pages are loaded only on demand, not in advance.
When a context switch occurs, the operating system does not copy any of the old program’s pages
out to the disk or any of the new program’s pages into the main memory Instead, it just begins
executing the new program after loading the first page and fetches that program’s pages as they are
referenced.
118
Figure 45:Demand Paging
While executing a program, if the program references a page which is not available in the main
memory because it was swapped out a little ago, the processor treats this invalid memory reference
as a page fault and transfers control from the program to the operating system to demand the page
back into the memory.
Using this approach allows the system to prioritize faster physical memory for more frequent
processes and applications, improving the overall performance and preventing the device from
locking up in the event it runs out of system memory.
In addition, the paging file is important to support crash dumps during a system crash (Blue Screen
of Death), as without a large enough page file, a dump with all the contents of the system memory
won't be created.
To adjust the virtual memory size on Windows 10, use these steps:
Note: Although anyone can change the paging file size, it's only recommended to use these
instructions if you have a valid reason, and you know what you're doing.
1. Open Settings.
2. Click on System.
3. Click on About.
4. Under the "Related settings" section, click the System info option.
119
5. Click the "Advanced system settings" option from the left pane.
120
8. Click the Advanced tab.
9. Under the "Virtual memory" section, click the Change button.
10. Clear the Automatically manage paging files size for all drives option.
11. Select the Custom size option.
12. Specify the initial and maximum size for the paging file in megabytes.
121
Note: The size of the virtual memory is unique to each device, and it can't be generalized. However,
usually, it's recommended to use a number that's one and a half times the total available memory for
the "Initial size" and three times of available memory for the "Maximum size" when possible.
13. Click the Set button.
14. Click the OK button.
15. Click the OK button again.
16. Restart your device.
Once you complete the steps, you should notice an increase in performance when navigating
Windows 10 as well as when running multiple apps at the same time.
If you need to revert the changes, you can use the same instructions, but on step No. 10, make sure
to check the Automatically manage paging size for all drives option, and restart your device.
To modify the paging file size with Command Prompt, use these steps:
1. Open Start.
2. Search for Command Prompt, right-click the top result, and select the Run as
administrator option.
3. Type the following command to understand the current status of the paging file and press Enter:
wmic pagefile list /format:list
122
4. Type the following command to switch form manage to custom virtual memory and press Enter:
wmic computersystem where name="%computername%" set
AutomaticManagedPagefile=false
5. Type the following command to set the initial and maximum size of the virtual memory and
press Enter:
This example sets the paging file to "9216" and "12288" megabytes for the initial and maxium size:
123
6. Type the following command to restart your computer and press Enter:
shutdown -r -t 00
• After you complete the steps, the device will start using the new values for virtual memory,
which, if done correctly, should help to improve system performance.
• If you no longer need to use the custom size for virtual memory, you can always revert the
changes and allow Windows 10 to manage this feature using this command: wmic
computersystem where name="%computername%" set
AutomaticManagedPagefile=true and restarting your device.
• While it's recommended to use one and a half times the available memory for the initial and
three times the memory for the maximum size, make sure to test the changes and adjust the
values if you're experiencing freezes, crashes, and other problems.
• Although it's possible to disable virtual memory on Windows 10, even when you have a
large amount of system memory, it's not recommended to disable this feature. Usually, if
you disable paging file, some applications may stop working, some system features may not
work efficiently, and you may end up with some abnormal behaviour.
Conclusion
At the end of this learning outcome, the learner should be able to explain memory management,
illustrate memory management techniques and demonstrate virtual memory management settings
Further Reading
https://www.tutorialspoint.com/operating_system
124
3.3.4.3 Self assessment
Written Assessment
1. What is memory management
2. How are logical memory addresses different from physical memory addresses
3. What causes internal fragmentation?
4. What is swapping?
5. How is simple paging different from demand paging?
6. Why is sufficient virtual memory necessary in a computer system?
7. What is a page map table?
8. Illustrate how a segment map table is used.
9. How does external fragmentation occur
10. What is a page frame?
Oral Assessment
• Describe how demand paging works
Practical Assessment
• Configure the Virtual memory of the provide PC to one and a half size of the current setting
3.3.4.5 References
125
3.3.5 Learning Outcome 4: Understand Input and Output Management
3.3.5.1 Learning Activities
Learning Outcome 4: Understand Input and Output Management
Learning Activities Special Instructions
Introduction
This learning outcome covers explaining input - output management, explaining disk operations,
explaining the computer clock system, explaining virtual input and output, outlining disk selection
criteria, demonstrating verification of disk properties demonstrating disk storage management
operations and demonstrating device management operations.
Input-Output Hardware
One of the important jobs of an Operating System is to manage various I/O devices including
mouse, keyboards, touch pad, disk drives, display adapters, USB devices, Bit-mapped screen,
LED, Analog-to-digital converter, On/off switch, network connections, audio I/O, printers etc.
An I/O system is required to take an application I/O request and send it to the physical device, then
take whatever response comes back from the device and send it to the application. I/O devices can
be divided into two categories −
• Block devices − A block device is one with which the driver communicates by sending
entire blocks of data. For example, Hard disks, USB cameras, Disk-On-Key etc.
• Character devices − A character device is one with which the driver communicates by
sending and receiving single characters (bytes, octets). For example, serial ports, parallel
ports, sounds cards etc.
126
Device Controllers
• Device drivers are software modules that can be plugged into an OS to handle a particular
device. Operating System takes help from device drivers to handle all I/O devices.
• The Device Controller works like an interface between a device and a device driver. I/O
units (Keyboard, mouse, printer, etc.) typically consist of a mechanical component and an
electronic component where electronic component is called the device controller.
• There is always a device controller and a device driver for each device to communicate
with the Operating Systems. A device controller may be able to handle multiple devices.
As an interface its main task is to convert serial bit stream to block of bytes, perform error
correction as necessary.
127
Memory-mapped I/O
When using memory-mapped I/O, the same address space is shared by memory and I/O devices.
The device is connected directly to certain main memory locations so that I/O device can transfer
block of data to/from memory without going through CPU.
While using memory mapped IO, OS allocates buffer in memory and informs I/O device to use
that buffer to send data to the CPU. I/O device operates asynchronously with CPU, interrupts CPU
when finished.
128
• There are two ways that this can happen, known as polling and interrupts. Both of these
techniques allow the processor to deal with events that can happen at any time and that are
not related to the process it is currently running.
Polling I/O
Polling is the simplest way for an I/O device to communicate with the processor. The process of
periodically checking status of the device to see if it is time for the next I/O operation, is called
polling. The I/O device simply puts the information in a Status register, and the processor must
come and get the information.
Interrupts I/O
• An alternative scheme for dealing with I/O is the interrupt-driven method. An interrupt is a
signal to the microprocessor from a device that requires attention.
• A device controller puts an interrupt signal on the bus when it needs CPU’s attention when
CPU receives an interrupt, it saves its current state and invokes the appropriate interrupt
handler using the interrupt vector (addresses of OS routines to handle various events).
• When the interrupting device has been dealt with, the CPU continues with its original task
as if it had never been interrupted.
I/O Software
I/O software is often organized in the following layers −
• User Level Libraries − this provides simple interface to the user program to perform input
and output. For example, stdio is a library provided by C and C++ programming
languages.
• Kernel Level Modules − this provides device driver to interact with the device controller
and device independent I/O modules used by the device drivers.
• Hardware − this layer includes actual hardware and hardware controller which interact
with the device drivers and makes hardware alive.
A key concept in the design of I/O software is that it should be device independent where it should
be possible to write programs that can access any I/O device without having to specify the device
in advance. For example, a program that reads a file as input should be able to read a file on a hard
disk, or on a CD-ROM, without having to modify the program for each different device.
Device Drivers
Device drivers are software modules that can be plugged into an OS to handle a particular device.
Operating System takes help from device drivers to handle all I/O devices. Device drivers
encapsulate device-dependent code and implement a standard interface in such a way that code
contains device-specific register reads/writes.
Device driver, is generally written by the device's manufacturer and delivered along with the device
on a CD-ROM.
129
A device driver performs the following jobs −
• To accept request from the device independent software above to it.
• Interact with the device controller to take and give I/O and perform required error
handling
• Making sure that the request is executed successfully
How a device driver handles a request is as follows: Suppose a request comes to read a block N.
If the driver is idle at the time a request arrives, it starts carrying out the request immediately.
Otherwise, if the driver is already busy with some other request, it places the new request in the
queue of pending requests.
Interrupt handlers
• An interrupt handler, also known as an interrupt service routine or ISR, is a piece of
software or more specifically a callback function in an operating system or more
specifically in a device driver, whose execution is triggered by the reception of an
interrupt.
• When the interrupt happens, the interrupt procedure does whatever it has to in order to
handle the interrupt, updates data structures and wakes up process that was waiting for an
interrupt to happen.
• The technique that operating system uses to determine the request which is to be satisfied
next is called disk scheduling.
• When the disk drive is operating, the disk is rotating at constant speed. To read or write the
head must be positioned at the desired track and at the beginning of the desired sector on
that track
• Track selection involves moving the head in a movable-head system or electronically
selecting one head on a fixed-head system
• On a movable-head system the time it takes to position the head at the track is known as
seek time
• The time it takes for the beginning of the sector to reach the head is known as rotational
delay
• The sum of the seek time and the rotational delay equals the access time
• Disk Response Time- It is the average of time spent by each request waiting for the IO
operation.
A programmable interrupt timer, PIT can be used to trigger operations and to measure elapsed time.
It can be set to trigger an interrupt at a specific future time, or to trigger interrupts periodically on a
regular basis.
The scheduler uses a PIT to trigger interrupts for ending time slices. The disk system for example
may use a PIT to schedule periodic maintenance cleanup, such as flushing buffers to disk.
This technique takes a single physical component and presents it to devices as multiple
components. Because it separates logical from physical resources, IOV is considered an enabling
data center technology that aggregates IT infrastructure as a shared pool, including computing,
networking and storage.
132
Choose a PATA drive if you are repairing or upgrading an older system that lacks SATA
interfaces. Choose an SATA drive if you are repairing or upgrading a system that has SATA
interfaces.
Length of Warranty - warranties provide consumers with a guarantee that the hard disk they
purchase will be repaired or replaced if a defect should crop up that is determined to be the fault of
the manufacturer.
Or, you can use the Run box to open the System Information utility.
• Press Win + R (hold down the Windows key and press R).
• In the Run box, type msinfo32.
• Press Enter or click OK.
133
6. In the System Information window that opens, in the left window pane, you'll see a list of
hardware categories. Expand Components, then Storage. Then, choose Drives, Disks, or any
category you'd like to view.
Disk Management is used to manage the drives installed in a computer—like hard disk drives
(internal and external), optical disk drives, and flash drives. It can be used to partition drives, format
drives, assign drive letters, and much more.
134
Disk Management is available in most versions of Microsoft Windows including Windows 10,
Windows 8, Windows 7, Windows Vista, Windows XP, and Windows 2000.
Note: Even though Disk Management is available in multiple Windows operating systems, some
small differences in the utility do exist from one Windows version to the next.
Disk Management can also be started by executing diskmgmt.msc via the Command Prompt or
another command-line interface in Windows.
The top section of Disk Management contains a list of all the partitions, formatted or not, that
Windows recognizes.
The bottom section of Disk Management contains a graphical representation of the physical drives
installed in the computer.
N/B: The panes and menus you see in Disk Management are customizable, so if you've ever
changed the settings, the above might not be exactly how the program looks to you. For example,
you can change the top pane to be the graphical representation and disable the bottom pane entirely.
Use the View menu to change where the panes are displayed in Disk Management.
135
Performing certain actions on the drives or partitions make them available or unavailable to
Windows and configure them to be used by Windows in certain ways.
Here are some common things that you can do in Disk Management:
i) Partitioning a volume
ii) Formattinga volume
iii) Shrinking volume
Partitioning a volume
The first thing to do after installing a hard drive is to partition it. You have to partition a hard drive,
and then format it, before you can use it to store data.
To partition a hard drive in Windows means to section off a part of it and make that part available
to the operating system. Most of the time, the "part" of the hard drive is the entire usable space, but
creating multiple partitions on a hard drive is also possible so that you can store backup files in one
partition, movies in another, etc.
Don't worry if this sounds like more than you thought — partitioning a hard drive in Windows isn't
hard and usually only takes a few minutes to do.
1. Open Disk Management, the tool included in all versions of Windows that lets you partition
drives, among a number of other things.
136
Note: In Windows 10 and Windows 8/8.1, the Power User Menu is the easiest way to start Disk
Management. You can also start Disk Management via command-line in any version of Windows
but the Computer Management method is probably best for most people.
2. When Disk Management opens, you should see an Initialize Disk window with the message
"You must initialize a disk before Logical Disk Manager can access it."
Initialize Disk window
Don't worry if this window doesn't appear. There are legitimate reasons you may not see it. Skip
on to Step 4 if you don't see this.
3. On this screen, you're asked to choose a partition style for the new hard drive. Choose GPT if the
new hard drive you installed is 2 TB or larger. Choose MBR if it's smaller than 2 TB. Select OK
after making your selection.
4. Locate the hard drive you want to partition from the drive map at the bottom of the Disk
Management window. You might need to maximize the Disk Management or Computer
Management window to see all the drives on the bottom. An unpartitioned drive will not show up in
the drive list at the top of the window.
If the hard drive is new, it will probably be on a dedicated row labeled Disk 1 (or 2, etc.) and will
say Unallocated. If the space you want to partition is part of an existing drive, you'll see
Unallocated next to existing partitions on that drive.
If you don't see the drive you want to partition, you may have installed it incorrectly. Turn
off your computer and double-check that the hard drive is properly installed.
5. Once you've found the space you want to partition, tap-and-hold or right-click anywhere on it,
and choose New Simple Volume.
137
New Partition
6. Choose Next > on the New Simple Volume Wizard window that appeared.
7. Choose Next > on the Specify Volume Size step to confirm the size of the drive you're creating.
138
The default size that you see in the Simple volume size is in MB: field should equal the amount
shown in the Maximum disk space in MB: field. This means that you're creating a partition that
equals the total available space on the physical hard drive.
You're welcome to create multiple partitions that will eventually become multiple, independent
drives in Windows. To do so, calculate how many and how large you want those drives to be and
repeat these steps to create those partitions. For example, if the drive is 61437 MB and you want to
partitions, specify an initial size of 30718 to partition only half the drive, and then repeat the
partitioning again for the rest of the unallocated space.
Select Next > on the Assign Drive Letter or Path step, assuming the default drive letter you see is
OK with you
Windows automatically assigns the first available drive letter, skipping A & B, which on most
computers will be D or E. You're welcome to set the Assign the following drive letter option to
anything that's available.
You're also welcome to change the letter assigned to this hard drive later on if you want. See How
to Change Drive Letters in Windows for help doing that.
8. Choose Do not format this volume on the Format Partition step, and then select Next
9. Verify your choices on the Completing the New Simple Volume Wizard screen.
Volume Type: Simple Volume
Disk selected: Disk 1
Volume size: 61437 MB
Drive letter or path: F:
File system: None
Allocation unit size: Default
NOTE: Because your computer and hard drive are unlikely exactly like above, expect your Disk
selected, Volume size, and Drive letter or path values to be different than what you see here. File
system: None just means that you've decided not to also format the drive right now.
139
10. Choose Finish and Windows will partition the drive, a process that will only take a few seconds
on most computers.
You might notice that your cursor is busy during this time. Once you see the new drive letter (F: in
our example) appear in the listing at the top of Disk Management, then you know the partitioning
process is complete.
11. Next, Windows will try to open the new drive automatically. However, since it's not yet
formatted and can't be used, you'll see this message instead: "You need to format the disk in drive
F: before you can use it. Do you want to format it?"
Formatting a volume
You need to format a hard drive if you plan on using it in Windows. To format a hard drive means
to erase any information on the drive and to set up a file system so your operating system can read
data from, and write data to, the drive.
All operating systems offer this capability and Windows makes it easy. Before formatting a drive, it
must be partitioned first.
The time it takes to format a hard drive in Windows depends almost entirely on the drive's size, but
your computer's overall speed plays a part, too.
2. After Disk Management opens, which might take several seconds, look for the drive you want to
format from the list at the top. There's a lot of information in Disk Management, so if you can't see
everything, maximize the window.
Drive to format
140
3. Look for the amount of storage on the drive as well as the drive name. For example, if it says
Music for the drive name and it has 2 GB of hard drive space, then you've likely selected a small
flash drive full of music.
Feel free to open the drive to make sure that it's what you want to format if it makes you confident
that you're going to format the right device.
If you don't see the drive listed on the top or an Initialize Disk windows appears, it probably means
that the hard drive is new and has not yet been partitioned.
Now that you've found the drive you want to format, right-click it and choose Format to
Existing Drive: If you're formatting a drive that you've been using and that has data on it, double-
check in Explorer that the drive letter you're choosing here in Disk Management is the same as the
one you see in Explorer that has the information on it that you want to erase. Once formatted, the
existing data on the disk are probably unrecoverable for most people.
141
New Drive: If you're formatting a new drive, a great way to tell that it's the right one is to look at
the File System column in the top part of Disk Management. Your existing drives will show file
systems of NTFS or FAT32 but a new, unformatted drive will show RAW instead.
You cannot format your C drive, or whatever drive Windows is installed on, from within
Windows. In fact, the Format option isn't even enabled for the drive with Windows on it.
4. The first of several formatting details which covered over the next several steps is the volume
label, which essentially a name is given to the hard drive.
In the Volume label textbox, enter whatever name you'd like to give to the drive.
If the drive had a previous name and that makes sense for you, by all means, keep it. Drive
letters are assigned during the Windows partitioning process but can easily be changed after the
format is complete.
5. Next up is the file system choice. In the File system textbox, choose NTFS.
NTFS
NTFS is the most recent file system available and is almost always the best choice.
6. In the Allocation unit size textbox, choose Default. The best allocation size based on the size of
the hard drive will be chosen.
It's not at all common to set a custom allocation unit size when formatting a hard drive in Windows.
7. Next is the Perform a quick format checkbox. Windows will check this box by default,
suggesting that you do a "quick format" but we recommend that you uncheck this box so that a
"standard format" is performed.
142
In a standard format, each individual "part" of the hard drive, called a sector, is checked for errors
and overwritten with a zero — a sometimes painfully slow process. This procedure ensures that the
hard drive is physically working as expected, that each sector is a reliable place to store data, and
that existing data is unrecoverable.
In a quick format, this bad sector search and basic data sanitization is skipped entirely and
Windows assumes that the hard drive is free of errors. A quick format is very fast.
The final format option is the Enable file and folder compression setting that is unchecked by
default, which we recommend sticking with.
The file and folder compression feature allows you to choose files or folders to be compressed and
decompressed on the fly, potentially offering considerable savings on hard drive space. The
downside here is that performance can be equally affected, making your day-to-day Windows use
much slower than it would be without compression enabled.
File and folder compression has little use in today's world of very large and very inexpensive hard
drives. In all but the rarest occasions, a modern computer with a large hard drive is better off
protecting all the processing power it can and skipping on the hard drive space savings.
7. Review the settings you've made in the last several steps and then click OK.
8. Windows is usually pretty good about warning you before you might do something damaging,
and a hard drive format is no exception.
Warning message
143
Note: Just as the warning says, all the information on this drive will be erased if you click OK. You
can't cancel the format process halfway through and expect to have half of your data back. As soon
as this starts, there's no going back.
Format progress
If you chose a quick format, your hard drive should only take several seconds to format. If you
chose the standard format, which we suggested, the time it takes the drive to format will depend
144
almost completely on the size of the drive. A small drive will take a small amount of time to format
and a very large drive will take a very long time to format.
Your hard drive's speed, as well as your overall computer's speed, play some part but the size is the
biggest variable.
In the next step, we'll look at whether the format completed as planned.
After the format percentage indicator reaches 100%, wait a few seconds and then check again under
Status and make sure it's listed as Healthy like your other drives.
You may notice that now that the format is complete, the volume label has changed to what you set
it as (New Drive in our case) and the % Free is listed at 100%. There's a little overhead involved so
don't worry if your drive isn't completely empty. That's it!
Your hard drive has been formatted and it's ready for use in Windows. You can use the new drive
however you want — back up files, store music, and videos, etc.
If the hard drive you're reformatting won't ever need to be used again, you can skip the format and
the wipe, and physically or magnetically destroy it instead.
Sharing a volume
Shrinking volume refers to the task of decreasing the size of a partition, which helps to organize
disk space in accordance with specific needs. When you have a large partition that has much free
space to spare, it may make sense to spare free space from the volume by shrinking it, for instance
you can either create a new partition on unallocated space or add it to other partitions.
As we all know, a disk should be partitioned before we can use the space on the disk to store data.
There can be multiple volumes on the disk and each works like distinct area, thus you can separate
operating systems from personal data and manage data orderly.
Thus, this disk is not properly partitioned. There might be too much free space in C drive (system
partition), and the other partition contains too many file types. In this case, you can shrink system
145
volume to a suitable size such as 100GB, and you can get 400GB free space which can be used to
create a new partition to store data.
For the large partition, you can split it, after which you can store working files on one partition,
games on a different partition. Apart from organizing data effective, some user shrinks partition for
the purpose of dual boot computer. There is not enough free space on the disk to create a new
partition for new operating system, and you can shrink a large partition to get free space.
i) Disk Management: Disk Management is the Windows internal tool and it provides basic function
to manage disk and partitions.
Users can extend partition by adding the adjacent free space, shrink partition, create new partition,
etc. But it cannot deal with all partition resizing tasks, for example, unallocated space is not on the
right side or not adjacent to the partition. If you want to do extra operations, you need to use third-
party disk partition software.
ii) Disk partition software: partition management software enables you to create, delete, format,
shrink, extend, split, expand or resize partitions on your hard drive or other storage devices.
Example: DiskGenius Free includes more features than Disk Management and similar third-party
software. Apart from regular functions on disk partitions, it also can wipe hard drive, erase
partition, permanently delete data, image disk/partition, clone partition /disk, convert GPT/MBR
disk, convert virtual disk format, edit hex data, check and repair bad sectors, check partition table
errors, manage virtual disks, etc. Besides, it supports file recovery and partition from various
storage devices.
iii) DiskPart commands: DiskPart commands help to manage disks, partitions, volumes or virtual
disk and you can use it shrink partition if you know how to use it. The shrink command reduces the
size of selected volume by the specified amount. Similar to Disk Management, it is able to get free
disk space from the unused space at the end of selected volume.
Then Disk Management starts to query the volume for available space to shrink, which may take a
couple of seconds, then wait with patience. It'll be better if the partition was properly defragmented
in advance.
146
When the calculation finishes, a window pops up. In Disk Management, you can view all disks and
partitions on your computer, locate the one you want to spare free space. In this case, we are going
to shrink the 120GB New Volume (D :) which is located on basic disk 1.
If Shrink Volume option is grayed out, then it is not supported for the partition, for example the
FAT32 partition of USB flash drive. In this case, you need to use a tool such as DiskGenius to
resize it.
Shrink Volume
3. Specify the disk amount you want to reduce from the partition. Enter the exact disk space in MB
and click Shrink button.
Note: you cannot shrink a partition beyond the point where any unmovable files are located.
147
Disk Management completes the process quickly and the you'll be back at the original interface and
see the shrunk partition and unallocated disk space on the drive. Then you can create a new
partition on it.
This option is available for primary partitions and logical drive or volumes formatted in NTFS file
system and it grays out on FAT32 or FAT16 or any other types partitions.
The shrinking process will fail if there are too many bad clusters on the volume.
If the partition you want to shrink does not have a file system such as RAW drive and contains data
like database file, shrining the drive may destroy the data.
When you try to shrink a system volume, you may not be able to reduce the partition size beyond
the point where unmovable files are stored, like paging file, hibernation file, shadow copy storage
area, etc.
Hardware Optimization
From a hardware perspective there are two things we can do to optimize the performance of our
storage system. The first thing we can do is to upgrade to the fasted hard disk possible.
Hard drives come in different rotational speeds. Currently the slowest drives run at about 5400
revolutions per minute (RPM). The rotation speed dictates how fast data can be written to, or read
from the hard disk drive. The faster the drive spins, the faster it can read data and the faster it can
148
store data. As a bare minimum we should get a 7200 RPM drive. More RPMs also mean more
money for the drive.
The second thing we can do is to upgrade our disk interface. If we have to stick with IDE then we
should ensure that our motherboard supports the ATA133 standard, which transfers data at roughly
133 megabits per second. Also, disks have to support ATA33 standard as well. Upgrading to a
faster disk interface will dramatically improve the throughput of data to and from our hard disk
drive. Because of that we should move away from the older ATA/IDE interface and upgrade to a
serial ATA disk interface (SATA). By doing this we can upgrade speed to 150 megabytes for
SATA 1, 300 MB for SATA 2, or 600 MB for SATA 3.
Software Optimization
Disk Clean-up
When talking about software optimization one of the key things that we can do is keep our disk
clean. That means that we should get rid of the files that we don’t need. Mostly empty drive is
faster than a full one. A drive that is mostly full is a bit slower because the hard disk interface has to
go all over the hard drive to find pieces of a file or trying to find an empty space in which to save a
file.
To accomplish this, one thing we can do is to run Disk Cleanup utility. To run disk clean-up, go to
the properties of the drive and in the General tab click on the Disk Clean-up button. Disk
Clean-up helps us to dispose of files that can be safely removed from the disk. Those include
emptying the Recycle Bin, deleting temporary files such as those used by Internet Explorer
(temporary Internet files), application installation files, installation log files, offline web pages,
hibernation files, Windows error reports, and also compressing old files. We can also run Dick
Clean-up in CMD by typing cleanmgr.
Regular users can also run Disk Clean-up wizard, but they will be only able to delete user specific
files, and not system files.
Another thing we can do is to remove unused Windows components. When Windows is installed
by default a certain set of Windows components are included in the installation. To do that we can
go into Control Panel > Add/remove programs > Windows Components and deselect different
components that we never use. Getting rid of certain things that we don’t use frees up space on the
hard disk drive. When our hard disk drive has more free space the disk interface can read
information faster and it can write information faster.
Fragmentation
Another thing we can do is to defragment our disk drive.
When hard disk controller writes data to the disk it scatters parts of the same file over different
areas of the disk. This is called fragmentation, and it gets worse as time goes along. After we first
149
install an operating system and start installing applications, disk isn’t fragmented very badly, since
new files and folders are created on available free space in contiguous blocks.
This is the most optimized way to store files on our disk. The fragmentation occurs over time, as we
delete and then add new files. That’s because as the free space reduces, the amount of contiguous
block is also reduced. Pretty soon fragments are stored all over the hard disk drive. In other words,
different parts of the same file are stored on different sectors of the hard drive, which leads to
suboptimal performance.
On the picture below we can see how files are scattered on the disk. In this example the disk should
be defragmented. White area indicates free space, while other lines indicates data on the drive.
When we try to open fragmented file, in order for system to display that file, the disk interface has
to find all the chunks of the file on the disk, then reassemble them and load it into memory so that
the application can use it. The more fragmented a file is, the longer it takes to read the information
from the disk.
The same thing is when we’re writing information. If we have empty chunks of hard disk space
which are scattered all over the disk, and we’ve got a large file that needs to be written, that file will
get fragmented as it is written to the disk, which will slow things down. In order to fix this we need
to defragment the hard disk drive. When we defragment the drive, the system will take all the
chunks of the same file and put them in contiguous blocks. They will still be separate chunks, but
they’ll be next to each other.
So, the defragmentation is the process of moving parts of a file to contiguous sectors on the hard
disk drive, to increase the speed of access and retrieval. We can do this using the defragmentation
utility that comes with Windows.
To defragment disks in Windows, go to the properties of the drive, open the Tools tab and click on
the Defragment Now button. Before the defragmentation we will have to analyze the disk first. The
more information on the drive, the more time it will take to defragment the drive. To run Disk
Defragmenter in CMD we can type in the Defrag command.
We should configure our computer to run defragmentation on a schedule. We can use our computer
during the defragmentation process, but it is recommended not to since we can actually create
additional fragmentation as we work. Remember that we can’t defragment network drives, and that
only one defragmentation process can run at the time.
150
To determine if our disk needs defragmentation, we can use the Analyze Disk option. We have to
have administrative rights to run defragmentation.
Error checking tool looks for and fixes two different things. First it looks for lost clusters. A lost
cluster is a series of clusters on the hard disk drive that are not associated with a particular file. Data
is there but it’s unknown as to what file that data belongs to. Error checking tool looks for those and
tries to repair them. Usually it can repair them, but sometimes it can’t. If we’re in a situation where
we can’t repair lost clusters that usually means we’ve got some serious disk errors and we’re going
to be losing some data.
The second thing that errors checking utility checks for are cross linked files. A cross linked file
occurs when two files try to claim the same cluster. Both of files claim that particular cluster is a
part of itself. Error checking tool will look for cross linked filed and fix those. Orphaned files are
files that exist on the hard drive but which are not associated with a directory in the index.
Normally Check Disk can re-associate the file with the correct directory. Abad sector is a portion of
the hard disk that cannot be used. Bad sectors are marked so that they are no longer used. Any used
bad sectors are redirected to another sector. The NTFS file system automatically detects bad sectors
as the system saves and reads files.
We can run Check Disk by typing Chkdsk command at a command prompt. We can also use
Chkdsk command with the /f switch to automatically fix errors without scanning for bad sectors.
Also, we can use the /r switch to scan and fix bad sectors and other errors.
Check Disk replaces the ScanDisk utility that was available in Windows 9x/Me, so Check Disk is
sometimes referred to as Scan Disk.
We should perform defragmentation and disk checking on regular basis and do them frequently.
How frequently depends on how heavily the system is used. If we have a heavily used system we
should run error checking scan, disk clean up and disk defragmentation about once a week, maybe
even more frequently.
If it’s a system that doesn’t get used much then we could probably get away with doing this once a
month. To check for disk errors in Windows, go to the properties of the drive, open the Tools tab
and click on the Check Now button.
151
Device Manager is a Windows utility that allows you to update and reinstall drivers for individual
devices (e.g. your video card, sound card or network card).
IMPORTANT: Windows Device Manager doesn’t always detect outdated drivers. So you
can’t assume all your drivers are up to date
(There are other ways to open Device Manager; it changes depending on your version of Windows.
But the above method works for all versions of Windows)
3. Select a category and expand it to see the devices in that category.
4. If you see a yellow triangle or question mark next to a device, that means Windows has detected
that it has an outdated or corrupt driver. For example:
152
Figure 50: Windows Device Manager
When you see this yellow mark, the device has a corrupt or outdated driver. You can try to update
or reinstall the driver as described below.
153
6. Select Search automatically for updated driver software.
154
3. Select a category and expand it to see the devices in that category. Right-click the device whose
driver you’d like to reinstall.
4. Select Uninstall device.
155
But all driver updates are important, even when Windows calls them ‘optional’. If they weren’t, the
hardware manufacturers wouldn’t go to all the trouble of coding and releasing them.
Sometimes these ‘optional’ updates include just a new, nice-to-have feature, and you can arguably
do without that. But sometimes it’s an important bug fix – perhaps the old driver is causing your
device to stop working or your computer to crash. Windows often categorizes these updates as
‘Critical’, but definitely not always.
Other times, it’s not Device Manager’s fault at all. It’s just that the device manufacturer has failed
to include the drivers you need in the latest Windows Update.
To do this, you’ll need to know the brand and model of the device, as well as your exact operating
system and whether it’s 32 or 64 bit. Then you have to find the manufacturer’s driver download
page, find the correct driver, and check that it’s newer than the one you already have installed.
Conclusion
At the end of this learning outcome, the trainee should be able to explain input - output
management, explain disk operations, explain the computer clock system, explain virtual input and
output, outline disk selection criteria, verify disk properties demonstrate disk storage management
operations and demonstrate device management operations.
Further reading
1. https://www.drivereasy.com/knowledge/a-common-and-easy-way-to-access-device-
manager-in-windows/
2. https://docs.microsoft.com/en-us/windows-server/storage/disk-management/overview-of-
disk-management
3.2.5.4 Self assessment
Written Assessment
156
Oral Assessment
1. What circumstances would require device drivers to be updated?
2. Which options are available for hardware optimisation?
Practical Assessment
Use appropriate tools to:
• Check for disk errors
• Perform disk cleaning
• Check hard disk properties
• View driver settings
3.3.2.5 References
1. https://www.javatpoint.com/os-disk-scheduling
2. https://www.tutorialspoint.com/operating_system/os_io_hardware.htm
3. https://www.ifixit.com/Wiki/Choosing_a_Hard_Drive
157
3.3.6 Learning Outcome 5. Understand File Management and local policy settings
3.3.6.1 Learning Activities
Learning Outcome 5: Understand File Management and local policy settings
Learning Activities Special Instructions
3.3.6.2 Information sheet No 3/LO5: Understand File management and local policy settings
Introduction
This learning outcome covers explaining file management, file access methods, file allocation
techniques, file protection and security and demonstrating file and directory operations and local
policy settings
File Management
The file management system is a software which is used to create, delete, modify and control
access and save files.
Security
By supporting authorization, it restricts unauthorized user to log into system and access files.
Username and password are required for authorization purpose. It supports file encryption feature
and asks for authorization to access those encrypted files.
Integrity
In support of integrity, file management system will keep track of data manipulations like deletion,
modification, addition of data, etc. If the data gets modified, deleted or added, then those changes
should be reflected in all the files.
Storage
This allocates memory for storing files, deallocates memory of deleted or unused files and
maintains backups.
158
Definitions
File
A file is a named collection of related information that is recorded on secondary storage such as
magnetic disks, magnetic tapes and optical disks. In general, a file is a sequence of bits, bytes,
lines or records whose meaning is defined by the files creator and user.
Files are used to provide a uniform view of data storage by the operating system. All the files are
mapped onto physical devices that are usually nonvolatile so data is safe in the case of system
failure.
File Attributes
The attributes of a file may vary a little on different operating systems. However, the common file
attributes are:
Name
This denotes the symbolic name of the file. The file name is the only attribute that is readable
by humans easily.
Identifier
This denotes the file name for the system. It is usually a number and uniquely identifies a file
in the file system.
Type
If there are different types of files in the system, then the type attribute denotes the type of file.
Location
This points to the device that a particular file is stored on and also the location of the file on
the device.
Size
This attribute defines the size of the file in bytes, words or blocks. It may also specify the
maximum allowed file size.
Protection
The protection attribute contains protection information for the file such as who can read or
write on the file.
File Structure
A File Structure should be according to a required format that the operating system can
understand.
• A file has a certain defined structure according to its type.
• A text file is a sequence of characters organized into lines.
• A source file is a sequence of procedures and functions.
• An object file is a sequence of bytes organized into blocks that are understandable by the
machine.
• When operating system defines different file structures, it also contains the code to support
these file structure. UNIX, MS-DOS support minimum number of file structure.
159
File Access Methods in Operating Systems
File access mechanism refers to the manner in which the records of a file may be accessed. There
are several ways to access files −
• Sequential access
• Direct/Random access
• Indexed sequential access
Sequential access
A sequential access is that in which the records are accessed in some sequence, i.e., the
information in the file is processed in order, one record after the other. This access method is the
most primitive one. Example: Compilers usually access files in this fashion.
Direct/Random access
• Random access file organization provides, accessing the records directly.
• Each record has its own address on the file with by the help of which it can be directly
accessed for reading or writing.
• The records need not be in any sequence within the file and they need not be in adjacent
locations on the storage medium.
Contiguous Allocation
• Each file occupies a contiguous address space on disk.
• Assigned disk address is in linear order.
• Easy to implement.
• External fragmentation is a major issue with this type of allocation technique.
Linked Allocation
• Each file carries a list of links to disk blocks.
• Directory contains link / pointer to first block of a file.
• No external fragmentation
• Effectively used in sequential access file.
160
• Inefficient in case of direct access file.
Indexed Allocation
• Provides solutions to problems of contiguous and linked allocation.
• An index block is created having all pointers to files.
• Each file has its own index block which stores the addresses of disk space occupied by the
file.
• Directory contains the addresses of index blocks of files.
For a single laptop system, we might provide protection by locking the computer in a desk
drawer or file cabinet. For multi-user systems, different mechanisms are used for the
protection.
The mechanism of the protection provide the facility of the controlled access by just
limiting the types of access to the file. Access can be given or not given to any user
depends on several factors, one of which is the type of access required.
Operations like renaming, editing the existing file, copying; these can also be controlled.
There are many protection mechanism. Each of them mechanism have different
advantages and disadvantages and must be appropriate for the intended application.
Access Control
There are different methods used by different users to access any file. The general way of
protection is to associate identity-dependent access with all the files and directories and
161
list called access-control list (ACL) which specify the names of the users and the types of
access associate with each of the user.
The main problem with the access list is their length. If we want to allow everyone to read
a file, we must list all the users with the read access. This technique has two undesirable
consequences:
The most common recent approach is to combine access-control lists with the normal
general owner, group, and universe access control scheme. For example: Solaris uses the
three categories of access by default but allows access-control lists to be added to
specific files and directories when more fine-grained access control is desired.
Windows 10 offers the user a number of methods to change file system attributes for folders and
files. Each attribute can have only one state at a moment: it can be set or disabled. While file
attributes are part of file system metadata, they always considered separate from other metadata
values like file date or permissions.
In Windows 10, you can use File Explorer (both the Ribbon option and the File Properties dialog),
PowerShell, and the command prompt to modify or set file attributes.
163
Figure 52: Windows file sharing
4. When you've chosen the user or group to share with, click Add.
5. Click Share to make the changes you've selected, then click Done to close.
File permissions
164
File permissions control what can happen to items you've shared. Usually, they'll be either 'Read' or
'Read/Write'.
By default, Windows 10 shares files and folders in 'Read' mode. Users will be able to open them,
but they can't save any changes to the original file.
To let others change a file, or add items to a shared folder, you'll have to give them permission.
To change permissions for an item, follow steps 1-3 above. After you've added the name of the user
or group, click the drop-down to change the permission level for that user to Read/Write before
clicking Share.
This window has three tabs filled with settings. Here’s how to access the Folder Options window,
browse its settings, change them, and apply your desired configuration:
The Folder Options window appears at the General tab. Here are settings for browsing folders in
File Explorer, opening an item in File Explorer, and whether to show recently used files and folders
in Quick Access.
1. In the General tab, change the settings that you’re interested in.
2. Click the View tab.
165
Figure 53:Customising Files and directories using the File Explorer
Here you find settings for viewing files and folders in File Explorer.
The list of settings is long. Browse through the list and read what they do. Each name is self-
explanatory.
3. Change any advanced settings that you want.
4. Click the Search tab.
Here you find settings for using search in Windows 10 and in File Explorer.
166
The Search tab in Folder Options.
5. Change how search works.
6. To apply your settings, click OK.
When a local setting is inaccessible, it indicates that a GPO currently controls that setting.
To configure a setting using the Local Security Policy console
1. To open Local Security Policy, on the Start screen, type secpol.msc, and then press ENTER.
2. Under Security Settings of the console tree, do one of the following:
167
Figure 54:Configuring Local security policy
o Click Account Policies to edit the Password Policy or Account Lockout Policy.
o Click Local Policies to edit an Audit Policy, a User Rights Assignment, or Security
Options.
3. When you find the policy setting in the details pane, double-click the security policy that you
want to modify.
4. Modify the security policy setting, and then click OK.
Note
o Some security policy settings require that the device be restarted before the setting takes
effect.
o Any change to the user rights assignment for an account becomes effective the next
time the owner of the account logs on.
To configure a security policy setting using the Local Group Policy Editor console
You must have the appropriate permissions to install and use the Microsoft Management Console
(MMC), and to update a Group Policy Object (GPO) on the domain controller to perform these
procedures.
1. Open the Local Group Policy Editor (gpedit.msc).
2. In the console tree, click Computer Configuration, click Windows Settings, and then
click Security Settings.
3. Do one of the following:
o Click Account Policies to edit the Password Policy or Account Lockout Policy.
o Click Local Policies to edit an Audit Policy, a User Rights Assignment, or Security
Options.
4. In the details pane, double-click the security policy setting that you want to modify.
Note
If this security policy has not yet been defined, select the Define these policy settings check
box.
5. Modify the security policy setting, and then click OK.
Note
If you want to configure security settings for many devices on your network, you can use the Group
Policy Management Console.
Conclusion
At the end of this learning outcome, the learner should be able to explain file management, file
access methods, file allocation techniques, file protection and security and demonstrate file and
directory operations and local policy settings
Further Reading
1. https://www.tutorialspoint.com/operating_system/os_file_system.htm
2. https://www.tutorialspoint.com/computer_concepts/computer_concepts_file_management_syste
m.htm
168
3.3.6. 3 Self-assessment
Written Assessment
1. What is a file?
2. Outline five file operations
3. Which attributes does a file possess?
4. How does contiguous allocation allocate file space?
5. Which are the three classification of users under the condensed version of the access control
list?
Oral Assessment
Describe available file protection and security operating system mechanisms
Practical Assessment
1. Select a file from a folder in your computer and set its permissions and share it to everyone on
your network.
2. Configure folder options to ensure all hidden files, folders and drives are displayed.
3.3.6.5 References
1. https://www.tutorialspoint.com/File-System-Management
2. https://www.geeksforgeeks.org/protection-in-file-system/?ref=rp
3. https://docs.microsoft.com/en-us/windows/security/threat-protection/security-policy-
settings/how-to-configure-security-policy-settings
169
CHAPTER 4: MATHEMATICS FOR COMPUTER SCIENCE
4.1 Introduction
This unit covers the competencies required to understand Mathematics for Computer Science. It
involves understanding Linear Algebra, understanding Boolean algebra, understanding Set Theory,
understanding Calculus and understanding Probability and Statistics.
170
4. Understand Calculus
5. Understand Probability and Statistics
171
4.3.2 Learning Outcome 1: Understand Linear Algebra
4.3.2.1 Learning Activities
Learning Outcome 1: Understand Linear Algebra
Learning Activities Special Instructions
Introduction
This learning outcome covers explaining and solving linear equations, explaining and illustrating
vectors and matrix operations and illustrating inverse of a matrix.
Definitions
❏ Vector: A quantity with a magnitude (a non-negative number) and a direction is called a
vector
Linear Equations
172
The graph of y = 2x+1 is a straight line
Example 1:
• A linear equation is a polynomial of degree 1.
• In order to solve for the unknown variable, you must isolate the variable.
• In the order of operation, multiplication and division are completed before addition and
subtraction.
Solve for x in 5 x - 6 = 3 x - 8
Subtract 3x from both sides of the equation:
The answer is x = - 1
Example 2:
Solve for x in 4 x - 6 = 12 x - 30
Subtract 4x from both sides of the equation:
The answer is x = 3
Check the solution by substituting 3 in the original equation for x. If the left side of the
equation equals the right side of the equation after the substitution, you have found the
correct answer.
• Left side: 4(3) - 6 = 6
173
• Right side: 12(3) - 30 = 6
Vectors
A vector is an object which has both magnitude as well as direction. It is usually represented by an
arrow which shows the direction (→) and its length shows the magnitude. The arrow which
indicates the vector has an arrowhead and its opposite end is the tail. It is denoted as V⃗ . The
magnitude of the vector is represented as |V|. Two vectors are termed as equal if they have equal
magnitudes and equal direction.
Addition of Vectors
Let us consider there are two vectors P and Q, then the sum of these two vectors can be performed
when the tail of vector Q meets with the head of vector A. And during this addition, the magnitude
and direction of the vectors should not change. The vector addition follows two important laws,
which are;
• Commutative Law: P + Q = Q + P
• Associative Law: P + (Q + R) = (P + Q) + R
Subtraction of Vectors
Here, the direction of other vectors is reversed and then the addition is performed on both the given
vectors. If P and Q are the vectors, for which the subtraction method has to be performed, then we
invert the direction of another vector say for Q, to make it -Q. Now, we need to add vector P and -
Q. So here the direction of the vectors are opposite each other but the magnitude remains the same.
• P – Q = P + (-Q)
Multiplication of Vectors
If k is a scalar quantity and it is multiplied by a vector A, then the scalar multiplication is given by
kA. If k is positive then the direction of the vector kA is the same as vector A, but if the value of k
is negative, then the direction of vector kP will be opposite to the direction of vector A. And the
magnitude of the vector kP is given by |k|.
Dot Product
The dot product is often called a scalar product. It is represented using a dot(.) between two vectors.
Here, two coordinate vectors of equal length are multiplied in such a way that they result in a single
number. So basically when we take the scalar product of two vectors the result is either a number of
a scalar quantity. Suppose P and Q are two vectors, then the dot product for both the vectors is
given by;
• P.Q = |P| |Q| cos θ
174
If P and Q are both in the same direction, i.e. θ = 0°, then;
• P.Q = |P| |Q|
Cross Product
A cross product is denoted by the multiplication sign(x) between two vectors. It is a binary vector
operation, defined in a three-dimensional system. If P and Q are two independent vectors, then the
result of the cross product of these two vectors (P x Q) is perpendicular to both the vectors and
normal to the plane that contains both the vectors. It is represented by;
• P x Q = |P| |Q| sin θ
Therefore,
P.Q = 1.3 + 3. (-5) + (-4).2
= 3 – 15 – 8
= -20
Matrices
A matrix is a two - dimensional collection of elements. We use bold upper case letters to
denote matrices. For example,
is a matrix with two rows and three columns, or a 2 × 3 matrix. Individual elements are labeled
with the first subscript indicating the row, and the second indicating the column. An n -
175
element column vector may be considered an n × 1 matrix, and an n - element row vector may
be considered a 1 × n matrix.
Types of matrices
Symmetric Matrix: A square matrix is symmetric if elements with interchanged subscripts are equal:
For example,
is symmetric.
Hermitian Matrix: A square complex matrix is Hermitian if elements with interchanged subscripts
are equal to the complex conjugate of each other:
Toeplitz Matrix: A square matrix is Toeplitz if all elements along the upper left to lower right
diagonals are equal:
For example:
is Toeplitz.
Identity Matrix: A square matrix that is all zero except for ones along the main diagonal is the
identity matrix, denoted as I .
For example,
is an n × n identity matrix.
Triangular Matrix: All elements of a lower triangular matrix above the main diagonal are zero.
All elements of an upper triangular matrix below the main diagonal are zero. For example,
is a triangular matrix.
176
Matrix operations
Addition and subtraction
Two or more vectors or matrices of the same dimensions may be added or subtracted by
adding/subtracting individual elements.
For example, if
then
Scalar multiplication
Two matrices, where the column dimension of the first (m) is equal to the row dimension of
the second, may be multiplied by forming the dot product of the rows of the first matrix and
the columns of the second; that is
For example, if
then
We can multiply a number (a.k.a. scalar) by a matrix by multiplying every entry of the
matrix by the scalar this is denoted by juxtaposition or ·, with the scalar on the left:
177
Determinant
The determinant of a square matrix is a measure of scale change when the matrix is viewed as a
linear transformation. When the determinant of a matrix is zero, the matrix is indeterminate or
singular, and cannot be inverted. The rank of matrix |A| is the largest square array in A that has
nonzero determinant.
The determinant of matrix A is denoted as det (A) or |A|. Laplace’s method for computing
determinants uses cofactors , where a cofactor of a given matrix element ij is
For 2 × 2 matrix
The determinant is the sum of the products of matrix elements and cofactors for any row or
column. Thus
For a 3 × 3 matrix A ,
178
Transposition
The transpose of a matrix, denoted with superscript T , is formed by interchanging row and
column elements:
For example,
A square matrix that multiplies another square matrix to produce the identity matrix is called
the inverse, and is denoted by a superscript − 1
Example 1
because
179
but you can’t have a − 2b = 1 and −a + 2b = 0
Conclusion
At the end of this learning outcome, the learner should be able to explain and solve linear equations,
explain and illustrate vectors and matrix operations and illustrate inverse of a matrix.
Further Reading
1. https://www.math-only-math.com/solving-linear-equations.html
2. http://www.sosmath.com/algebra/solve/solve1/s13/S1301/S1301.html
3. https://byjus.com/maths/vector-algebra/
4.3.2.3 Self-Assessment
Written Assessment
1. For each matrix below, determine the order and state whether it is a square matrix.
2. Verify that matrices A and B given below are inverses of each other.
180
a. 0
b. 1
c. 2
d. 3
7. A set of linear equations is represented by the matrix equation Ax = b. The necessary
condition for the existence of a solution for this system is
A.A must be invertible
B. b must be linearly depended on the columns of A
C. b must be linearly independent of the columns of A
D.None of these
8. The system of linear equations
(4d - 1)x +y + z = 0
-y+z=0
(4d - 1) z = 0
has a non-trivial solution, if d equals
A. 1/2
B. 1/4
C. 3/4
D. 1
9. The rank of a 3 x 3 matrix C (= AB), found by multiplying a non-zero column matrix A of
size 3 x 1 and a non-zero row matrix B of size 1 x 3, is
A.0
B. 1
C. 2
D.3
10. If A and B are square matrices of size n x n, then which of the following statement is not
true?
A.det. (AB) = det (A) det (B)
B. det (kA) = kn det (A)
C. det (A + B) = det (A) + det (B)
D.det (AT) =1/det (A-1)
Oral Assessment
1. Why is y2 − 2 = 0 not a linear equation?
2. Explain inverse of square matrix.
Practical Assessment
1. Solve each of the following equations.
181
2. Verify that matrices A and B given below are inverses of each other.
4.3.2.5 References
1. http://people.math.harvard.edu/~jjchen/math21a/handouts/vectors.html
2. https://onlinelibrary.wiley.com/doi/pdf/10.1002/9780470890042.app1
3. https://www.math10.com/en/geometry/vectors-operations/vectors-operations.html
4. https://www.analyzemath.com/linear-algebra/matrices/matrices-examples-and-questions-
with-solutions.html
182
4.3.3 Learning outcome 2: Understand Boolean Algebra
4.3.3.1 Learning Activities
Learning Outcome 2: Understand Boolean Algebra
Learning Activities Special Instructions
Introduction:
This learning outcome covers explaining Boolean algebra, basic Boolean operations, secondary
operations, illustratingboolean expressions, simplifying Boolean expressions, illustrating Boolean
laws and theorems and simplification rules for Boolean expressions.
Boolean algebra
Boolean algebra is used to analyze and simplify the digital (logic) circuits. It uses only the binary
numbers that is 0 and 1. It is also referred to as Binary Algebra or Logic Algebra.
Boolean algebra is the mathematics we use to analyse digital gates and circuits. We can use these
“Laws of Boolean” to both reduce and simplify a complex Boolean expression in an attempt to
reduce the number of logic gates required. Boolean algebra is therefore a system of mathematics
based on logic that has its own set of rules or laws which are used to define and reduce Boolean
expressions.
i) The logic gates are the main structural part of a digital system.
ii) Logic Gates are a block of hardware that produces signals of binary 1 or 0 when input logic
requirements are satisfied.
183
iii) Each gate has a distinct graphic symbol, and its operation can be described by means of algebraic
expressions.
iv) The seven basic logic gates include: primary operations (AND, OR, NOT), secondary operations
(XOR, NAND, NOR, and XNOR).
v) The relationship between the input-output binary variables for each gate can be represented in
tabular form by a truth table.
vi) Each gate has one or two binary input variables designated by A and B and one binary output
variable designated by x.
AND: The AND gate is an electronic circuit which gives a high output only if all its inputs are high.
The AND operation is represented by a dot (.) sign.
OR: The OR gate is an electronic circuit which gives a high output if one or more of its inputs are
high. The operation performed by an OR gate is represented by a plus (+) sign.
NOT: The NOT gate is an electronic circuit which produces an inverted version of the input at its
output. It is also known as an Inverter.
184
NAND: The NOT-AND (NAND) gate which is equal to an AND gate followed by a NOT gate. The
NAND gate gives a high output if any of the inputs are low. The NAND gate is represented by a
AND gate with a small circle on the output. The small circle represents inversion.
NOR: The NOT-OR (NOR) gate which is equal to an OR gate followed by a NOT gate. The NOR
gate gives a low output if any of the inputs are high. The NOR gate is represented by an OR gate with
a small circle on the output. The small circle represents inversion.
XOR: The 'Exclusive-OR' gate is a circuit which will give a high output if one of its inputs is high
but not both of them. The XOR operation is represented by an encircled plus sign.
185
XNOR: The 'Exclusive-NOR' gate is a circuit that does the inverse operation to the XOR gate. It will
give a low output if one of its inputs is high but not both of them. The small circle represents inversion.
186
Inversion law This law uses the NOT
operation. The inversion
law states that double
inversion of a variable
results in the original
variable itself
187
Simplification (Reduction) Rules for Boolean expressions
Let us consider an example of a Boolean function: AB+A (B+C) + B (B+C)
The logic diagram for the Boolean function AB+A (B+C) + B (B+C) can be represented as:
Sample logic diagram 1
We will simplify this Boolean function on the basis of rules given by Boolean algebra.
AB + A (B+C) + B (B+C)
AB + AB + AC + BB + BC {Distributive law; A (B+C) = AB+AC, B (B+C) = BB+BC}
AB + AB + AC + B + BC {Idempotent law; BB = B}
AB + AC + B + BC {Idempotent law; AB+AB = AB}
AB + AC +B {Absorption law; B+BC = B}
B + AC {Absorption law; AB+B = B}
Conclusion:
At the end of this learning outcome, the learner should be able to explain Boolean algebra, basic
Boolean operations, secondary operations, illustrate Boolean expressions, simplify Boolean
expressions, illustrate Boolean laws and theorems and illustrate simplification rules for Boolean
expressions.
Further Reading
1. Wolfram, S. A New Kind of Science. Champaign, IL: Wolfram Media, p. 1168, 2002
2. http://www.ee.surrey.ac.uk/Projects/Labview/minimisation/karnaugh.html
188
4.3.3.3 Self-Assessment
Written Assessment
1. Simplify the Boolean expression (A+B+C)(D+E)' + (A+B+C)(D+E) and choose the best
answer.
1. A + B + C
2. D + E
3. A'B'C'
4. D'E'
5. None of the above
2. Which of the following relationships represents the dual of the Boolean property x + x'y = x
+ y?
1. x'(x + y') = x'y'
2. x(x'y) = xy
3. x*x' + y = xy
4. x'(xy') = x'y'
5. x(x' + y) = xy
3. Given the function F(X,Y,Z) = XZ + Z(X'+ XY), the equivalent most simplified Boolean
representation for F is:
1. Z + YZ
2. Z + XYZ
3. XZ
4. X + YZ
5. None of the above
4. Which of the following Boolean functions is algebraically complete?
1. F = xy
2. F = x + y
3. F = x'
4. F = xy + yz
5. F = x + y'
5. The logic gate that provides high output for same inputs ____________
a) NOT
b) X-NOR
c) AND
d) XOR
6. Algebra of logic is termed as
a. Numerical logic
b. Boolean algebra
c. Arithmetic logic
d. Boolean number
7. F(X,Y,Z,M) = X`Y`Z`M`. The degree of the function is
a. 2
b. 5
189
c. 4
d. 1
8. Boolean algebra can be used
a. For designing of the digital computers
b. Circuit theory
c. Building algebraic functions
d. In building logic symbols
9. A ______ value is represented by a Boolean expression.
a. Positive
b. Recursive
c. Negative
d. Boolean
10. What is the logic gate that provides high output for same inputs?
a. NOT
b. X-NOR
c. AND
d. XOR
Oral Assessment
Practical Assessment
1. Given that F = A'B'+ C'+ D'+ E', which of the following represent the only correct
expression for F'?
1. F'= A+B+C+D+E
2. F'= ABCDE
3. F'= AB(C+D+E)
4. F'= AB+C'+D'+E'
5. F'= (A+B)CDE
2. An equivalent representation for the Boolean expression A' + 1 is
1. A
2. A'
3. 1
4. 0
3. Simplification of the Boolean expression AB + ABC + ABCD + ABCDE + ABCDEF yields
which of the following results?
1. ABCDEF
2. AB
3. AB + CD + EF
4. A + B + C + D + E + F
5. A + B(C+D(E+F))
190
4.3.3.4 Tools, Equipment, Supplies and Materials
● Internet
● Calculator
● Computer
● Instruction material
● Stationery
4.3.3.5 References
3. https://www.electronicshub.org/boolean-algebra-laws-and-theorems/
4. https://www.javatpoint.com/boolean-algebra
191
4.3.4 Learning outcome 3: Understand Set Theory
4.3.4.1 Learning Activities
Learning Outcome 3: Understand Set Theory
Learning Activities Special Instructions
Introduction:
This learning outcome covers explaining set theory, illustrating methods of set representation,
explaining cardinality of a set, illustrating types of sets, Venn diagrams and set operations.
Definitions
Set theory: Set theory is the mathematical theory of well-determined collections, called sets, of
objects that are called members, or elements, of the set
Set Theory
A set is a collection of distinct objects, called elements of the set
A set can be defined by describing the contents, or by listing the elements of the set, enclosed in curly
brackets.
A set simply specifies the contents; order is not important. The set represented by {1, 2, 3} is
equivalent to the set {3, 1, 2}.
Notation
Commonly, we will use a variable to represent a set, to make it easier to refer to that set later.
The symbol ∈ means “is an element of”.
A set that contains no elements, { }, is called the empty set and is notated ∅
Let A = {1, 2, 3, 4}
To notate that 2 is element of the set, we’d write 2 ∈ A
Subset
A subset of a set A is another set that contains only elements from the set A, but may not contain all
the elements of A.
If B is a subset of A, we write B ⊆ A
A proper subset is a subset that is not identical to the original set—it contains fewer elements.
192
If B is a proper subset of A, we write B ⊂ A
Statement form
In this representation, the well-defined description of the elements of the set is given. Below are some
examples of the same.
1. The set of all even number less than 10.
2. The set of the number less than 10 and more than 1.
Roster form
In this representation, elements are listed within the pair of brackets {} and are separated by commas.
Below are two examples.
1. Let N is the set of natural numbers less than 5.
N = { 1 , 2 , 3, 4 }.
2. The set of all vowels in the English alphabet.
V = { a , e , i , o , u }.
Cardinality of a set
The number of elements in a set is the cardinality of that set. The cardinality of the set A is often
notated as |A| or n(A)
Answers:
The cardinality of B is 4, since there are 4 elements in the set.
The cardinality of A ⋃ B is 7, since A ⋃ B = {1, 2, 3, 4, 5, 6, 8}, which contains 7 elements.
The cardinality of A ⋂ B is 3, since A ⋂ B = {2, 4, 6}, which contains 3 elements.
Types of sets
There are many types of set in the set theory:
Singleton set
193
If a set contains only one element it is called to be a singleton set.
Hence the set given by {1}, {0}, {a} are all consisting of only one element and therefore are singleton
sets.
Finite Set
A set consisting of a natural number of objects, i.e. in which number element is finite is said to be a
finite set. Consider the sets
A = { 5, 7, 9, 11} and B = { 4 , 8 , 16, 32, 64, 128}
Obviously, A, B contain a finite number of elements, i.e. 4 objects in A and 6 in B. Thus they are
finite sets.
Infinite set
If the number of elements in a set is finite, the set is said to be an infinite set.
Thus the set of all natural numbers is given by N = { 1, 2, 3, ...} is an infinite set. Similarly the set of
all rational number between ) and 1 given by
A = {x:x E Q, 0 <x<1} is an infinite set.
Equal set
Two set A and B consisting of the same elements are said to be equal sets. In other words, if an
element of the set A sets the set A and B are called equal i.e. A = B.
A Venn diagram represents each set by a circle, usually drawn inside of a containing box representing
the universal set. Overlapping areas indicate elements common to both sets.For example; set A{1, 2,
4, 8} is represented as:
Sample Venn diagram
194
Set Operations: Set Union, Set Intersection, Complement of Set
The union of two sets contains all the elements contained in either set (or both sets). The union is
notated A ⋃ B. More formally, x ∊ A ⋃ B if x ∈ A or x ∈ B (or both)
Union of two sets
The intersection of two sets contains only the elements that are in both sets. The intersection is
notated A ⋂ B. More formally, x ∈ A ⋂ B if x ∈ A and x ∈ B.
The complement of a set A contains everything that is not in the set A. The complement is notated
A’, or Ac, or sometimes ~A.
Complement of a set A
Universal set
A universal set is a set that contains all the elements we are interested in. This would have to be
defined by the context.
A complement is relative to the universal set, so Ac contains all the elements in the universal set that
are not in A.
Universal set
195
Figure 58:Universal set
‘U’ denotes the universal set. Above Venn diagram shows that A is a subset of B
Cartesian Products
Let A and B be two sets. Cartesian product of A and B is denoted by A × B, is the set of all ordered
pairs (a,b), where a belong to A and b belong to B.
A × B = {(a, b) | a ∈ A ∧ b ∈ B}.
Conclusion
At the end of this learning outcome, the learner should be able to explain set theory, illustrate methods
of set representation, explain cardinality of a set, illustrate types of sets, Venn diagrams and set
operations.
Further Reading
https://www.mbacrystalball.com/blog/2015/10/09/set-theory-tutorial/
4.3.4.3 Self-Assessment
Written Assessment
1. There are 30 students in a class. Among them, 8 students are learning both English and French.
A total of 18 students are learning English. If every student is learning at least one language,
how many students are learning French in total?
a. 30
b. 22
c. 20
d. 24
2. In a group, there were 115 people whose proofs of identity were being verified. Some had
passport, some had voter id and some had both. If 65 had passport and 30 had both, how many
had voter id only and not passport?
A. 30
B. 50
C. 80
D. None of the above
3. Among a group of people, 40% liked red, 30% liked blue and 30% liked green. 7% liked both
red and green, 5% liked both red and blue, and 10% liked both green and blue. If 86% of them
liked at least one colour, what percentage of people liked all three?
A. 10
B. 6
C. 8
D. None
4. The set A = {1, 3, 5}. What is a larger set this might be a subset of?
196
a. 2,4,6
b. 2,6,8
c. 5,7,9
d. 7,8,9
5. If A and B are sets and A⋃B = A⋂B, then
a. A=B
b. A= θ
c. B= θ
d. None of these
6. If X and Y are two sets then X⋂(Y⋃X) equals
A. Y
B. Θ
C. X
D. None of these
7. The number of elements in the power set of the set {{a, b},c} is
a. 7
b. 3
c. 4
d. 8
8. Order of the power set of a set of order n is
a. 2^n
b. n^2
c. 2n
d. n
9. In a beauty contest half the number of experts voted for Mr. A and two thirds voted for Mr.
B. Ten voted for both and six did not vote for either. How many experts were there in total?
a. 18
b. 24
c. 36
d. None of these
10. Let n (A) denote the number of elements in set A if n(A) = p and n(B) =q then how many
ordered pairs (a, b) are there with a ∈A and b ∈B?
a. 2pq
b. p x q
c. p^2
d. p + q
Oral Assessment
1. What is cardinality?
2. Define set theory.
Practical Assessment
1. Consider the sets:
A = {red, green, blue}
B = {red, yellow, orange}
197
C = {red, orange, yellow, green, blue, purple}
Find A ⋃ B
Find A ⋂ B
Find Ac⋂ C
2. Among a group of students, 50 played cricket, 50 played hockey and 40 played volleyball. 15
played both cricket and hockey, 20 played both hockey and volleyball, 15 played cricket and
volleyball and 10 played all three. If every student played at least one game, find the number
of students and how many played only cricket, only hockey and only volley ball?
4.3.4.5 References
1. https://www.britannica.com/science/set-theory
2. https://courses.lumenlearning.com/atd-hostos-introcollegemath/chapter/set-theory
198
4.3.5 Learning outcome 4: Understand Calculus
4.3.5.1 Learning Activities
Learning Outcome 4: Understand Calculus
Learning Activities Special Instructions
4.1 Functions and graphs are explained Activities may be carried out
4.2 Differential calculus is illustrated in groups or as individual
4.3 Integral calculus is illustrated
Introduction:
This learning outcome covers explaining functions and graphs and illustrating differential and
integral calculus.
Definitions
Calculus: The word Calculus comes from Latin meaning "small stone", because it is like
understanding something by looking at small pieces
Differential calculus: Differential Calculus cuts something into small pieces to find how it changes
Integral calculus: Integral Calculus joins (integrates) the small pieces together to find how much
there is
Functions
What exactly is a function? An equation will be a function if, for any x in the domain of the equation
(the domain is all the x’s that can be plugged into the equation), the equation will yield exactly one
value of y when we evaluate the equation at a specific x.
For example: y = x2 +1
is a function because given an x, there is only one way to square it and then add 1 to the result. So,
no matter what value of x you put into the equation, there is only one possible value of y when we
evaluate the equation at that value of x.
y2 = x+1 is not a function because there are two possible values of y that we could use here. We
could use y=2 or y=−2. Since there are two possible values of y that we get from a single x, then
this equation isn’t a function.
199
Domain and range of a function
In simplest terms the domain of a function is the set of all values that can be plugged into a function
and have the function exist and have a real number for a value. So, for the domain we need to avoid
division by zero, square roots of negative numbers, logarithms of zero and logarithms of negative
numbers etc.
The range of a function is simply the set of all possible values that a function can take.
For example; Find the domain and range of each of the following functions.
f(x)=5x−3
We know that this is a line and that it’s not a horizontal line (because the slope is 5 and not zero…).
This means that this function can take on any value and so the range is all real numbers. Using
“mathematical” notation this is,
Range:(−∞,∞)
This is more generally a polynomial and we know that we can plug any value into a polynomial and
so the domain in this case is also all real numbers or,
Domain:−∞<x<∞or(−∞,∞) of functions
Many of the basic functions of calculus could be expressed as graphs
For example;
Example 1
Example 2
There really isn’t much to this problem outside of reminding ourselves of what absolute value is.
Recall that the absolute value function is defined as,
200
The graph is then,
Again, there really isn’t much to this other than to make sure it’s been graphed somewhere so we
can say we’ve done it
Graph 3: y = x3
Limits
Limits are all about approaching. Sometimes you can't work something out directly, but you can
see what it should be as you get closer and closer!
201
For example; The limit of (x2−1)/(x−1) as x approaches 1 is 2
And it is written in symbols as:
So, in truth, we cannot say what the value at x=1 is. But we can say that as we approach 1, the limit
is 2.
Intercepts
X Intercept: where the graph of an equation crosses the x-axis; Y Intercept: where the graph of an
equation crosses the y-axis
When you want the x intercepts (x,0): Set y=0 then solve for x
When you want the y intercepts (0,y): Set x=0 then solve for y
For example; Find the intercepts of y = x2 − 4
x intercept: set y=0; 0 = x2 − 4; x2 = 4; x = 2 or −2
The points are (2,0) and (−2,0)
Derivatives (Differential Calculus): The Derivative is the "rate of change" or slope of a function.
203
Simplify it as best we can, then make Δx shrink towards zero. Like this:
204
Common functions and rules of Derivatives
There are rules we can follow to find many derivatives.
For example:
● The slope of a constant value (like 3) is always 0
● The slope of a line like 2x is 2, or 3x is 3 etc
205
First and second order differential equations
Integral calculus
Integration can be used to find areas, volumes, central points and many useful things. But it is
easiest to start with finding the area under the curve of a function like this
206
What is the area under y = f(x)? We write dx to mean the Δx is approaching zero
The symbol for "Integral" is a stylish "S" (for "Sum", the idea of summing slices). After the Integral
Symbol we put the function we want to find the integral of (called the Integrand), and then finish
with dx to mean the slices go in the x direction (and approach zero in width)
Notation
207
Graph 4: Indefinite integral
Further Reading
http://tutorial.math.lamar.edu
4.3.5.3 Self-Assessment
Written Assessment
1. The function of f(x)=3x(x-2) has a maximum at
a. X=1
b. X=2
c. Both of the above
d. None of the above
2. The function of f(x)=3x(x-2) has a minimum at
a. X=1
b. X=2
c. Both of the above
d. None of the above
3. Maxima and minima occur
a. Simultaneously
b. Once
c. Alternately
d. Rarely
4. What is the integral of 1/x ?
a. X^2
b. lnx
c. x
d. 2x
5. If x+y=k, x>0,y>0 then xy is maximum when
a. x=ky
b. kx=y
c. x=y
d. None of these
6. What is the derivative of 3x^5+4?
a. 15x
b. 15x^2
c. 15x^3
d. 15x^4
7. Area bounded by the parabola 2y=x^2 and the line x=y-4 is equal to
a. 18
b. 6
c. Infinite
209
d. None of these
8. The minimum value of |x ^2-5x+21| is
a. 0
b. -1
c. -2
d. -5
9. Sum of the perimeters of a circle and a square is 1. If sum of the area is least, then
a. Side of the square is double the radius of the circle
b. Side of the square if half the radius of the circle
c. Side of the square is equal to the radius of the circle
d. None of these
10. The limit of the function f(x)=[1-a^4/x^4] as x approaches infinity is given by
a. exp[-a^4]
b. 1
c. Infinity
d. Zero
Oral Assessment
1. Explain the power rule in differential calculus
2. Differentiate between first order and second order differential equations
Practical Assessment
1. Evaluate
210
4.3.6 Learning outcome 5: Understand Probability and Statistics
4.3.6.1 Learning Activities
5.1 Key terminologies in Probability are explained Activities may be carried out
5.2 Probability axioms and simple counting problems are in groups or as individual
illustrated
5.3 Permutations and combinations are illustrated
5.4 Conditional probability and the multiplication rule are
illustrated
5.5 Key terminologies in Statistics are explained
5.6 Data representation techniques are illustrated
5.7. Measures of central tendency are illustrated
5.8 Measures of spread are illustrated
5. 9 Measure of Location are illustrated
Definitions
❏ Probability: Probability is the measure of the likelihood that an event will occur in a
random Experiment
❏ Sample space: The set of all possible outcomes of a game, experiment or other situation.
❏ Independence: The occurrence of one event does not affect the probability of the
occurrence of another.
❏ Probability theory: The mathematical study of probability (the likelihood of occurrence of
random events in order to predict the behavior of defined systems).
Probability Axioms
We assign a probability measure P(A) to an event A. This is a value between 0 and 1 that shows
how likely the event is. If P(A) is close to 0, it is very unlikely that the event A occurs. On the other
hand, if P(A) is close to 1, A is very likely to occur. The main subject of probability theory is to
develop tools and techniques to calculate probabilities of different events. Probability theory is
based on some axioms that act as the foundation for the theory.
Axioms of Probability:
• Axiom 1: For any event A, P(A)≥0.
• Axiom 2: Probability of the sample space S is P(S)=1
211
• Axiom 3: If A1,A2,A3,⋯ are disjoint events, then
P(A1∪A2∪A3⋯)=P(A1)+P(A2)+P(A3)+⋯
The first axiom states that probability cannot be negative. The smallest value for P(A) is zero and
if P(A)=0, then the event A will never happen.
The second axiom states that the probability of the whole sample space is equal to one, i.e., 100
percent. The reason for this is that the sample space S contains all possible outcomes of our random
experiment. Thus, the outcome of each trial always belongs to S, i.e., the event S always occurs
and P(S)=1. In the example of rolling a die, S={1,2,3,4,5,6, and since the outcome is always among
the numbers 1 through 6, P(S)=1.
The third axiom is probably the most interesting one. The basic idea is that if some events are
disjoint (i.e., there is no overlap between them), then the probability of their union must be the
summations of their probabilities.
Example 1
In a presidential election, there are four candidates. Call them A, B, C, and D. Based on our polling
analysis, we estimate that A has a 20 percent chance of winning the election, while B has a 40
percent chance of winning. What is the probability that A or B win the election?
Solution:
Notice that the events that {A wins}, {B wins}, {C wins}, and {D wins}are disjoint since more
than one of them cannot occur at the same time.
For example, if A wins, then B cannot win. From the third axiom of probability, the probability of
the union of two disjoint events is the summation of individual probabilities.
Therefore,
P(A wins or B wins) =P({A wins}∪{B wins})
=P({A wins})+P({B wins})
=0.2+0.4
=0.6
P(A1∪A2)=P(A1)+P(A2)
The same argument is true when you have n disjoint events A1,A2,⋯,An:
P(A1∪A2∪A3⋯∪An)=P(A1)+P(A2)+⋯+P(An), if A1,A2,⋯,An are disjoint.
212
In fact, the third axiom goes beyond that and states that the same is true even for a countably infinite
number of disjoint events.
As we have seen, when working with events, intersection means "and", and union means "or". The
probability of intersection of A and B, P(A∩B), is sometimes shown by P(A,B) or P(AB).
• P(A∪B)=P(A or B).
Illustration of axioms
Suppose that we are given a random experiment with a sample space S. To find the probability of
an event, there are usually two steps:
first, we use the specific information that we have about the random experiment. Second, we use
the probability axioms.
Let's look at an example. Although this is a simple example and you might be tempted to write the
answer without following the steps, we encourage you to follow the steps.
Example 2
Solution
Let's first use the specific information that we have about the random experiment. The problem
states that the die is fair, which means that all six possible outcomes are equally likely, i.e.,
P({1})=P({2})=⋯=P({6}).
Now we can use the axioms of probability. In particular, since the events
{1},{2},⋯,{6}{1},{2},⋯,{6} are disjoint we can write
1 =P(S)
=P({1}∪{2}∪⋯∪{6})
=P({1})+P({2})+⋯+P({6})
=6P({1})
Thus,
P({1})=P({2})=⋯=P({6})=16.
Again since {1} and {5} are disjoint, we have
P(E)=P({1,5})=P({1})+P({5})=26=13.
213
It is worth noting that we often write P(1) instead of P({1}) to simplify the notation, but we should
emphasize that probability is defined for sets (events) not for individual outcomes. Thus, when we
write P(2)=16, what we really mean is that P({2})=16.
When the order doesn't matter, it is a Combination. For example, a cloth with 3 colours - grey,
yellow and red. When describing the cloth, you name its colours irrespective of the order. We have
Combinations with Repetition and Combinations without Repetition
When the order does matter it is a Permutation. For example; "The combination to the safe is 472".
Now we do care about the order. "724" won't work, nor will "247". It has to be exactly 4-7-2
Conditional probability is the probability of an event ( A ), given that another ( B ) has already
occurred.
Suppose we have two events A and B where the probability of event B is positive, that is P(B) > 0.
Then the probability of A given B is defined as the quotient
P(A|B)=P(A∩B)P(B)
Example
Suppose that we draw two cards out of a deck of cards and let A be the event the the first card is
an ace, and B be the event that the second card is an ace, then:
P(A)=4/52
And:
214
P(B|A)=3/51
The denominator in the second equation is 51 since we know a card has already been drawn.
Therefore, there are 51 left in total. We also know the first card was an ace, therefore:
P(A∩B)=P(A)⋅P(B|A)=4/52⋅3/51=0.0045
Statististics
This is the practice or science of collecting and analysing numerical data in large quantities,
especially for the purpose of inferring proportions in a whole from those in a representative sample.
Line Graph: a graph that shows information that is connected in some way (such as change over
time)
215
Pie Chart: a special chart that uses "pie slices" to show relative sizes of data
For example;
A survey of "How long does it take you to eat breakfast?" has these results:
Minutes:0 1 2 3 4 5 6 7 8 9 10 11 12
People:6 2 3 5 2 5 0 0 2 3 7 4 1
Which means that 6 people take 0 minutes to eat breakfast (they probably had no breakfast!), 2
people say they only spend 1 minute having breakfast, etc.
216
And here is the dot plot:
Mean
Add up the numbers and divide by how many numbers
For example, mean of 2, 4, 6
2+4+6 = 12
12/2 = 6
Mode
Simply list all numbers in order and choose the middle one
For example; mode of 2, 4, 6 is 4 (middle number)
Median
The Mode is the value that occurs most often
For example; the median of 1,4,5,6,5,5,1 is 5
Measures of spread
Variance
217
The variance of a random variable X is a measure of how concentrated the distribution
of a random variable X is around its mean (The average of the squared differences from
the Mean).
To calculate the variance follow these steps:
● Work out the Mean (the simple average of the numbers)
● Then for each number: subtract the Mean and square the result (the squared
difference).
● Then work out the average of those squared differences.
Standard deviation
The Standard Deviation is a measure of how spread out numbers are. Its symbol is σ
(the greek letter sigma) and it is the square root of the Variance.
Example
Given the heights of wooden logs are: 600mm, 470mm, 170mm, 430mm and
300mm. Find out the Mean, the Variance, and the Standard Deviation
i) Mean
Mean = (600 + 470 + 170 + 430 + 300) /5
= (1970) /5
= 394
Variance
Variance = σ2
= (2062 + 762 + (−224)2 + 362 + (−94)2) /5
= (42436 + 5776 + 50176 + 1296 + 8836) /5
= 108520 /5
= 21704
Standard Deviation = σ
= √21704
= 147.32...
= 147 (to the nearest mm)
Measure of Location
Quartiles are the values that divide a list of numbers into quarters:
i) Put the list of numbers in order
ii) Then cut the list into four equal parts
iii) The Quartiles are at the "cuts"
For example, given the numbers 2, 4, 4, 5, 6, 7, 8; find the Quartiles
218
And the result is:
Quartile 1 (Q1) = 4
Quartile 2 (Q2), which is also the Median, = 5
Quartile 3 (Q3) = 7
Conclusion:
At the end of this learning outcome, the learner should be able to explain key terminologies in
probability and statistics, illustrate probability axioms and simple counting problems, permutations
and combinations, conditional probability and multiplication rule, measures of central tendency,
measures of spread and measures of location.
Further Reading
1 https://www.probabilitycourse.com/chapter1/
2. https://bgsu.instructure.com/courses/901773/pages/p5-definition-of-conditional-probability-
and-multiplying-probabilities?module_item_id=6367147
3. https://courses.lumenlearning.com/boundless-statistics/chapter/probability-rules/
4.3.6.3 Self-Assessment
Written Assessment
1. What are the quartiles for the following set of numbers?
13, 18, 6, 20, 25, 11, 9, 18, 3, 30, 16, 9, 8, 23, 26, 17
A. Q1 = 22.5, Q2 = 10.5, Q3 = 8.5
219
B. Q1 = 9, Q2 = 16.5, Q3 = 19
C. Q1 = 10, Q2 = 16.5, Q3 = 21.5
D. Q1 = 9, Q2 = 16.5, Q3 = 21.5
2. The following are the measures of central tendency except
a. Mean
b. Mode
c. Mass
d. Median
3. The following are scores made on a math test 80,90,90,85,60,70,75,85,90,60,80. What is the
median of these scores?
a. 80
b. 85
c. 70
d. 90
4. What is the mode of the following numbers 1,2,2,8,9,14?
a. 9
b. 14
c. 8
d. 2
5. Which set of data has a mean of 15, a range of 22, and a median of 14 and a mode of 14?
a. 14,22,15,15,9
b. 14,22,14,15,4
c. 25,15,14,3,7
d. 3,14,19,25,14
6. If the total sum of a square is 20 and the sample variance is 5 then the total number of
observations are
a. 25
b. 15
c. 35
d. 4
7. In a manufacturing company the number of employees in unit A is 40, the mean is $6400
and the number of employees in unit B is 30 with the mean of Rs. 5500 the combined
arithmetic mean is
a. 9500
b. 7014.29
c. 6014.29
d. 8000
8. The value of 1st quartile is 23 and the inter-quartile range is 20. What is the value of the 3rd
quartile
a. 73
b. 63
c. 53
d. 43
220
9. What is the probability of getting a sum 9 from two throws of a dice?
a. 1/8
b. 1/12
c. 1/6
d. 1/9
10. Three unbiased coins are tossed. What is the probability of getting at most two heads?
a. ¾
b. 3/8
c. 7/8
d. ¼
Oral Assessment
1. Name the measures of central tendency
2. What is variance and how does it relate to standard deviation?
Practical Assessment
1. Given the numbers 200, 300, 401, 225, 500, 630 and 900, calculate mean, variance
and standard deviation.
4.3.6.5 References
1. https://www.mathsisfun.com/
2. https://www.mathsisfun.com/data/data-graph.php
221
CHAPTER 5: FUNDAMENTALS OF PROGRAMMING
5.1 Introduction
This unit covers the competencies required to understand fundamentals of programming. It involves
understanding programming concepts, understanding the Java environment, performing data
operations, using control structures, using methods and understanding Object Oriented programming.
222
5.3.2 Learning Outcome 1: Understand programming concepts
5.3.2.1 Learning Activities
Learning Outcome No. 1: Understand Special Instructions
Programming Concepts
Introduction
This learning outcome covers explaining programming, phases of program development, key
terms in programming, types of code, programming translators and OOP fundamental concepts.
Programming
Programming is the process of creating a set of instructions that tell a computer how to perform a
task. Programming can be done using a variety of computer "languages," such as SQL, Java,
Python, and C++.
2. Design a program
The requirement specifications from the first phase are studied in this phase and the system
design is prepared. This system design helps in specifying hardware and system requirements and
helps in defining the overall system architecture.
3. Coding
With inputs from the system design, the system is first developed in small programs called units,
which are integrated in the next phase. Each unit is developed and tested for its functionality,
which is referred to as Unit Testing.
5. Document
In this phase all the information about the system is well documented
6. Maintain
There are some issues which come up in the client environment. To fix those issues, patches are
released. Also to enhance the product some better versions are released. Maintenance is done to
deliver these changes in the customer environment.
Source code
Source code is the fundamental component of a computer program that is created by a
programmer. It can be read and easily understood by a human being
Executable
An executable is a file that contains a program - that is, a particular kind of file that is capable of
being executed or run as a program in the computer.
Compiling
It is the process which the source code undergo to produce an output with the help of an
executable program.
Debugging
Debugging is the routine process of locating and removing computer program bugs, errors or
abnormalities, which is methodically handled by software programmers via debugging tools.
Debugging checks, detects and corrects errors or bugs to allow proper program operation
according to set specifications.
Types of code
Source code
Source code is the list of human-readable instructions that a programmer writes often in a word
processing program when he is developing a program.
Object code
224
Object code is the output of a compiler after it processes source code
Machine code
Machine code is a computer program written in machine language. It uses the instruction set of a
particular computer architecture. It is usually written in binary. Machine code is the lowest level
of software.
Interpreter
An interpreter is a computer program, which coverts each high-level program statement into the
machine code. This includes source code, pre-compiled code, and scripts.
Assembler
An assembler is a program that converts assembly language into machine code. It takes the basic
commands and operations from assembly code and converts them into binary code that can be
recognized by a specific type of processor.
Conclusion
At the end of this learning outcome, the trainee should be able to explain phases of program
development, types of code and translators and understand the OOP programming concepts.
Further reading
5.3.2.3 Self-Assessment
Written Assessment
1. Which is the first stage in program development?
225
(a) Design a program
(b) Establish program requirements
(c) Coding
(d) Code test and debug
2. Which step of program development could project termination be done?
(a) Design a program
(b) Establish program requirements
(c) Coding
(d) System maintenance phase.
3. Which of the following is the most important phase in system development?
(a) Design a program
(b) Establish program requirements
(c) Establishing program requirement
(d) Code test and debug
4. Which of the following is NOT a programming translator?
(a) Compiler
(b) Interpreter
(c) Assembler
(d) CPU
5. What are the phases of program development?
6. What is an algorithm?
7. What is a compiler?
Oral Assessment
1. What do you understand by Object Oriented programming?
2. What are the common types of codes in java?
Practical Assessment
Research on which contemporary programming languages use compilers and those that use
translators
5.3.2.4 Tools, Equipment, Supplies and Materials
● Computer
● Internet
● Stationery
● Instruction material
5.3.2.5 References
1. https://www.tutorialspoint.com/computer_programming/index.htm
226
5.3.3 Learning outcome 2: Understand the Java Environment
5.3.3.1 Learning Activities
Introduction
This learning outcome covers installing java, demonstrating the Java Environment, explaining
features of Java and demonstrating java syntax.
Installation of Java
The Java Development Kit (JDK) allows you to code and run Java programs. It's possible that you
install multiple JDK versions on the same PC. But it’s recommended that you install only the latest
version.
227
Step 2) Next,
1. Accept License Agreement
2. Download latest Java JDK for your version (32 or 64 bit) of java for Windows.
Step 3) Once the download is complete, run the exe for install JDK. Click Next
Step 4) Select the PATH for Java installation and click next.
228
Step 5) Once installation is complete, click Close
Let's look into the steps to set the PATH and CLASSPATH
Step 1) Right Click on the My Computer and Select the properties
229
Step 3) Click on Environment Variables
230
Step 6) Copy the path of bin folder which is installed in JDK folder.
Step 7) Paste Path of bin folder in Variable value and click on OK Button.
Note: In case you already have a PATH variable created in your PC, edit the PATH variable to
PATH = <JDK installation directory>\bin;%PATH%;
Here, %PATH% appends the existing path variable to our new value
Start the Eclipse Installer executable. You may get a security warning to run this file. If the Eclipse
Foundation is the Publisher, you are good to select Run.
For Mac and Linux users, you will still need to unzip the download to create the Installer. Start the
Installer once it is available.
232
• Select and click on the package you want to install.
5. Launch Eclipse
Once the installation is complete you can now launch Eclipse.
Features of Java
• Object Oriented
In Java, everything is an Object. Java can be easily extended since it is based on the Object model.
233
• Platform Independent
Unlike many other programming languages including C and C++, when Java is compiled, it is not
compiled into platform specific machine, rather into platform-independent byte code. This byte code
is distributed over the web and interpreted by the Virtual Machine (JVM) on whichever platform it is
being run on.
• Simple
Java is designed to be easy to learn. If you understand the basic concept of OOP Java, it would be
easy to master.
• Secure
With Java's secure feature it enables to develop virus-free, tamper-free systems. Authentication
techniques are based on public-key encryption.
• Architecture-neutral
Java compiler generates an architecture-neutral object file format, which makes the compiled code
executable on many processors, with the presence of Java runtime system.
• Portable
Being architecture-neutral and having no implementation dependent aspects of the specification
makes Java portable.
• Robust
Java makes an effort to eliminate error-prone situations by emphasizing mainly on compile time error
checking and runtime checking.
• Multithreaded
With Java's multithreaded feature it is possible to write programs that can perform many tasks
simultaneously. This design feature allows the developers to construct interactive applications that
can run smoothly.
• Interpreted
Java byte code is translated on the fly to native machine instructions and is not stored anywhere. The
development process is more rapid and analytical since the linking is an incremental and light-weight
process.
• High Performance
With the use of Just-In-Time compilers, Java enables high performance.
• Distributed
Java is designed for the distributed environment of the internet.
• Dynamic
Java is considered to be more dynamic than C or C++ since it is designed to adapt to an evolving
environment. Java programs can carry an extensive amount of run-time information that can be used
to verify and resolve accesses to objects at run-time.
Java syntax
• Case Sensitivity
Java is case sensitive, which means identifier Hello and hello would have different meaning in
Java.
• Class names
234
For all class names the first letter should be in Upper Case. If several words are used to form a
name of the class, each inner word's first letter should be in Upper Case.
Example: class MyFirstJavaClass
• Method names
All method names should start with a Lower Case letter. If several words are used to form the name
of the method, then each inner word's first letter should be in Upper Case.
Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as
'MyFirstJavaProgram.java'
public static void main
In Java programs, the point from where the program starts its execution or simply the entry point of
Java programs is the main() method. Hence, it is one of the most important methods of Java and
having proper understanding of it is very important.
Making the main() method public makes it globally available. It is made public so that JVM can
invoke it from outside the class as it is not present in the current class.
235
class GeeksforGeeks {
private static void main(String[]
args)
{
System.out.println("I am a
Geek");
}
}
Error: Main method not found in class, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
• ·Static: It is a keyword which is when associated with a method, makes it a class related
method. The main() method is static so that JVM can invoke it without instantiating the
class. This also saves the unnecessary wastage of memory which would have been used by
the object declared only for calling the main() method by the JVM.
class GeeksforGeeks {
public void main(String[] args)
{
System.out.println("I am a
Geek");
}
}
Error: Main method is not static in class test, please define the main method
as:
public static void main(String[] args)
Void: It is a keyword and used to specify that a method doesn’t return anything. As main() method
doesn’t return anything, its return type is void. As soon as the main() method terminates, the java
program terminates too. Hence, it doesn’t make any sense to return from main() method as JVM
can’t do anything with the return value of it.
class GeeksforGeeks {
public static int main(String[] args)
{
System.out.println("I am a
Geek");
return1;
}
}
Error: Main method not found in class, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
• main: It is the name of Java main method. It is the identifier that the JVM looks for as the
starting point of the java program. It’s not a keyword.
236
class GeeksforGeeks {
public static void myMain(String[]
args)
{
System.out.println("I am a Geek");
}
}
Error: Main method not found in class, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
• String[] args: It stores Java command line arguments and is an array of type
java.lang.String class. Here, the name of the String array is args but it is not fixed and user
can use any name in place of it.
class GeeksforGeeks {
// javac GeeksforGeeks.java
// java GeeksforGeeks 1 2 3
public static void main(String[]
args)
{
for(String elem : args)
System.out.println(elem);
}
}
1
2
3
Apart from the above mentioned signature of main, you could use public static void main(String
args[]) or public static void main(String… args) to call the main function in java. The main
method is called if it’s formal parameter matches that of an array of Strings
• Identifiers
In programming languages, identifiers are used for identification purpose. In Java, an identifier can
be a class name, method name, variable name or a label. For example :
public class Test
{
public static void main(String[] args)
{
int a = 20;
}
}
Modifiers
Modifiers are keywords that you add to those definitions to change their meanings. Java language
has a wide variety of modifiers, including the following −
• Java Access Modifiers
• Non Access Modifiers
To use a modifier, you include its keyword in the definition of a class, method, or variable. The
modifier precedes the rest of the statement, as in the following example.
public class className {
// ...
}
238
Non-Access Modifiers
Java provides a number of non-access modifiers to achieve many other functionality.
• The static modifier for creating class methods and variables.
• The final modifier for finalizing the implementations of classes, methods, and variables.
• The abstract modifier for creating abstract classes and methods.
• The synchronized and volatile modifiers, which are used for threads.
Variables
A variable can be thought of as a container which holds value for you, during the life of a Java
program. Every variable is assigned a data type which designates the type and quantity of value
it can hold.
Conclusion
At the end of this learning outcome, the trainee should be able to install Java, understand java
programming environment, explain features of Java and understand the java syntax.
Further Reading
5.3.3.3 Self-Assessment
Written Assessment
1. Which component is used to compile, debug and execute java program?
a) JVM
b) JDK
c) JIT
d) JRE
2. Which component is responsible to run java programs?
a) JVM
b) JDK
c) JIT
d) JRE
3. Which statement is true about java?
a) Platform independent programming language
b) Platform dependent programming language
239
c) Code dependent programming language
d) Sequence dependent programming language
4. Which of the below is invalid identifier with the main method?
a) public
b) static
c) private
d) final
Oral Assessment
1. Differentiate between JDE and Eclipse IDE
2. How do you set the Java environment variables?
Practical Assessment
1. Download and install JDE
2. Download, install and launch Eclipse IDE
5.3.3.5 References
https://www.javatpoint.com/java-tutorial
240
5.3.4 Learning outcome 3: Perform Data Operations
5.3.4.1 Learning Activities
Learning Outcome No. 3: Perform Data Operations Special Instructions
Introduction
This learning outcome covers explaining data types, types of statements, variable and constants,
demonstration of data operations and creating a program to perform a specified operation.
Based on the data type of a variable, the operating system allocates memory and decides what can
be stored in the reserved memory. Therefore, by assigning different data types to variables, you can
store integers, decimals, or characters in these variables.
241
• The default value is 0
• Example: int a = 100000, int b = -200000
Float
• Float data type is a single-precision 32-bit IEEE 754 floating point
• Float is mainly used to save memory in large arrays of floating point numbers
• Default value is 0.0f
• Float data type is never used for precise values such as currency
• Example: float f1 = 234.5
Strings
• A Java string data type is a sequence or string of connected characters (Java char data type
objects). The String is also a class, meaning it has its own methods. These methods include
checking for string length, transforming to upper or lower case, and replacing values in
strings with other value
Boolean
● boolean data type represents one bit of information
● There are only two possible values: true and false
● This data type is used for simple flags that track true/false conditions
● Default value is false
● Example: boolean one = true
Java statements
Statements are everything that make up a complete unit of execution. For example,
int score = 9*5;
Here, 9*5 is an expression that returns 45, and int score = 9*5; is a statement.
Expression Statements
Some expressions can be made into statement by terminating the expression with a ;. These are
known as expression statements. For example:
number = 10;
242
Here, number = 10 is an expression where as number = 10; is a statement that compiler can execute.
++number;
Here, ++number is an expression where as ++number; is a statement.
Declaration Statements
Declaration statements declares variables. For example,
Double tax = 9.5;
Control-flow statements
Control-flow statements determine the order that statements are executed. Typically, Java
statements parse from the top to the bottom of the program. However, with control-flow
statements, that order can be interrupted to implement branching or looping so that the Java
program can run particular sections of code based on certain conditions.
Local Variables
• Local variables are declared in methods, constructors, or blocks.
• Local variables are created when the method, constructor or block is entered and the
variable will be destroyed once it exits the method, constructor, or block.
• Access modifiers cannot be used for local variables.
• Local variables are visible only within the declared method, constructor, or block.
• Local variables are implemented at stack level internally.
• There is no default value for local variables, so local variables should be declared and an
initial value should be assigned before the first use.
Example
Here, age is a local variable. This is defined inside pupAge() method and its scope is limited to only
this method.
public class Test {
public void pupAge() {
int age = 0;
age = age + 7;
System.out.println("Puppy age is : " + age);
243
}
Output
Puppy age is: 7
Class Variables
• Class variables also known as static variables are declared with the static keyword in a class,
but outside a method, constructor or a block.
• There would only be one copy of each class variable per class, regardless of how many
objects are created from it.
• Static variables are rarely used other than being declared as constants. Constants are
variables that are declared as public/private, final, and static. Constant variables never
change from their initial value.
• Static variables are stored in the static memory. It is rare to use static variables other than
declared final and used as either public or private constants.
• Static variables are created when the program starts and destroyed when the program stops.
• Visibility of static variables is similar to instance variables. However, most static variables
are declared public since they must be available for users of the class.
• Default values are same as instance variables. For numbers, the default value is 0; for
Booleans, it is false; and for object references, it is null. Values can be assigned during the
declaration or within the constructor. Additionally, values can be assigned in special static
initializer blocks.
• Static variables can be accessed by calling with the class name ClassName.VariableName.
• When declaring class variables as public static final, then variable names (constants) are all
in upper case. If the static variables are not public and final, the naming syntax is the same
as instance and local variables.
Example
import java.io.*;
public class Employee {
// salary variable is a private static variable
private static double salary;
// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";
public static void main(String args[]) {
salary = 1000;
244
System.out.println(DEPARTMENT + "average salary:" + salary);
}
}
This will produce the following result −
Output
Development average salary:1000
Instance Variables
• Instance variables are declared in a class, but outside a method, constructor or any block.
• When a space is allocated for an object in the heap, a slot for each instance variable value is
created.
• Instance variables are created when an object is created with the use of the keyword 'new'
and destroyed when the object is destroyed.
• Instance variables hold values that must be referenced by more than one method, constructor
or block, or essential parts of an object's state that must be present throughout the class.
• Instance variables can be declared in class level before or after use.
• Access modifiers can be given for instance variables.
• The instance variables are visible for all methods, constructors and block in the class.
Normally, it is recommended to make these variables private (access level). However,
visibility for subclasses can be given for these variables with the use of access modifiers.
• Instance variables have default values. For numbers, the default value is 0, for Booleans it is
false, and for object references it is null. Values can be assigned during the declaration or
within the constructor.
• Instance variables can be accessed directly by calling the variable name inside the class.
However, within static methods (when instance variables are given accessibility), they
should be called using the fully qualified name. ObjectReference.VariableName.
Example
import java.io.*;
public class Employee {
// this instance variable is visible for any child class.
public String name;
// salary variable is visible in Employee class only.
private double salary;
// The name variable is assigned in the constructor.
public Employee (String empName) {
name = empName;
}
Output
name : Ransika
salary :1000.0
Constants
Constants are values that do not change during program execution.
Integer Constants
Integer Constants refers to a Sequence of digits which Includes only negative or positive Values and
many other things those are as follows
• An Integer Constant must have at Least one Digit.
• it must not have a Decimal value.
• it could be either positive or Negative.
• if no sign is Specified then it should be treated as Positive.
• No Spaces and Commas are allowed in Name.
Examples: 23. -5600
Real Constants
• A Real Constant must have at Least one Digit.
• it must have a Decimal value.
• it could be either positive or Negative.
• if no sign is Specified then it should be treated as Positive.
• No Spaces and Commas are allowed in Name.
Examples: -76.34,-3
246
String Constants
● String is a Sequence of Characters Enclosed between double Quotes These Characters may
be digits , Alphabets Like “Hello” , “1234” etc.
Here are three concrete examples which assign values to three different variables with different data
types
myByte = 127;
myFloat = 199.99;
myString = "This is a text";
The first line assigns the byte value 127 to the byte variable named myByte. The second line assigns
the floating point value 199.99 to the floating point variable named myFloat. The third line assigns
the String value (text) this is a text to the String variable named myString.
You can also assign a value to a variable already when it is declared. Here is how that is done:
byte myByte = 127;
float myFloat = 199.99;
String myString = "string value";
Variable Reading
● You can read the value of a Java variable by writing its name anywhere a variable or
constant variable can be used in the code.
● For instance, as the right side of a variable assignment, as parameter to a method call, or
inside a arithmetic expression. For instance:
float myFloat1 = 199.99;
float myFloat2 = myFloat1; // right hand side value in assignment
float myFloat3 = myFloat2 + 123.45; // as part of arithmetic expression
System.out.println(myFloat3); // as parameter in method call.
Variable arithmetic
● We can use arithmetic operators to perform calculations with values in programs.
Arithmetic operators are used in mathematical expressions in the same way that they are
used in algebra.
● A value used on either side of an operator is called an operand. For example, in below
statement the expression 47 + 3, the numbers 47 and 3 are operands.
● The arithmetic operators are examples of binary operators because they require two
operands. The operands of the arithmetic operators must be of a numeric type. You cannot
247
use them on Boolean types, but you can use them on char types, since the char type in Java
is, essentially, a subset of int.
Examples
Example 1: Java Program to perform an operation - Calculating Area of a circle
Java program to calculate or to print area of a circle in a simple method
import java.util.Scanner;
class AreaOfCircle
{
public static void main(String args[])
{
Output:
Enter the radius :
7
Area of circle : 154.0
248
Step – 1:
import java.util.Scanner;
( Here ‘import’ is a keyword in java used to get features from inbuilt packages. here we using a
package called until it consists of many classes and we using one of the class Scanner to get
command over console which is the interface between user and program. )
Step – 2:
public static void main(Stringargs[])
( The main function, where the execution of program start from here onwards )
Step – 3:
Scanner s= new Scanner(System.in);
(scanner is a class used to scan the input data which was given by the user through a console.
so to get access on a console we want to create an object Syntax:new Scanner(); after creating an
object that reference will store in variable ‘s’ )
Step – 4:
System.out.println("Enter theradius:");
( above code is giving instructions for the user to give the input for radius)
Step – 5:
double r= s.nextDouble();
( here above instruction is get input in the required format. first we want to know about
nextDouble() method it takes a token(collection of symbols divide by white space example:”ABC”,
“DEF” , “GHI”,”10″,”20″) which is given by user.
When user give 10 as input actually in user perspective it is number but any number or string
which entered on console by default those are strings (1o as string) but we want 10 as number
format for that we have method to convert string to number(Int, Double, Float, Long…..)
Let’s say an amount of $2,000 is deposited into a bank account as a fixed deposit at an annual
interest rate of 8%, compounded monthly, the compound interest after 5 years would be:
● P = 2000.
● R = 8/100 = 0.08 (decimal).
● n = 12.
● t = 5.
Conclusion
At the end of this learning outcome, the trainee should be able to explain Java data types, types of
statements, variables and constants and demonstrate data operations.
Further Reading
250
https://www.tutorialspoint.com/java/index.htm
5.3.4.3 Self-Assessment
Written Assessment
1. Java has ……...primitive data types.
a)9
b) 8
c) 7
d) 6
2. Which of the following is considered a platform independent code?
a) source code
b) Compiled code
Practical Assessment
1. Create a java program to calculate the circumference of a circle
.
5.3.4.4 Tools, Equipment, Supplies and Materials
251
• Computer
• JDK
• Stationery
• Instruction material
• Internet
5.3.4.5 References
252
5.3.5 Learning outcome 4: Use Control Statements
5.3.5.1 Learning Activities
Introduction
This learning outcome covers using control statements. It entails explaining java control
structures, use of different control statements and creating a program using control statements.
The statements which breaks the normal sequential flow of the program are called control
statements.
Branching statements
Branching statements are used to jump from the current executing loop.
● break
● continue
}
Output:
a is greater than b
Here the value of a is greater than the value of b, thus the statement ‘a is greater than b is
printed. Deciding whether to execute the statement(s) or not, depends upon the condition
specified. Hence it is called as decision making statement.
3. If then else
If then else statement provides two paths. The if block is executed when the condition holds true.
When the condition evaluates to false, the statements inside the else block are executed.
if(condition)
{ //statements, when condition is true
}
else
{
//statements, when condition is false
254
}
Example:
class Great{
public static void main(String args[]){
int a = 10, b = 5;
if(a>b)
{
System.out.println(“a is greater than b”);
}
else
{
System.out.println(“b is greater than a”);
Output:
b is greater than a
In the above program, the statement inside the else block is executed since the
condition a>b evaluates to false.
In the above program, the statement inside the else block is not executed since the
condition a>b evaluates to false.
4. Switch statement
‘switch’ statement can have multiple execution paths. It is similar to that of ‘if else-if’ statement
except that switch can handle expressions which results to any primitive data type and if
statements handle only boolean expressions.
Syntax:
switch (expression)
{
case ‘value1’:
//statements
break;
case ‘value2’:
//statements
break;
case ‘value3’:
//statements
break;
255
…
default:
//statements
}
The value of the expression is matched with the case values. Only the statements inside the
matched case are executed.
The ‘break’ keyword is added after each case in order to exit from the switch case. If the ‘break’
keyword is not specified, all the cases would be checked and the matching cases would be executed.
Example:
class Number{
public static void main(String args[]){
int n =2;
switch (n)
{case 1:
System.out.println(“One”);
break;
case 2:
System.out.println(“Two”);
break;
case 3:
System.out.println(“Three”);
break;
case 4:
System.out.println(“Four”);
break;
case 5:
System.out.println(“Five”);
break;
default:
System.out.println(“Enter a number within 1 to 5”);
}
}
Output:
TWO
In the above program the value of n decides which statement to be executed. Here it is 2 and hence
the statement inside the case 2 is executed.
256
Looping statements
For
For loop executes a set of statements repeatedly until a specified condition evaluates to false.
Syntax:
For loop has 3 parts
i) Initialization
Executes once, initializes the loop variable which causes the loop to iterate
ii) Condition
the expression which evaluates to true / false. When this condition becomes false, the loop is
terminated.
iii) increment/decrement
Executes at every iteration of the loop, causes the loop variable either to increment or
decrement
Syntax:
for (initialization; condition; increment/decrement)
{
//statements to be repeated
}
Example:
for(int i = 0; i < 5; i++)
{ System.out.println(“Number”+i);
}
Output:
Number:0
Number:1
Number:2
Number:3
Number:4
Note: The 3 parts of the ‘for’ loop can be made optional if necessary. Without them, it becomes an
infinite loop.
While
While loop executes a set of statements repeatedly until a given condition remains true.
257
Syntax:
while(condition)
{ //statements
}
Example:
int i = 5;
while ( i != 0 )
{
System.out.println(“value:”+i);
--i;
Output:
value:5
value:4
value:3
value:2
Value:1
In the above program, the value of i is printed until it is not equal to zero. When the value of i
reaches 0, the execution of the loop is terminated.
do while
Do while loop is similar to that of the while loop except that the condition is evaluated at the end
of the loop in do-while whereas in while loop, it is evaluated before entering into the loop.
Syntax:
do
{
//statements
}while(condition)
The statements given inside the ‘do’ block are executed at least once regardless of the condition.
Example:
int i = 0;
do
{
System.out.println(“value:”+i);
i++;
} while (i<6)
Output:
258
Value: 0
Value: 1
Value: 2
Value: 3
Value: 4
Value: 5
Branching statements
break
When a program executes a break statement, then the loop (for/switch/while/do while) which contains
the break statement is terminated. The flow of the execution jumps to the outside of the loop.
Example:
class Find{
public static void main(String args[]) {
int arr[] = {1,2,3,4,5,6,7};
boolean found = false;
for(int i = 0; i<arr.length; i++)
{ if(arr[i]== 5)
{ found = true;
break;
}
}
if(found)
{System.out.println(“5 is found”);
}
Output:
5 is found
In the above program the for loop iterates over the elements of the array ‘arr’. When the element 5
is present in the array, then a boolean flag ‘found’ is set to true and immediately the for loop is
terminated. Thus the next if block followed by the for loop is executed.
The difference between the labelled and unlabeled break is that, unlabeled break terminates the
innermost switch, for, while, do while loop which contains the break statement and labeled break
terminates the outer loop which is labeled.
259
Example:
Consider the same example searching an element over a two dimensional array.
class Find{
public static void main(String args[]) {
int arr[][] = {{1,2,3},{4,5,6,}};
boolean found = false;
find:
for(int i = 0; i<arr.length; i++)
{ for(int j=0; j<arr[i].length;j++)
if(arr[i][j] == 5)
{ found = true;
break find; //terminates outer for loop
}
}
if(found)
{System.out.println(“5 is found”);
}
}
Output
5 is found
In this case, the break statement terminates the outermost ‘for’ loop which is labeled.
Continue
Continue statement skips the current iteration of the loop and evaluates the loop’s condition for the
next iteration. Rest of the statements of the loop after the continue statement is not executed and the
next iteration is followed.
The difference between break and continue is that continue statement breaks the current iteration of
the loop whereas break statement terminates the loop itself.
Example:
public class ContinueExample {
public static void main(String a[]){
for(int i=1;i<=10;i++){
if(i%2 == 0){
continue;
}
System.out.println(i);
}
}
260
}
Output
1
3
5
7
9
In the above program, whenever the value of i is divisible by 2 (even number) the current
iteration is ignored printing just the odd numbers alone.
Conclusion
At the end of this learning outcome, the trainee should be able to explain control statements
explained, demonstrate different control statements and create programs using statements.
Further Reading
Written Assessment
1. Which of these are selection statements in Java?
a) if()
b) for()
c) continue
d) break
2. Which of the following loops will execute the body of loop even when condition controlling
the loop is initially false?
a) do-while
b) while
c) for
d) none of the mentioned
3. Which of these jump statements can skip processing the remainder of the code in its body
for a particular iteration?
a) break
b) return
c) exit
261
d) continue
4. Which of this statement is incorrect?
a) switch statement is more efficient than a set of nested ifs
b) two case constants in the same switch can have identical values
c) switch statement can only test for equality, whereas if statement can evaluate any type of
boolean expression
d) it is possible to create a nested switch statements
5. Which of these selection statements test only for equality?
a) if
b) switch
c) if & switch
d) none of the mentioned
Oral Assessment
1. What are the common java looping statements?
2. What do you understand by branching statements?
3. What are java decision making statements? Give examples
4. In what situation can the if then else statement be used?
Practical Assessment
1. Create a java program using the following decision making controls
• if then - to display whether a person is an adult or not depending on the age
• switch – To display a message informing the user the number/she has entered e.g.
“Nine” upon entering the number 9 when prompted in the program.
2. Create a java program using both the for and the while loops to display odd numbers from
20 to 10 in descending order.
5.3.5.4 Tools, Equipment, Supplies and Materials
• Computer
• JDK
• Stationery
• Instruction material
• Internet
5.3.5.5 References
https://www.edureka.co/blog/control-statements-in-java/
262
5.3.6 Learning Outcome 5: Use Methods
5.3.6.1 Learning Activities
Learning Outcome No. 5: Use Methods Special Instructions
Introduction
This learning outcome covers using methods. It entails explaining java procedures/methods/
functions, demonstrating methods and creating programs using methods.
Java Methods
Definition
A Java method is a collection of statements that are grouped together to perform an operation.
When you call the System.out.println() method, for example, the system actually executes several
statements in order to display a message on the console.
Structure of a method
Syntax: Method definition consists of a method header and a method body.
modifier returnType nameOfMethod (Parameter List) {
// method body
}
• modifier − It defines the access type of the method and it is optional to use.
• returnType − Method may return a value.
• nameOfMethod − This is the method name. The method signature consists of the method
name and the parameter list.
• Parameter List − The list of parameters, it is the type, order, and number of parameters of a
method. These are optional, method may contain zero parameters.
• method body − The method body defines what the method does with the statements.
Example:
public static int methodName(int a, int b) {
263
// body
}
Here,
• public static − modifier
• int − return type
• methodName − name of the method
• a, b − formal parameters
• int a, int b − list of parameters
Method calling
To use or apply a method, it should be called. There are two ways in which a method is called i.e.
method returns a value or returning nothing (no return value).
When a program invokes a method, the program control gets transferred to the called method.
This called method then returns control to the caller in two conditions, when −
o the return statement is executed.
o it reaches the method ending closing brace.
Program Example:
public class ExampleMinNumber {
public static void main(String[] args) {
int a = 11;
int b = 6;
int c = minFunction(a, b);
264
System.out.println("Minimum Value = " + c);
}
Output:
Minimum value = 6
Void keyword
The void keyword allows us to create methods which do not return a value. Here, in the following
example we're considering a void method methodRankPoints. This method is a void method,
which does not return any value.
Program Example:
public class ExampleVoid {
public static void main(String[] args) {
methodRankPoints(255.7);
}
265
Passing parameters by value
During a method call, arguments should be passed in the same order as their respective
parameters in the method specification. Parameters can be passed by value or by reference.
Passing Parameters by Value means calling a method with a parameter. Through this, the
argument value is passed to the parameter.
Example:
The following program shows an example of passing parameter by value. The values of the
arguments remain the same even after the method invocation.
Method overloading
266
When a class has two or more methods by the same name but different parameters, it is known as
method overloading. It is different from overriding. In overriding, a method has the same method
name, type, number of parameters, etc.
Let’s consider the example discussed earlier for finding minimum numbers of integer type. If,
let’s say we want to find the minimum number of double type. Then the concept of overloading
will be introduced to create two or more methods with the same name but different parameters.
// for integer
public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
// for double
public static double minFunction(double n1, double n2) {
double min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
267
}
Output
Minimum Value = 6
Minimum Value = 7.3
“this” keyword
“this” is a keyword in Java which is used as a reference to the object of the current class, with in
an instance method or a constructor. Using this you can refer the members of a class such as
constructors, variables and methods.
Note − The keyword this is used only within instance methods or constructors
In general, the keyword this is used to differentiate the instance variables from local variables if
they have same names, within a constructor or a method.
Example:
Here is an example that uses this keyword to access the members of a class
268
}
public static void main(String[] args) {
// Instantiating the class
This_Example obj1 = new This_Example();
// Invoking the print method
obj1.print();
// Passing a new value to the num variable through parametrized constructor
This_Example obj2 = new This_Example(30);
// Invoking the print method again
obj2.print();
}
}
Output
This is an example program on keyword this
value of local variable num is : 20
value of instance variable num is : 10
Hi Welcome to Java tutorial
This is an example program on keyword this
value of local variable num is : 20
value of instance variable num is : 30
Hi Welcome to Java tutorial
Variable arguments
JDK 1.5 enables you to pass a variable number of arguments of the same type to a method. The
parameter in the method is declared as follows
typeName... parameterName
In the method declaration, you specify the type followed by an ellipsis (...). Only one variable-
length parameter may be specified in a method, and this parameter must be the last parameter.
Any regular parameters must precede it.
Example:
public class VarargsDemo {
public static void main(String args[]) {
// Call method with variable args
printMax(34, 3, 3, 2, 56.5);
printMax(new double[]{1, 2, 3});
}
public static void printMax( double... numbers) {
if (numbers.length == 0) {
System.out.println("No argument passed");
return;
269
}
double result = numbers[0];
for (int i = 1; i < numbers.length; i++)
if (numbers[i] > result)
result = numbers[i];
System.out.println("The max value is " + result);
}
}
Output:
The max value is 56.5
The max value is 3.0
Conclusion
At the end of this learning outcome, the trainee should be able to explain
methods/procedures/functions, demonstrate methods and create programs using methods.
Further Reading
5.3.6.3 Self-Assessment
Written Assessment
1. What is the process of defining more than one method in a class differentiated by method
signature?
a) Function overriding
b) Function overloading
c) Function doubling
d) None of the mentioned
2. Which of the following is a method having same name as that of its class?
a) finalize
b) delete
c) class
d) constructor
3. Which method can be defined only once in a program?
a) main method
b) finalize method
c) static method
d) private method
270
4. Which of this statement is incorrect?
a) All object of a class are allotted memory for the all the variables defined in the class
b) If a function is defined public it can be accessed by object of other class by inheritation
c) main() method must be made public
d) All object of a class are allotted memory for the methods defined in the class
5. What is the return type of a method that does not return any value?
a) int
b) float
c) void
d) double
Oral Assessment
1. What do you understand by java methods?
2. Which is the best way to call a java method in a java program?
3. What is method overloading?
4. What do you understand by the keyword void?
Practical Assessment
1. Create a java method ComputeInterest that calculate and returns the simple interest I
earned from a principal amount P at a rate R over a period of time N (years)
2. Write a program that calls the above method using user entered parameters for principal,
rate and time and displays the Interest earned.
5.3.6.4 Tools, Equipment, Supplies and Materials
• Computer
• JDK
• Stationery
• Instruction material
• Internet
5.3.6.5 References
271
5.3.7 Learning Outcome 6: Understand Object Oriented Programming
5.3.7.1 Learning Activities
Learning Outcome No. 6: Understand Object Special Instructions
Oriented Programming
Introduction
This learning outcome covers explaining the Object oriented programming concept, java classes
and objects. It also includes demonstrating classes, objects and inheritance and developing
inheritance programs.
Object
272
Any entity that has state and behavior is known as an object. For example, a chair, pen, table,
keyboard, bike, etc. It can be physical or logical.
An Object can be defined as an instance of a class. An object contains an address and takes up some
space in memory. Objects can communicate without knowing the details of each other's data or
code. The only necessary thing is the type of message accepted and the type of response returned by
the objects.
Example: A dog is an object because it has states like color, name, breed, etc. as well as behaviors
like wagging the tail, barking, eating, etc.
Inheritance
When one object acquires all the properties and behaviors of a parent object, it is known as
inheritance. It provides code reusability.
Polymorphism
If one task is performed in different ways, it is known as polymorphism. For example: to draw
something, for example, shape, triangle, rectangle, etc.
Another example can be to speak something; for example, a cat speaks meow, dog barks woof, etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example phone call,
we don't know the internal processing.
In Java, we use abstract class and interface to achieve abstraction.
Encapsulation
Binding (or wrapping) code and data together into a single unit are known as encapsulation. For
example, a capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class because all
the data members are private here.
Creating Classes
A class consists of attributes and methods
Declaring attributes
Attribute An attribute is another term for a field. It’s typically a public field that can be accessed
directly.
Example:
Class called “MyClass” with two attributes: x and y:
273
public class MyClass {
int x = 5;
int y = 3;
}
Creating Methods
As explained earlier, A Java method is a collection of statements that are grouped together to perform
an operation. Methods in a class are usually declared as public in order for them to be accessed by
objects from outside the class (within the main function).
Example: The following class defines three variables and one method called Findvolume:
class Box{
double width;
double height;
double depth;
//Findvolume method
public void Findvolume(){
System.out.println("Volume is " + width*height*depth);
}
}
Creating objects
A class provides the blueprints for objects. So basically, an object is created from a class. In Java,
the new keyword is used to create new objects.
Example:
To use the above class, we must create an object of its type. The following program does that and
then uses the class variables and the method defined in the class.
class BoxDemo{
public static void main(String[] args){
Box myBox=new Box();
//assign values
myBox.width=10; //call the variables
myBox.height=20;
myBox.depth=15;
//display volume
myBox.Findvolume(); //call the method
}
}
Inheritance
Inheritance can be defined as the process where one class acquires the properties (methods and fields)
of another. With the use of inheritance the information is made manageable in a hierarchical order.
The class which inherits the properties of other is known as subclass (derived class, child class) and
the class whose properties are inherited is known as superclass (base class, parent class).
extends Keyword
extends is the keyword used to inherit the properties of a class.
Syntax
class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}
Example 1: My_Calculation.java
Following is an example demonstrating Java inheritance. In this example, you can observe two classes
namely Calculation and My_Calculation.
275
Using extends keyword, the My_Calculation inherits the methods addition() and Subtraction() of
Calculation class.
class Calculation {
int z;
public void addition(int x, int y) {
z = x + y;
System.out.println("The sum of the given numbers:"+z);
}
Output:
The sum of the given numbers:30
The difference between the given numbers:10
The product of the given numbers:200
In the given program, when an object to My_Calculation class is created, a copy of the contents
of the superclass is made within it. That is why, using the object of the subclass you can access the
members of a superclass.
276
The Superclass reference variable can hold the subclass object, but using that variable you can
access only the members of the superclass, so to access the members of both classes it is
recommended to always create reference variable to the subclass.
If you consider the above program, you can instantiate the class as given below. But using the
superclass reference variable ( cal in this case) you cannot call the method multiplication(), which
belongs to the subclass My_Calculation.
Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);
Note − A subclass inherits all the members (fields, methods, and nested
classes) from its superclass. Constructors are not members, so they are not
inherited by subclasses, but the constructor of the superclass can be invoked
from the subclass.
Example 2: Car.java
class Vehicle {
protected String brand = "Ford"; // Vehicle attribute
public void honk() { // Vehicle method
System.out.println("Tuut, tuut!");
}
}
Further Reading
277
Schildt, H(2019 ) . Java A Beginner’s Guide (8th ed.). McGraw-Hill Education
5.3.7.4 Self Assessment
Written Assessment
1. What is the difference between a class and an object?
2. What is the meaning of polymorphism
3. How are the concepts of encapsulation and a class related?
4. Why is the OOP style popular?
5. What is the key advantage of the inheritance concept?
Oral Assessment
• Describe how the inheritance concept can be used to easily capture data of different
categories of employees in an organisation.
Practical Assessment
1. Create a class Circle that has radius as the attribute and also contains a method to
ComputeArea to calculate the areas of a circle
2. Implement the above class in a program that you can test.
278
CHAPTER 6: DATABASE MANAGEMENT SKILLS
6.1 Introduction
This unit covers the competencies required to demonstrate database management skills. It involves
understanding database fundamentals, designing a database, using Structured Query Language,
understanding the design of object oriented databases, understanding indexing and hashing and
understanding database applications.
279
6.3.2 Learning Outcome 1: Understand database fundamentals
6.3.2.1 Learning Activities
Learning Outcome 1: Understand database fundamentals
Learning Activities Special Instructions
This learning outcome covers the definition of database, relational model and other terminologies
used in databases. It also explains the reasons for using databases, key concepts in relational
modelling, properties of tables and the MS SQL server interface. It also involves comparing relational
database management systems, demonstrating MS SQL server installation and explaining MS SQL
server database properties.
Database
A Database is a collection of related data organised in a way that data can be easily accessed,
managed and updated. Database can be software based or hardware based, with one sole purpose,
storing data
280
Database terminologies
✓ Table
A database table is composed of records and fields that hold data. Tables are also called datasheets.
Each table in a database holds data about a different, but related, subject.
✓ Database engine
A database engine (or storage engine) is the underlying software component that a database
management system (DBMS) uses to create, read, update and delete (CRUD) data from a database.
... The term "database engine" is frequently used interchangeably with "database server" or
"database management system".
✓ Records
Data is stored in records. A record is composed of fields and contains all the data about one
particular person, company, or item in a database. In this database, a record contains the data for
one customer support incident report. Records appear as rows in the database table. A record for
Log ID 1201242 is highlighted in below.
✓ Field
A field is part of a record and contains a single piece of data for the subject of the record. In the
database table illustrated in Figure below, each record contains four fields:
Log ID A number assigned to this customer support incident for
identification purposes
Operator The code for the customer support operator who handled
this incident
Resolved A check box to indicate whether the incident was resolved
Duration The time in seconds the operator spent on this incident
281
Fields appear as columns in a database table. Data from the Log ID field for five records is
highlighted in the Figure below.
Accurate
A database is pretty accurate as it has all sorts of build in constraints, checks etc. This means
that the information available in a database is guaranteed to be correct in most cases.
Security of data
Databases have various methods to ensure security of data. There are user logins required
before accessing a database and various access specifiers. These allow only authorised users
to access the database.
Data integrity
This is ensured in databases by using various constraints for data. Data integrity in databases
makes sure that the data is accurate and consistent in a database.
282
redundancy is controlled by application programming and kept to minimum by introducing
as little redundancy as possible when designing the database.
Data sharing
The integration of all the data, for an organization, within a database system has many
advantages. First, it allows for data sharing among employees and others who have access to the
system. Second, it gives users the ability to generate more information from a given amount of
data than would be possible without the integration.
Data independence
Another advantage of a database management system is how it allows for data independence. In
other words, the system data descriptions or data describing data (metadata) are separated from
the application programs. This is possible because changes to the data structure are handled by
the database management system and are not embedded in the program itself.
Relational model
The relational model represents the database as a collection of relations. A relation is
nothing but a table of values. In this model, data is organised in two-dimensional tables and
the relationship is maintained by storing a common field.
.
283
✓ Relations/tables
A relational database system contains one or more objects called tables or relations. The data or
information for the database are stored in these tables. Tables are uniquely identified by their names
and are comprised of columns and rows. Columns contain the column name, data type, and any
other attributes for the column. Rows contain the records or data for the columns. Here is a sample
table called "weather". City, state, high, and low are the columns. The rows contain the data for
this table:
Weather
city state high low
Phoenix Arizona 105 90
Tucson Arizona 101 92
Flagstaff Arizona 88 69
San Diego California 77 60
New
Albuquerque 80 72
Mexico
Table Weather
✓ Attributes/Columns
Each named column in a Table is an attribute. Attributes are the properties which define a relation.
e.g., Student_Rollno, NAME, etc.
✓ Domain
A domain is the original sets of atomic values used to model data. By atomic value, we mean that
each value in the domain is indivisible as far as the relational model is concerned. For example:
• The domain of Marital Status has a set of possibilities: Married, Single, Divorced.
• The domain of Shift has the set of all possible days: {Mon, Tue, Wed…}.
• The domain of Salary is the set of all floating-point numbers greater than 0 and less than
200,000.
• The domain of First Name is the set of character strings that represents names of people.
In summary, a domain is a set of acceptable values that a column is allowed to contain. This is
based on various properties and the data type for the column. We will discuss data types in another
chapter.
✓ Tuples/Rows
A row—also called a tuple—represents a single, implicitly structured data item in a table. Each
row in a table represents a set of related data, and every row in the table has the same structure.
✓ Primary Key
284
A primary key is a field in a table which uniquely identifies each row/record in a database table.
Primary keys must contain unique values. A primary key column cannot have NULL values. A
table can have only one primary key, which may consist of single or multiple fields.
.
Example:
Employee ID FirstName LastName
11 Andrew Johnson
22 Tom Wood
33 Alex Hale
Demonstration of a Primary Key
"Persons" table:
Persons table
PersonID LastName FirstName Age
1 Hansen Ola 30
2 Svendson Tove 23
3 Pettersen Kari 20
"Orders" table:
Orders table
OrderID OrderNumber PersonID
1 77895 3
2 44678 3
3 22456 2
4 24562 1
• Notice that the "PersonID" column in the "Orders" table points to the "PersonID" column in
the "Persons" table.
• The "PersonID" column in the "Persons" table is the PRIMARY KEY in the "Persons"
table.
• The "PersonID" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.
• The FOREIGN KEY constraint is used to prevent actions that would destroy links between
tables.
• The FOREIGN KEY constraint also prevents invalid data from being inserted into the
foreign key column, because it has to be one of the values contained in the table it points to.
285
Properties of a relation/table
286
✓ Oracle
Oracle Corporation owns Oracle Database, and the code is not open sourced.
Oracle DB is for large applications, particularly in the banking industry. Most of the world’s top
banks run Oracle applications because Oracle offers a powerful combination of technology and
comprehensive, pre-integrated business applications, including essential functionality built
specifically for banks.
The main disadvantage of using Oracle is that it is not free to use like its open source competitors
and can be quite expensive.
✓ MS SQL server
Microsoft owns SQL Server. Like Oracle DB, the code is close sourced. Large enterprise
applications mostly use SQL Server.
Microsoft offers a free entry-level version called Express but can become very expensive as you
scale your application.
✓ My SQL
MySQL is the most popular open source SQL database. It is typically used for web application
development, and often accessed using PHP.
The main advantages of MySQL are that it is easy to use, inexpensive, reliable (has been around
since 1995), and has a large community of developers who can help answer questions.
Some of the disadvantages are that it has been known to suffer from poor performance when
scaling, open source development has lagged since Oracle has taken control of MySQL, and it does
not include some advanced features that developers may be used to
.
✓ Ms Access
Microsoft Access is a Database Management System offered by Microsoft. It uses the Microsoft Jet
Database Engine and comes as a part of the Microsoft Office suite of application.
Microsoft Access offers the functionality of a database and the programming capabilities to create
easy to navigate screens (forms)
Editions and features: Review the supported features for the different editions and versions of
SQL Server to determine which best suits your business needs.
• SQL Server 2019 (15.x).
• SQL Server 2017 (14.x).
• SQL Server 2016 (13.x).
287
• SQL Server 2014 (12.x)
Requirements: Review installation requirements, system configuration checks, and security
considerations in Planning a SQL Server Installation
1. The installer asks you to select the installation type, choose the Custom installation type allows
you to step through the SQL Server installation wizard and select the features that you want to
install.
2. Specify the folder for storing the installation files that the installer will download, then click the
Install button.
288
3. The installer starts downloading the install package for a while.
4. Once the download completes, open the folder that stores the install package and double-click the
SETUP.exe file.
5. The following window displays; select the installation option on the left.
289
6. Click the first link to launch a wizard to install SQL Server 2017.
7. Specify the edition that you want to install, select Developer edition and click the Next button.
290
8. Select the “I accept the license terms.” and click the Next button.
9. Check the “Use Microsoft Update to check for updates (recommended)” to get the security and
other important updates for the SQL Server and click the Next button.
291
10. The installation checks for the prerequisites before installation. If no error found, click the Next
button.
11. Select the features that you want to install. For now, you just need the Database Engine
Services, just check the checkbox and click the Next button to continue
292
12. Specify the name and install ID for the instance of the SQL Server and click the Next button.
13. Specify the service account and collation configuration. Just use the default configuration and
click the Next button.
293
14. Specify the database engine security mode. First, choose Mixed Mode. Next, enter the password
for the SQL Server system administrator (sa) account. Then, re-enter the same password to confirm
it. After that, click the Add Current User button. Finally, click the Next button.
294
16. The installer starts the installation process
295
17. Once it completes, the following window displays. Click the OK button.
296
Install Microsoft SQL Server Management Studio
To interact with SQL Servers, you need to install SQL Server Management Studio (SSMS). The
SQL Server Management Studio is a software for querying, designing, and managing SQL Server
on your local computer or in the cloud. It provides you with tools to configure, monitor, and
administer SQL Server instances.
First, download the SSMS from the Microsoft website via the following link:
Download SQL Server Management Studio
2. Wait for few minutes while the installer sets up the software.
297
Now, you should have a SQL Server 2017 and SQL Server Management Studio installed on your
computer.
• Object Explorer (F8): Object Explorer is a tree view of all the database objects in a server.
This view includes the databases of the SQL Server Database Engine, SQL Server Analysis
Services, SQL Server Reporting Services, and SQL Server Integration Services. Object
Explorer includes information for all servers that are connected to it.
298
• Query Window (Ctrl+N): After you select New Query, enter your Transact-SQL (T-SQL)
queries in this window. The results of your queries also appear here.
• Properties (F4): You can see the Properties view when the Query Window is open. The view
displays basic properties of the query. For example, it shows the time that a query started, the
number of rows returned, and connection details.
299
• Template Browser (Ctrl+Alt+T): Template Browser has various pre-built T-SQL templates.
You can use these templates to perform various functions, such as creating or backing up a
database.
• Object Explorer Details (F7): This view is more granular than the view in Object Explorer.
You can use Object Explorer Details to manipulate multiple objects at the same time. For
example, in this window, you can select multiple databases, and then either delete them or
script them out simultaneously.
300
Change the environment layout
This section describes how to change the environment layout, such as how to move various
windows.
• To move a window, press and hold the title, and then drag the window.
• To pin or unpin a window, select the pushpin icon in the title bar:
• Each window component has a drop-down menu that you can use to manipulate the window
in various ways:
301
• When two or more query windows are open, the windows can be tabbed vertically or
horizontally so that both query windows are visible. To view tabbed windows, right-click the
title of the query, and then select the tabbed option that you want:
•
302
o To merge the tabs, right-click the query title, and then select Move to Previous Tab
Group or Move to Next Tab Group:
• To restore the default environment layout, in the Window menu, select Reset Window
Layout:
303
Maximize Query Editor
You can maximize Query Editor to full-screen mode:
1. Click anywhere in the Query Editor window.
2. Press Shift+Alt+Enter to toggle between full-screen mode and regular mode.
This keyboard shortcut works with any document window.
304
Change the font
• To change the font, select Tools > Options > Fonts and Colors:
305
Reset settings to the default
• You can export and import all these settings from the menu. To import or export settings, or
to restore default settings, select Tools > Import and Export Settings
Conclusion
At the end of this learning outcome, the learner should be able to define of database, relational model
and other terminologies used in databases. The learner should also be able to explain the reasons for
using databases, key concepts in relational modelling, properties of tables and the MS SQL server
interface. In addition, a learner should be able to compare relational database management systems,
demonstration of MS SQL server installation and explanation of MS SQL server database properties
should be one.
Further Reading
1. Elmasri, R., & Navathe, S. B. (2011). Database systems (Vol. 9). Boston, MA: Pearson
Education.
2. Hoffer, J. A., Ramesh, V., & Topi, H. (2011). Modern database management. Upper Saddle
River, NJ: Prentice Hall,.
3. Rankins, R., Jensen, P., & Bertucci, P. (2002). Microsoft SQL Server 2000 Unleashed.
Sams Publishing.
4. Davidson, L. (2001). Professional SQL server 2000 database design. Birmingham, UK:
Wrox Press.
6.3.2.3 Self-Assessment
Written Assessment
307
4 The term attribute refers to a ___________ of a table.
a) Record
b) Column
c) Tuple
d) Key
5 For each attribute of a relation, there is a set of permitted values, called the ________ of that
attribute.
a) Domain
b) Relation
c) Set
d) Schema
6 Course(course_id,sec_id,semester)
Here the course_id,sec_id and semester are __________ and course is a _________
a) Relations, Attribute
b) Attributes, Relation
c) Tuple, Relation
d) Tuple, Attributes
7 A _____ is a property of the entire relation, rather than of the individual tuples in which each
tuple is unique.
a) Rows
b) Key
c) Attribute
d) Fields
8 Which one of the following attribute can be taken as a primary key?
a) Name
b) Street
c) Id
d) Department
9 Which one of the following cannot be taken as a primary key?
a) Id
b) Register number
c) Dept_id
d) Street
10 Which language can a user request information from a database with?
a) Query
b) Relational
c) Structural
d) Compiler
11 Student(ID, name, dept name, tot_cred)
In this statement which attributes form the primary key?
a) Name
b) Dept
308
c) Tot_cred
d) ID
12 Database __________ which is the logical design of the database, and the database _______
which is a snapshot of the data in the database at a given instant in time.
a) Instance, Schema
b) Relation, Schema
c) Relation, Domain
d) Schema, Instance
Oral Assessment
Practical Assesssment
6.3.2.5 References
1. https://www.guru99.com/dbms-tutorial.html
2. https://www.cengage.com/school/corpview/RegularFeatures/DatabaseTutorial/db_elements/db_
elements2.htm
3. https://www.cs.wcupa.edu/~zjiang/RDB_table.htm(Retrieved on 2nd March 2020)
309
6.3.3 Learning Outcome 2: Design a database
6.3.2.1 Learning Activities
Learning Outcome No.2: Design a Database
·
3.1.1.1 Information Sheet No 6/LO2: Design a Database
Introduction
This learning outcome covers explanation of the phases of database design, illustration of
entity modelling, entity model design and validation of the ER model.
Conceptual database design is the process of constructing a model of the data used in an enterprise,
independent of all physical considerations.
310
The conceptual database design phase starts with the formation of a conceptual data model of the
enterprise that is entirely independent of implementation details such as the target DBMS, use of
application programs, programming languages used, hardware platform, performance issues, or
any other physical deliberations.
The main aim of this model is to establish the entities, their attributes, and their relationships. In
this Data modeling level, there is hardly any detail available of the actual Database structure.
The 3 basic tenants of Data Model are
Entity: A real-world thing
Attribute: Characteristics or properties of an entity
Relationship: Dependency or association between two entities
For example:
• Customer and Product are two entities. Customer number and name are attributes of the
Customer entity
• Product name and price are attributes of product entity
• Sale is the relationship between the customer and product
311
• Consider the use of improved modeling concepts (optional step)
• Check model for redundancy
• Validate the conceptual model against user transactions
• Review the conceptual data model with user
The objective of logical database design methodology is to interpret the conceptual data model into
a logical data model and then authorize this model to check whether it is structurally correct and
able to support the required transactions or not.
Logical data models add further information to the conceptual model elements. It defines the
structure of the data elements and set the relationships between them.
The advantage of the Logical data model is to provide a foundation to form the base for the Physical
model. However, the modeling structure remains generic.
312
In this step of the database development life cycle, the main purpose is to translate the conceptual
data model created in conceptual methodology into a logical data model of the data requirements
of the enterprise. This objective can be achieved by following the activities given below:
• Obtain the relations for the logical data model
• Authorize those relations using normalization
• Validate those relations against user transactions
• Check integrity control and its limitation
• Evaluate the logical data model with user
• Combine logical data models into the global model (This step is an optional one)
• Check for future growth and development
The structure of the relational schema is authorized using normalization. It then makes sure to
ensure that the relations are capable of supporting the transactions given in the users' requirements
specification. You can then check those all-important integrity constraints that are characterized by
the logical data model. At this stage, the logical data model is authorized by the users to ensure that
they consider the model to be a true demonstration of the data requirements for the enterprise.
Physical database design is the process of producing a description of the implementation of the
database on secondary storage; it describes the base relations, file organizations, and indexes used
to achieve efficient access to the data, and any associated integrity constraints and security measures.
It offers an abstraction of the database and helps generate schema. This is because of the richness of
meta-data offered by a Physical Data Model.
This type of Data model also helps to visualize database structure. It helps to model database
columns keys, constraints, indexes, triggers, and other RDBMS features.
Example of Entities:
314
A university may have some departments. All these departments employ various lecturers and offer
several programs.
Some courses make up each program. Students register in a particular program and enroll in various
courses. A lecturer from the specific department takes each course, and each lecturer teaches a
various group of students.
b) Attributes
Attributes
c) Relationships
Relationship is nothing but an association among two or more entities. E.g., Tom works in the
Chemistry department.
Entities take part in relationships. We can often identify relationships with verbs or verb phrases.
For example:
• You are attending this lecture
• I am giving the lecture
• Just like entities, we can classify relationships according to relationship-types:
• A student attends a lecture
• A lecturer is giving a lecture.
❑ Designing an Entity Model using UML (Unified Modelling Language)
316
Figure 71: Elements in ER diagrams
There are three basic elements in an ER Diagram: entity, attribute, relationship. There are more
elements which are based on the main elements. They are weak entity, multi valued attribute,
derived attribute, weak relationship, and recursive relationship. Cardinality and ordinality are two
other notations used in ER diagrams to further define relationships
How to Draw ER Diagrams
Below points show how to go about creating an ER diagram.
1. Identify all the entities in the system. An entity should appear only once in a particular
diagram. Create rectangles for all entities and name them properly.
2. Identify relationships between entities. Connect them using a line and add a diamond in
the middle describing the relationship.
3. Add attributes for entities. Give meaningful attribute names so they can be understood
easily.
Sounds simple right? In a complex system, it can be a nightmare to identify relationships. This is
something you’ll perfect only with practice.
ER Diagram Best Practices
1. Provide a precise and appropriate name for each entity, attribute, and relationship in the
diagram. Terms that are simple and familiar always beats vague, technical-sounding words.
In naming entities, remember to use singular nouns. However, adjectives may be used to
distinguish entities belonging to the same class (part-time employee and full-time employee,
for example). Meanwhile attribute names must be meaningful, unique, system-independent,
and easily understandable.
2. Remove vague, redundant or unnecessary relationships between entities.
3. Never connect a relationship to another relationship.
4. Make effective use of colors. You can use colors to classify similar entities or to highlight
key areas in your diagrams.
Worked Examples in ER Modelling
ER diagram of Branch Has Staff relationship
317
Has Entity relationship
Relationship Types
Degree of a Relationship
– Number of participating entities in relationship.
Relationship of degree:
– two is binary
– three is ternary
– four is quaternary.
Binary relationship called POwns
319
Figure 76:Entities associated through two distinct relationships with role names
Figure 77:ER diagram of Staff and Branch entities and their attributes
❑ Normalization
320
Database normalization is a database schema design technique, by which an existing schema is
modified to minimize redundancy and dependency of data.
b) Update Anomaly
In this case we have the same information in several rows. For instance if the office number
changes, then there are multiple updates that need to be made. If we don’t update all rows, then
inconsistencies appear.
c) Deletion Anomaly
Deletion of a row causes removal of more than one set of facts. For instance, if John Hunt retires,
then deleting that row cause us to lose information about the New York office.
Here you see Movies Rented column has multiple values. Now let's move into 1st Normal Forms:
321
• Each table cell should contain a single value.
• Each record needs to be unique.
The above table in 1NF-
1NF Example
322
Hence, we require both Full Name and Address to identify a record uniquely. That is a composite
key.
Let's move into second normal form 2NF
2NF (Second Normal Form) Rules
• Rule 1- Be in 1NF
• Rule 2- Single Column Primary Key
It is clear that we can't move forward to make our simple database in 2nd Normalization form unless
we partition the table above.
We have divided our 1NF table into two tables viz. Table 1 and Table2. Table 1 contains member
information. Table 2 contains information on movies rented.
We have introduced a new column called Membership_id which is the primary key for table 1.
Records can be uniquely identified in Table 1 using membership id
Database - Foreign Key
In Table 2, Membership ID is the Foreign Key
323
Foreign Key references the primary key of another Table. It
helps connect your Tables
• A foreign key can have a different name from its
primary key
• It ensures rows in one table have corresponding rows in
another
• Unlike the Primary key, they do not have to be unique.
Most often they aren't
• Foreign keys can be null even though primary keys can
not
324
The above problem can be overcome by declaring membership id fromTable2 as foreign key of
membership id from Table1
Now, if somebody tries to insert a value in the membership id field that does not exist in the parent
table, an error will be shown!
What are transitive functional dependencies?
A transitive functional dependency is when changing a non-key column, might cause any of the
other non-key columns to change
Consider the table 1. Changing the non-key column Full Name may change Salutation.
325
Table Salutation Introduced-Table 3
We have again divided our tables and created a new table which stores Salutations.
There are no transitive functional dependencies, and hence our table is in 3NF
In Table 3 Salutation ID is primary key, and in Table 1 Salutation ID is foreign to primary key in
Table 3
Now our little example is at a level that cannot further be decomposed to attain higher forms of
normalization. In fact, it is already in higher normalization forms. Separate efforts for moving into
next levels of normalizing data are normally needed in complex databases. However, we will be
discussing next levels of normalizations in brief in the following.
CRUD is an acronym that refers to the following actions on an object (typically a data entity):
• Create - to create and store new data
• Read - to retrieve and read data
• Update - to change or modify then store the data.
• Delete - to delete or remove the data
A CRUD matrix is a very useful way to capture and display activities and permissions within a
system. It is very valuable to combine a CRUD Matrix with the analysis of user processes within
the system, especially in the context of the actors and roles involved to complete the picture. The
analysis helps to identify the usage of entities and associated GUIs. The information that is used
heavily, and may therefore be a performance bottleneck, is also easily identified.
The simple example below illustrates how to capture this information. In this case what is shown
is what access or usage that a role has with a particular protected object (i.e., data entity, or activity,
etc.).
Crud Matrix A
326
In the following example, another way to capture this information, the protected objects are list
across the top, with permissions/usage define in each cell.
Object
Order Invoice Customer Employee Product
Role
Sales VP crud crud crud crud crud
Sales Manager crud crud ru r r
Sales Rep crud r ru r R
Stock Manager - - - r Ru
Note that "crude" appears, which is create; read; update; delete; and execute. Execute is added here,
indicating that a "Sale Manager" role can execute (fulfill) an Order.
Conclusion
At the end of this learning outcome, the leaner should be able to explain of the phases of database
design, illustrate entity modelling, entity model design and validate other ER model.
Further Reading
1. Batini, C., Ceri, S., & Navathe, S. B. (1992). Conceptual database design: an Entity-
relationship approach (Vol. 116). Redwood City, CA: Benjamin/Cummings.
2. Elmasri, R., & Navathe, S. B. (2011). Database systems (Vol. 9). Boston, MA: Pearson
Education.
3. Hoffer, J. A., Ramesh, V., & Topi, H. (2011). Modern database management. Upper Saddle
River, NJ: Prentice Hall,.
4. Rankins, R., Jensen, P., & Bertucci, P. (2002). Microsoft SQL Server 2000 Unleashed. Sams
Publishing.
6.3.3.3 Self-Assessment
Written Assessment
6. Entity is a _________
a) Object of relation
b) Present working model
c) Thing in real world
d) Model of relation
328
d) Primary key
9. Consider a directed line (->) from the relationship set advisor to both entity sets instructor
and student. This indicates _________ cardinality
a) One to many
b) One to one
c) Many to many
d) Many to one
10. We indicate roles in E-R diagrams by labeling the lines that connect ___________ to
__________
a) Diamond , diamond
b) Rectangle, diamond
c) Rectangle, rectangle
d) Diamond, rectangle
Oral Assessment
1. What is the difference between Primary and Unique Key
2. Explain any 3 symbols used in ER Modelling.
Practical Assessment
1. Model the relationship between Bank, Employees and Clients
2. Use ER diagram to describe a Weak Entity set
6.3.3.4 Tools, Equipment, Supplies and Materials
• Microsoft Office with MS Visio Modelling tool
• MS SQL server software
• Computers
• Instruction material
• Stationery
• Internet
6.3.3.5 References
1) Davidson, L. (2001). Professional SQL server 2000 database design. Birmingham, UK:
Wrox Press.
2) https://opentextbc.ca/dbdesign01/chapter/chapter-13-database-development-process
3) https://www.guru99.com/data-modelling-conceptual-logical.html
4) https://www.essentialsql.com/get-ready-to-learn-sql-database-normalization-explained-in-
simple-english/(Retrieved on 2nd March 2020
5) http://www.databaseanswers.org/data_migration/crud_matrix.htm
329
6.3.4 Learning Outcome 3: Use Structured Query Language (SQL)
6.3.4.1 Learning Activities
Learning Outcome No.3: Use Structured Query Language
Introduction
This learning outcome covers explaining SQL and data definition, creating tables using CREATE
TABLE constraints, using the ALTER TABLE AND DROP TABLE statements, demonstrating
data manipulation query statements, explaining joins and demonstrating types of joins and creating
and querying a database from validated ER model.
330
SQL in itself is non graphical but different industry players have come up with GUI’s to ease the
process of SQL use in relational database management.
The columns can range from one to a standard 1024 number of columns though other management
tools could allow for more.
The data types do not differ much with regular data types used in programming languages, e.g.
integer, varchar, date, datetime, timestamp, float, lately json among others.
331
SQL CREATE table constraints are set integrity conditions and rules to manage data in a table.
This is to ensure consistency, accuracy and reliability of data within a table. The constraints are
implemented on per column basis as shown in the syntax below:
CREATE TABLE table_name(
column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
column4 datatype constraint
);
NOT NULL – this ensures that a column cannot have a NULL value.
UNIQUE - Ensures that all values in a column are different.
PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each row
in a table.
FOREIGN KEY - Uniquely identifies a row/record in another table.
CHECK - Ensures that all values in a column satisfy a specific condition.
DEFAULT - Sets a default value for a column when no value is specified.
INDEX - Used to create and retrieve data from the database very quickly.
332
SQL SELECT Statement
The most commonly used SQL command is SELECT statement. The SQL SELECT statement is
used to query or retrieve data from a table in the database.
A query may retrieve information from specified columns or from all of the columns in the table.
To create a simple SQL SELECT Statement, you must specify the column(s) name and the table
name. The whole query is called SQL SELECT Statement.
For example, consider the table student_details. To select the first name of all the students the query
would be like:
• You can also retrieve data from more than one column. For example, to select first name
and last name of all the students.
333
NOTE: In a SQL SELECT statement only SELECT and FROM statements are mandatory. Other
clauses like WHERE, ORDER BY, GROUP BY, HAVING are optional.
For example: If we want to display the first and last name of an employee combined
together, the SQL Select Statement would be like
Output:
emp_name
Rahul Sharma
Anjali
Bhagwat
Stephen
Fleming
Shekar
Gowda
Priya Chandra
SQL ALIAS
SQL Aliases are defined for columns and tables. Basically aliases is created to make the column
selected more readable.
For Example: To select the first name of all the students, the query would be like:
334
SELECT first_name AS Name FROM student_details;
or
Output:
Name
Rahul Sharma
Anjali
Bhagwat
Stephen
Fleming
Shekar Gowda
Priya Chandra
In the above query, alias 's' is defined for the table student_details and the column first_name is
selected from the table.
The condition you provide in the WHERE clause filters the rows retrieved from the table and gives
you only those rows which you expected to see. WHERE clause can be used along with SELECT,
DELETE, UPDATE statements.
335
Syntax for a WHERE clause with Select statement is:
For Example: To find the name of a student with id 100, the query would be like:
• Comparison Operators and Logical Operators are used in WHERE Clause (Discussed later)
If you want to display employee name, current salary, and a 20% increase in the salary for
only those employees where the percentage increase in salary is greater than 30000, the
SELECT statement can be written as shown below
Output:
Name salary new_salary
Hrithik 35000 42000
Harsha 35000 42000
336
Priya 30000 36000
SQL OPERATORS
There are two types of Operators, namely Comparison Operators and Logical Operators. These
operators are used mainly in the WHERE clause, HAVING clause to filter the data to be selected.
Comparison Operators:
Comparison operators are used to compare the column data with specific values in a condition.
Comparison Operators are also used along with the SELECT statement to filter data based on
specific conditions.
Logical Operators:
There are three Logical Operators namely, AND, OR, and NOT. These operators compare two
conditions at a time to determine whether a row can be selected for the output. When retrieving data
using a SELECT statement, you can use logical operators in the WHERE clause, which allows you
to combine more than one condition.
Logical
Description
Operators
For the row to be
selected at least one of
OR
the conditions must be
true.
For a row to be selected
AND all the specified
conditions must be true.
337
For a row to be selected
NOT the specified condition
must be false.
For example: if you want to find the names of students who are studying either Maths or Science,
the query would be like,
For Example: To find the names of the students between the age 10 to 15 years, the query would
be like:
SELECT first_name, last_name, age
FROM student_details
WHERE age >= 10 AND age <= 15;
The following table describes how logical "AND" operator selects a row.
Column1 Column2 Row
Satisfied? Satisfied? Selected
YES YES YES
YES NO NO
NO YES NO
NO NO NO
If you want to find rows that do not satisfy a condition, you can use the logical operator, NOT.
NOT results in the reverse of a condition. That is, if a condition is satisfied, then the row is not
returned.
For example: If you want to find out the names of the students who do not play football, the query
would be like:
The following table describes how logical "NOT" operator selects a row.
NOT
Column1 Row
Column1
Satisfied? Selected
Satisfied?
YES NO NO
NO YES YES
339
Nested Logical Operators:
You can use multiple logical operators in an SQL statement. When you combine the logical
operators in a SELECT statement, the order in which the statement is processed is
1) NOT
2) AND
3) OR
For example: If you want to select the names of the students whose’ age is between 10 and 15
years, or those who do not play football, the SELECT statement would be
NOTE:The order in which you phrase the condition is important, if the order changes you are likely
to get a different result.
340
column value is between two values, including the end
BETWEEN...AND
values specified in the range.
IS NULL column value does not exist.
For example: To select all the students whose name begins with 'S'
The above select statement searches for all the rows where the first letter of the column first_name
is 'S' and rest of the letters in the name can be any character.
There is another wildcard character you can use with LIKE operator. It is the underscore character, '
_ ' . In a search string, the underscore signifies a single character.
For example: to display all the names with 'a' second character,
NOTE: Each underscore act as a placeholder for only one character. So you can use more than one
underscore. Eg: ' __i% '-this has two underscores towards the left, 'S__j%' - this has two
underscores between character 'S' and 'i'.
SQL IN Operator:
The IN operator is used when you want to compare a column with more than one value. It is similar
to an OR condition.
For example: If you want to find the names of students who are studying either Maths or Science,
the query would be like,
For Example: If you want to find the names of students who do not participate in any games, the
query would be as given below
342
SELECT first_name, last_name
FROM student_details
WHERE games IS NULL
There would be no output as we have every student participate in a game in the table
student_details, else the names of the students who do not participate in any games would be
displayed.
SQL ORDER BY
The ORDER BY clause is used in a SELECT statement to sort results either in ascending or
descending order. Oracle sorts query results in ascending order by default.
For Example: If you want to sort the employee table by salary of the employee, the sql query
would be.
The query first sorts the result according to name and then displays it.
You can also use more than one column in the ORDER BY clause.
343
If you want to sort the employee table by the name and salary, the query would be like,
SELECT name, salary FROM employee ORDER BY name, salary;
NOTE:The columns specified in ORDER BY clause should be one of the columns selected in the
SELECT column list.
You can represent the columns in the ORDER BY clause by specifying the position of a column in
the SELECT list, instead of writing the column name.
By default, the ORDER BY Clause sorts data in ascending order. If you want to sort the data in
descending order, you must explicitly specify it as shown below.
The above query sorts only the column 'salary' in descending order and the column 'name' by
ascending order.
If you want to select both name and salary in descending order, the query would be as given below.
NOTE: Aliases defined in the SELECT Statement can be used in ORDER BY Clause.
SQL COUNT (): This function returns the number of rows in the table that satisfies the condition
specified in the WHERE condition. If the WHERE condition is not specified, then the query returns
the total number of rows in the table.
For Example: If you want the number of employees in a particular department, the query would
be:
SELECT COUNT (*) FROM employee
WHERE dept = 'Electronics';
The output would be '2' rows.
If you want the total number of employees in all the department, the query would take the form:
SELECT COUNT (*) FROM employee;
For Example: If you want to select all distinct department names from employee table, the query
would be:
To get the count of employees with unique name, the query would be:
SELECT COUNT (DISTINCT name) FROM employee;
345
SQL MAX(): This function is used to get the maximum value from a column.
To get the maximum salary drawn by an employee, the query would be:
SQL MIN(): This function is used to get the minimum value from a column.
To get the minimum salary drawn by an employee, The query would be:
SQL AVG(): This function is used to get the average value of a numeric column.
To get the average salary, the query would be
SQL SUM(): This function is used to get the sum of a numeric column
To get the total salary given out to the employees,
For Example: If you want to know the total amount of salary spent on each department, the query
would be:
dept salary
Electrical 25000
Electronics 55000
Aeronautics 35000
InfoTech 30000
346
Having clause is used to filter data based on the group functions. This is similar to WHERE
condition but is used with group functions. Group functions cannot be used in a WHERE Clause
but can be used in HAVING clause.
For Example: If you want to select the department that has total salary paid for its employees more
than 25000, the sql query would be like;
Note: When WHERE, GROUP BY and HAVING clauses are used together in a SELECT
statement, the WHERE clause is processed first, then the rows that are returned after the WHERE
clause is executed are grouped based on the GROUP BY clause.
Finally, any conditions on the group functions in the HAVING clause are applied to the grouped
rows before the final output is displayed.
For Example: To add a column "experience" to the employee table, the query would be like
For Example: To drop the column "location" from the employee table, the query
would be like
347
ALTER TABLE employee DROP location;
For Example: To modify the column salary in the employee table, the query would be like
For Example: To drop the table employee, the query would be like
DROP TABLE employee;
While inserting a row, if you are adding value for all the columns of the table you need not specify
the column(s) name in the sql query. But you need to make sure the order of the values is in the
same order as the columns in the table.
348
INSERT INTO TABLE_NAME
VALUES (value1, value2, value3,...valueN);
For Example: If you want to insert a row to the employee table, the query would be like,
NOTE: When adding a row, only the characters o te values r da should be enclosed with single
quotes.
If you are inserting data to all the columns, the column names can be omitted. The above insert
statement can also be written as,
For Example: To insert a row into the employee table from a temporary table, the sql insert query
would be like,
INSERT INTO employee (id, name, dept, age, salary location) SELECT emp_id,
emp_name, dept, age, salary, location
FROM temp_employee;
If you are inserting data to all the columns, the above insert statement can also be written as,
NOTE: We have assumed the temp_employee table has columns emp_id, emp_name, dept, age,
salary, location in the above given order and the same datatype.
349
IMPORTANT NOTE:
1) When adding a new row, you should ensure the datatype of the value and the column matches
2) You follow the integrity constraints, if any, defined for the table.
UPDATE table_name
SET column_name1 = value1,
column_name2 = value2, ...
[WHERE condition]
• table_name - the table name which has to be updated.
• column_name1, column_name2.. - the columns that gets changed.
• value1, value2... - are the new values.
NOTE: In the Update statement, WHERE clause identifies the rows that get affected. If you do not
include the WHERE clause, column values for all the rows get affected.
For Example: To update the location of an employee, the sql update query would be like,
UPDATE employee
SET location ='Mysore'
WHERE id = 101;
To change the salaries of all the employees, the query would be,
UPDATE employee
SET salary = salary + (salary * 0.2);
NOTE:The WHERE clause in the sql delete command is optional and it identifies the rows in the
column that gets deleted. If you do not include the WHERE clause all the rows in the table is
deleted, so be careful while writing a DELETE query without WHERE clause.
350
For Example: To delete an employee with id 100 from the employee table, the sql delete query
would be like,
To delete all the rows from the employee table, the query would be like,
For Example: To delete all the rows from employee table, the query would be like,
TRUNCATE TABLE employee;
DELETE Statement: This command deletes only the rows from the table based on the condition
given in the where clause or deletes all the rows from the table if no condition is specified. But it
does not free the space containing the table.
TRUNCATE statement: This command is used to delete all the rows from the table and free the
space containing the table.
Sql joins
SQL Joins are used to relate information in different tables. A Join condition is a part of the SQL
query that retrieves rows from two or more tables. A SQL Join condition is used in the SQL
WHERE Clause of select, update, delete statements.
If an SQL join condition is omitted or if it is invalid the join operation will result in a Cartesian
product.
351
The Cartesian product returns a number of rows equal to the product of all rows in all the tables
being joined. For example, if the first table has 20 rows and the second table has 10 rows, the result
will be 20 * 10, or 200 rows. This query takes a long time to execute.
Lets use the below two tables to explain the sql join conditions.
database table "product";
product_id product_name supplier_name unit_price
100 Camera Nikon 300
101 Television Onida 100
102 Refrigerator Vediocon 150
103 Ipod Apple 75
104 Mobile Nokia 50
SQL Joins can be classified into Equi join and Non Equi join.
For example: You can get the information about a customer who purchased a product and the
quantity of product.
352
For example: If you want to display the product information for each order the query will be as
given below.
Since you are retrieving the data from two tables, you need to identify the common column between
these two tables, which is the product_id.
The columns must be referenced by the table name in the join condition, because product_id is a
column in both the tables and needs a way to be identified. This avoids ambiguity in using the
columns in the SQL SELECT statement.
The number of join conditions is (n-1), if there are more than two tables joined in a query where 'n'
is the number of tables involved. The rule must be true to avoid Cartesian product.
We can also use aliases to reference the column name, then the above query would be like,
The syntax differs for different RDBMS implementation. Few of them represent the join conditions
as "SQL left outer join", "SQL right outer join".
If you want to display all the product data along with order items data, with null values displayed
for order items if a product has no order item, the SQL query for outer join would be as shown
below:
353
product_id product_name order_id total_units
100 Camera
101 Television 5103 10
102 Refrigerator 5101 5
103 Ipod 5102 25
104 Mobile 5100 30
NOTE:If the (+) operator is used in the left side of the join condition it is equivalent to left outer
join. If used on the right side of the join condition it is equivalent to right outer join.
Conclusion
At the end of this learning outcome, the learner should be able to eexplain SQL and data definition,
create tables using CREATE TABLE constraints, use the ALTER TABLE AND DROP TABLE
statements, demonstrate data manipulation query statements, explain and demonstrating types of
joins, create and query a database from validated ER model.
Further Reading
Davidson, L. (2001). Professional SQL server 2000 database design. Birmingham, UK: Wrox Press.
354
a. Get
b. Select
cc Pop
d.Extract
9. Which key word is used with update command to change the value?
a. Alter
b. Set
c Change
d. Add
Oral Assessment
1. What are the risks involved in using the DROP table command
2. What is the role of a join?
Practical assessment
Consider the following table to answer the questions that follow:
Customer
Customer_ID Name Address Town Age
503998 Charles 1423 Nakuru 43
504321 Mary 564 Nairobi 23
502342 Judy 4234 Mombasa 12
502321 Maina 7765 Kisumu 23
Required
Write the SQL statement which could be used to
(a) Create the table above
(b) Display a list of customer who are below 30yrs and come from Nairobi
(c) Add a new column called Physical Location to the Table
(d) Delete all the rows whose customers are above 40 yrs of age
355
e) Update the address of whose Customer_ID is 504321 to 68232
6.3.4.5 References
1) Davidson, L. (2001). Professional SQL server 2000 database design. Birmingham, UK:
Wrox Press.
2) https://opentextbc.ca/dbdesign01/chapter/chapter-13-database-development-process
3) https://www.essentialsql.com/get-ready-to-learn-sql-database-normalization-explained-in-
simple-english/(Retrieved on 2nd March 2020
356
6.3.5 Learning Outcome 4: Understand design of object oriented databases
6.3.5.1 Learning Activities
Learning Outcome No. 4: Understand design of object oriented databases
·
6.3.5.2 Information Sheet No 6/LO4: Understand design of object oriented databases
Introduction
This learning outcome covers explaning object oriented databases and their concepts, implementing
object oriented concepts and creating views and triggers.
Object oriented database- A database management system in which data is stored in the form of
objects which are instances of classes.
357
Data Handling Handles comparatively Handles larger and complex
simpler data. data than RDBMS.
Class-A collection of objects with the same or similar attributes and behavior.
Inheritance-Creation of a new object from an existing object in such a way that a new object inherits
all characteristics of an existing object.
Encapsulation-A data hiding concept in which attributes, methods and functions to manipulate the
data are hidden from the outside world
Objects are created using the CREATE [OR REPLACE] TYPE statement. Following is an example
to create a simple address object consisting of few attributes –
Type created.
Let's create one more object customer where we will wrap attributes and methods together to
have object-oriented feeling –
Instantiating an Object
Defining an object type provides a blueprint for the object. To use this object, you need to create
instances of this object. You can access the attributes and methods of the object using the instance
name and the access operator (.) as follows −
DECLARE
residence address;
BEGIN
residence := address('103A', 'M.G.Road', 'Jaipur', 'Rajasthan','201301');
dbms_output.put_line('House No: '|| residence.house_no);
dbms_output.put_line('Street: '|| residence.street);
dbms_output.put_line('City: '|| residence.city);
dbms_output.put_line('State: '|| residence.state);
dbms_output.put_line('Pincode: '|| residence.pincode);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Member Methods
Member methods are used for manipulating the attributes of the object. You provide the
declaration of a member method while declaring the object type. The object body defines the code
for the member methods. The object body is created using the CREATE TYPE BODY statement.
Constructors are functions that return a new object as its value. Every object has a system defined
constructor method. The name of the constructor is same as the object type. For example –
359
The comparison methods are used for comparing objects. There are two ways to compare objects
Map method
The Map method is a function implemented in such a way that its value depends upon the value of
the attributes. For example, for a customer object, if the customer code is same for two customers,
both customers could be the same. So the relationship between these two objects would depend upon
the value of code.
Order method
The Order method implements some internal logic for comparing two objects. For example, for a
rectangle object, a rectangle is bigger than another rectangle if both its sides are bigger.
When the above code is executed at the SQL prompt, it produces the following result −
Type created.
Length: 20
Width: 10
Material: Wood
Length: 50
Width: 30
Material: Steel
create or replace
view view_name
as
select column_name1, column_name2,...
from table_name
where condition;
For example
A table of names and addresses is created of students whose student ID value is less than 4.
363
Trigger-These are stored programs which are automatically executed whenever a special event
occurs in the data
Syntax
The following table shows the content of the INSERTED and DELETED tables before and after
each event:
DML event INSERTED table holds DELETED table holds
INSERT rows to be inserted empty
364
DML event INSERTED table holds DELETED table holds
UPDATE new rows modified by the update existing rows modified by the update
DELETE Empty rows to be deleted
We will use the following production.products table from the sample database for the
demonstration.
365
CREATE TRIGGER production.trg_product_audit
Next, you specify the name of the table, which the trigger will fire when an event occurs, in
the ON clause:
ON production.products
Then, you list the one or more events which will call the trigger in the AFTER clause:
AFTER INSERT, DELETE
After that, inside the body of the trigger, you set the SET NOCOUNT to ON to suppress the
number of rows affected messages from being returned whenever the trigger is fired.
SET NOCOUNT ON;
The trigger will insert a row into the production.product_audits table whenever a row is inserted
into or deleted from the production.products table. The data for insert is fed from
the INSERTED and DELETED tables via the UNION ALL operator:INSERT INTO
production.product_audits
(
product_id,
product_name,
brand_id,
category_id,
model_year,
list_price,
updated_at,
operation
)
SELECT
i.product_id,
product_name,
brand_id,
category_id,
model_year,
i.list_price,
GETDATE(),
'INS'
FROM
inserted AS i
UNION ALL
366
SELECT
d.product_id,
product_name,
brand_id,
category_id,
model_year,
d.list_price,
getdate(),
'DEL'
FROM
deleted AS d;
367
UNION ALL
SELECT
d.product_id,
product_name,
brand_id,
category_id,
model_year,
d.list_price,
GETDATE(),
'DEL'
FROM
deleted d;
END
Finally, you execute the whole statement to create the trigger. Once the trigger is created, you can
find it under the triggers folder of the table as shown in the following picture:
368
)
VALUES (
'Test product',
1,
1,
2018,
599
);
Because of the INSERT event, the production.trg_product_audit trigger
of production.products table was fired.
SELECT
*
FROM
production.product_audits;
Here is the output:
SELECT
*
FROM
production.product_audits;
The following picture shows the output:
Conclusion
At the end of this learning outcome, the learner should be able to explain object oriented databases
and their concepts, implement object oriented concepts and create views and triggers.
369
Further Reading
Davidson, L. (2001). Professional SQL server 2000 database design. Birmingham, UK:
6.3.5.3 Self-Assessment
Written Assessment
1.A __________ is a special kind of a stored procedure that executes in response to certain actions
on the table like insertion, deletion or updating of data.
a. Procedures
B. B. Triggers
c. Functions
d. None of the mentioned
2. The CREATE TRIGGER statement is used to create the trigger. THE _____ clause specifies the
table name on which the trigger is to be attached. The ______ specifies that this is an AFTER-
INSERT trigger.
a. for insert, on
b. On, for insert
c. For, insert
d. Both a and c
3. What is the purpose of a view?
4. What command do you use to create a view?
5. How is a view different from a normal table?
Oral Assessment
Explain object oriented concepts that can be used in object oriented databases.
Practical Assessment
Create a database with an Employee table that has the following schema, then demonstrate how
insertion and deletion of records using a trigger.
370
6.3.6 Learning Outcome 5: Understand indexing and hashing
6.3.6.1 Learning Activities
Learning Outcome No.5: Understand indexing and hashing
·
6.3.6.2 Information Sheet No 6/LO5: Understand indexing and hashing
Introduction
This learning outcome covers explaining, demonstrating and implementing indexing and hashing
in a database.
Indexing
Indexes are special lookup tables that the database search engine can use to speed up data retrieval.
Simply put, an index is a pointer to data in a table. An index in a database is very similar to an index
in the back of a book.
For example, if you want to reference all pages in a book that discusses a certain topic, you first refer
to the index, which lists all the topics alphabetically and are then referred to one or more specific
page numbers.
An index helps to speed up SELECT queries and WHERE clauses, but it slows down data input,
with the UPDATE and the INSERT statements. Indexes can be created or dropped with no effect
on the data.
371
Creating an index involves the CREATE INDEX statement, which allows you to name the index,
to specify the table and which column or columns to index, and to indicate whether the index is in
an ascending or descending order.
Indexes can also be unique, like the UNIQUE constraint, in that the index prevents duplicate entries
in the column or combination of columns on which there is an index.
Types of indexing
Primary Indexing- Data is sorted according to the search key the primary key of the database table is
used to create the index .There is a one-to-one relationship between the entries in the index table and
the records in the main table making quick and efficient.
Secondary Indexing-In this method, the huge range for the columns is selected initially so that the
mapping size of the first level becomes small. Then each range is further divided into smaller ranges.
The mapping of the first level is stored in the primary memory, so that address fetch is faster. The
mapping of the second level and actual data are stored in the secondary memory (hard disk).
Hashing
This is a technique used to directly search the location of desired data on the disk without using
index structure. Data is stored in the form of data blocks whose address is generated by applying a
hash function in the memory location where these records are stored known as a data block or data
bucket.
Types of Hashing
1. Static Hashing-when a search-key value is provided, the hash function always computes the
same address.
2. Dynamic Hashing-Static hashing does not expand or shrink as the size of the database grows or
shrinks. Dynamic hashing provides a mechanism in which data buckets are added and removed
dynamically and on-demand.
Note: Updating a table with indexes takes more time than updating a table without (because the
indexes also need an update). So, only create indexes on columns that will be frequently searched
against.
373
CREATE UNIQUE INDEX Syntax
Conclusion
At the end of this learning outcome, the learner should be able to explain, demonstrate and
implement indexing and hashing in a database.
Further Reading
1. https://www.tutorialspoint.com/sql/sql-indexes.htm
2. https://www.sqlservertutorial.net/sql-server-indexes/sql-server-create-index/
3. https://www.w3schools.com/sql/sql_create_index.asp
6.3.5.3 Self-Assessment
Written Assessment
1. What is the purpose of index in sql server
A. To enhance the query performance
B. To provide an index to a record
C. To perform fast searches
D. All of the mentioned
2. An indexing operation
A. sorts a file using a single key
B. sorts file using two keys
374
C. establishes an index for a file
D. both (b) and (c)
3. The index consists of
A. a list of keys
B. pointers to the master list
C. both (a) and (b)
D. All of the above
4. The hashing technique which allocates fixed number of buckets is classified as
A. dynamic hashing
B. Static hashing
C. external hashing
D. internal hashing
5. The index which has an entry for some of the key value is classified as
A. linear index
B. dense index
C. Sparse index
D. cluster index
6. What is the name given to indexing based on assorted order?
A. Sequenced indices
B. hashing indices
C ordered indices
D. Structured indices
9. A harsh function must meet______criteria
A. 2
B. 3
C. 4
D. none of the above
Oral Assessment
When should use of indexes be avoided?
Practical Assessment
Create a database with an Employee table that has the following schema, then demonstrate how a
single column index can be created for the table.
375
6.3.6.5 References
1. https://www.tutorialspoint.com/dbms/dbms_hashing.htm
2. https://www.tutorialspoint.com/dbms/dbms_indexing.htm
376
6.3.7 Learning Outcome 6: Understand Database applications
6.3.7.1 Learning Activities
Learning Outcome No.6: Understand Database applications
6.1 Decision support systems are explained. Activities may be carried out in groups
6.2 Data mining is explained or as individual
6.3 Distributed databases are demonstrated
6.4 Data warehousing is illustrated
6.5 Spatial and geographical databases are explained ·
6.6 Multi-media databases are illustrated
6.7 Mobility and personal databases are explained.
6.8 Data warehouses are designed and implemented from
a given set of requirements.
·
6.3.7.2 Information Sheet No 6/LO6: Understand Database applications
Introduction
This learning outcome covers explaining decision support systems, data mining, mobility and
personal databases, spatial and geographical databases, demonstrating distributed databases,
illustrating multi-media databases, illustrating, designing and implementing a data warehouse.
Database Mining-In organizations data is stored in databases. Data mining is the process of
automatically searching large databases to discover anomalies, patterns and correlations within
large data sets to predict outcomes. Data mining is used in sectors like
Marketing -To explore databases and to improve market segmentation by analysing the
relationships between parameters such as customer age, gender, tastes, etc. The trends can predict
which users are likely to unsubscribe from a service, what interests them based on their searches,
to achieve a higher response rate.
377
Retail- Supermarkets, for example, use joint purchasing patterns to identify product associations
and decide how to place them in the aisles and on the shelves.
Medicine-Data mining enables more accurate diagnostics. Having all of the patient's information,
such as medical records, physical examinations, and treatment patterns, allows more effective
treatments to be prescribed. It also enables more effective, efficient and cost-effective management
of health resources by identifying risks, predicting illnesses in certain segments of the population
or forecasting the length of hospital admission
Consider a banking system consisting of four branches in four different cities. Each branch has its
own computer, with a database of all the accounts maintained at that branch. Each installation is a
site. There also exists one single site that maintains information about all the branches of the bank.
The site containing information about all the branches of the bank maintains the relation branch
Branch schema is as follows: ( branch_name, branch-city, assets).
378
The DBMS Distributed Data Storage
Consider a database table named t that is to be stored in the database. There are two approaches to storing
this table in the distributed database:
- Replication: The system maintains several identical replicas (copies) of the table, and stores each
replica at a different site. The alternation to replication is to store only one copy of relation t.
- Fragmentation. The system partitions the table into several fragments, and stores each fragment at
a different site.
The two can be combined. A table can be partitioned into several fragments and there may be several replicas
of each fragment.
Data Replication
If table t replicated, a copy of the table is stored in two or more sites. In the most extreme case, we have full
replication, in which a copy is stored in every site in the system.
Advantages of replication
- Availability: If one of the sites containing table t fails, then the table can be found in another site.
Thus the system can continue to process queries involving the table t, despite the failure of one site.
- Increased parallelism: Several sites can process queries involving the table t in parallel. The more
replicas of r there are, the greater the chance that the needed data will be found in the site where the
transaction is executing. Hence data replication minimizes movement of data between sites.
Disadvantages of replication
- Increased overhead on update: The system must ensure that all replicas of a table t, are consistent,
otherwise erroneous computations may result. Thus whenever t is updated, the update must be
communicated to all sites containing replicas. The result is increased overhead. For example, in a
banking system, where account information is replicated in various sites; it is necessary to ensure
that the balance in a particular account agrees in all sites.
Data Fragmentation
If table t is fragmented, t is divided into a number of fragments t1, t2, t3,…., tn. These fragments contain
sufficient information to allow reconstruction of the original t.
Goals of fragmentation
Fragmentation aims to improve:
- Reliability
- Performance
- Balanced storage capacity and costs
- Communication costs
- Security
Types of fragmentation
379
There are two different schemes for fragmenting a table: Horizontal fragmentation and Vertical
fragmentation.
Horizontal fragmentation
- It splits the table by assigning each row to one or more fragments.
Vertical Fragmentation
- Splits the table by assigning each column to one or more fragments.
Example
380
Vertical fragmentation of PROJ table
• PROJ1: information about project budgets
• PROJ2: information about project names and locations
Homogeneous DDBMS
- All sites use same DBMS product
- All sites are aware of one another and agree to co-operate in processing
- Sites surrender a portion of their autonomy in terms of their right to change schemas or DBMS
software.
- The DBMS software must also co-operate with other sites in exchanging information about
transactions to make transaction processing across multiple sites.
- It is much easier to design and manage
381
- The approach provides incremental growth and allows increased performance
Heterogeneous DDBMS
- Sites may run different DBMS products, with possibly different underlying data models
- Sites may not be aware of one another and may provide only limited facilities for co-operation in
transaction processing. This occurs when sites have implemented their own databases first, and
integration is considered later.
- Translations are required to allow for different hardware and/or different DBMS products
- Differences in schema often a major problem for query processing, while divergence in software
becomes a hindrance for processing transactions that access multiple sites.
- Autonomy
• Each site is able to maintain a degree of control over data that are stored locally.
- Availability
• If one site fails in a distributed system, the remaining sites may be able to continue
operating. This is because data items are replicated in several sites.
o Parallelism in execution
Transparency: Hiding database implementation details from the users such as where the data is physically
located or how the data is accessed at the specific local site.
Data Warehousing
This is a system of pulling together data from many different sources within an organization for
reporting and analysis to make viable decisions
Features of data warehouse
1. Subject oriented-It provides information around a subject rather than the organization's
ongoing operations e.g. product, customers, suppliers, sales, revenue
2. Integrated –Data from different heterogeneous sources is stored in a common and
universally accepted manner
3. Time-Variant –Data collected in a data warehouse is identified with a particular time
period e. g. Weekly, Monthly, Annually
4. Non-volatile-Data residing in a data warehouse is permanent, meaning that data is not erased or
deleted when new data is inserted.
Multimedia databases - A database that stores data in the form of text, images, videos, audio
animations.
384
9. Roll-out the warehouses and applications: Once the data warehouse has been populated
and the end-client applications tested, the warehouse system and the operations may be
rolled out for the user's community to use.
Star Schema
• Each dimension in a star schema is represented with only one-dimension table.
• This dimension table contains the set of attributes.
• The following diagram shows the sales data of a company with respect to the four
dimensions, namely time, item, branch, and location.
385
Figure 82:Star Schema
• There is a fact table at the center. It contains the keys to each of four dimensions.
• The fact table also contains the attributes, namely dollars sold and units sold.
Note − each dimension has only one dimension table and each table holds a set of attributes. For
example, the location dimension table contains the attribute set {location_key, street, city,
province_or_state,country}. This constraint may cause data redundancy. For example,
"Vancouver" and "Victoria" both the cities are in the Canadian province of British Columbia. The
entries for such cities may cause data redundancy along the attributes province_or_state and
country.
Snowflake Schema
• Some dimension tables in the Snowflake schema are normalized.
• The normalization splits up the data into additional tables.
• Unlike Star schema, the dimensions table in a snowflake schema are normalized. For
example, the item dimension table in star schema is normalized and split into two
dimension tables, namely item and supplier table.
386
Figure 83:Snowflake Schema
• Now the item dimension table contains the attributes item_key, item_name, type, brand,
and supplier-key.
• The supplier key is linked to the supplier dimension table. The supplier dimension table
contains the attributes supplier_key and supplier_type.
Note − Due to normalization in the Snowflake schema, the redundancy is reduced and therefore, it
becomes easy to maintain and the save storage space.
387
• The shipping fact table has the five dimensions, namely item_key, time_key, shipper_key,
from_location, to_location.
• The shipping fact table also contains two measures, namely dollars sold and units sold.
• It is also possible to share dimension tables between fact tables. For example, time, item,
and location dimension tables are shared between the sales and shipping fact table.
Schema Definition
Multidimensional schema is defined using Data Mining Query Language (DMQL). The two
primitives, cube definition and dimension definition, can be used for defining the data warehouses
and data marts.
define dimension time as (time key, day, day of week, month, quarter,
year)
define dimension item as (item key, item name, brand, type, supplier
type)
define dimension branch as (branch key, branch name, branch type)
define dimension time as (time key, day, day of week, month, quarter,
year)
define dimension item as (item key, item name, brand, type, supplier
(supplier key, supplier type))
define dimension branch as (branch key, branch name, branch type)
388
define dimension location as (location key, street, city (city key,
city, province or state, country))
define dimension time as (time key, day, day of week, month, quarter,
year)
define dimension item as (item key, item name, brand, type, supplier
type)
define dimension branch as (branch key, branch name, branch type)
define dimension location as (location key, street, city, province or
state,country)
define cube shipping [time, item, shipper, from location, to location]:
Conclusion
At the end of this learning outcome, the learner should be able to explain decision support systems,
data mining, mobility and personal databases, spatial and geographical databases, demonstrate
distributed databases, illustrate multi-media databases, illustrate, design and implement a data
warehouse.
Further Reading
https://www.tutorialspoint.com/data_mining/index.htm
389
2. Which of the following is storing a separate copy of the database at multiple locations?
A. Data Replication
B. Horizontal Partitioning
C. Vertical Partitioning
D. Horizontal and Vertical Partitioning
Oral Assessment
1. What is the difference between OLAP and OLTP?
2. Using the example of any business you are familiar with, outline how a data warehouse
might be used to identify trends that can help a business be competitive.
Practical Assessment
Consider a bank system with at least the following tables: Customer, branch, Withdrawals,
Deposits. Demonstrate how you can build a star schema for the bank system.
6.3.7.5 References
1. https://www.tutorialspoint.com/dwh/index.htm
2. https://www.tutorialspoint.com/dwh/dwh_data_warehousing.htm
391
CHAPTER 7: INFORMATION SYSTEMS
7.1 Introduction
This unit covers the competencies required to develop an information system. It involves
understanding fundamentals of information systems, understanding the software development
process, demonstrating human computer interaction principles, understanding the VB.net
programming environment and developing and testing a VB.NET application.
392
7.3.2 Learning Outcome 1: Understand fundamentals of Information Systems
7.3.2.1 Learning Activities
Learning Outcome 1: Understand fundamentals of Information Systems
Learning Activities Special Instructions
Introduction:
This learning outcome covers describing the components of information systems, outlining types of
information systems, explaining emerging trends in information systems and recommending
Information systems for different scenarios
Information systems
Information systems are the combination of people, information technology, and business
processes to accomplish a business objective.
393
v) Process: a process is a series of steps undertaken to achieve a desired outcome or
goal. Information systems are becoming more and more integrated with organizational
processes, bringing more productivity and better control to those processes
ii) Socialization: social media sites are seeing tremendous growth; such as Facebook, and
twitter usage
394
iii) Personalization: ever since the advent of Web 2.0 and e-commerce, users of information
systems have expected to be able to modify their experiences to meet their personal tastes.
Soon, we will begin seeing devices perfectly matched to our personal preferences, based upon
information collected about us in the past
iv) Mobile technologies: Beginning with the simple cell phone in the 1990s and evolving into
the smartphones and tablets of today, the growth of mobile has been overwhelming
v) Wearable technologies: Wearables have been around for a long time, with technologies
such as hearing aids and, later, Bluetooth earpieces. But now, we are seeing an explosion of
new wearable technologies. Perhaps the best known of these is Google Glass, an augmented
reality device that you wear over your eyes like a pair of eyeglasses.
vi) Collaborative technologies: this is whereby it keeps getting simpler than ever to share data
with each other for mutual benefit. Such as adding our rating of a restaurant to a review site.
vii) Printable technologies: One of the most amazing innovations to be developed recently is
the 3-D printer. 3-D printing is quite useful for prototyping the designs of products to
determine their feasibility and marketability. 3-D printing has also been used to create
working prosthetic legs, handguns, and even an ear that can hear beyond the range of normal
hearing
vii) Wireless technologies (findable): The “Internet of Things” refers to the idea of physical
objects being connected to the Internet. Advances in wireless technologies and sensors will
allow physical objects to send and receive data about themselves. Many of the technologies
to enable this are already available – it is just a matter of integrating them together
viii) Autonomous: an extension of the Internet of Things is another major emerging trend:
autonomous robots and vehicles. By combining software, sensors, and location technologies,
devices that can operate themselves to perform specific functions are being developed.
395
iii) Availability: Availability means that information can be accessed and modified by anyone
authorized to do so in an appropriate time frame
vi) Virtual private networks: A VPN allows a user who is outside of a corporate network to take
a detour around the firewall and access the internal network from the outside. Through a
combination of software and security measures, this lets an organization allow limited access to
its networks while at the same time ensuring overall security.
396
vii) Physical Security: Physical security is the protection of the actual hardware and networking
components that store and transmit information resources to ensure that these resources cannot be
physically tampered with or stolen
Cyber security
Cyber security is the practice of defending computers, servers, mobile devices, electronic systems,
networks, and data from malicious attacks. It's also known as information technology security or
electronic information security
Web threats
The threats countered by cyber-security are three-fold:
1. Cybercrime includes single actors or groups targeting systems for financial gain or to cause
disruption.
2. Cyber-attack often involves politically motivated information gathering.
3. Cyber-terrorism is intended to undermine electronic systems to cause panic or fear.
Defence strategies
Cyber safety tips - protect yourself against cyber attacks
Businesses and individuals ought to take guard against cyber threats. The following are some cyber
safety tips:
1. Update your software and operating system: This means you benefit from the latest security
patches.
2. Use anti-virus software: Security solutions like Kaspersky Total Security will detect and
removes threats. Keep your software updated for the best level of protection.
3. Use strong passwords: Ensure your passwords are not easily guessable.
4. Do not open email attachments from unknown senders: These could be infected with
malware.
397
5. Do not click on links in emails from unknown senders or unfamiliar websites: This is a
common way that malware is spread.
6. Avoid using unsecured Wi-Fi networks in public places: Unsecure networks leave you
vulnerable to man-in-the-middle attacks.
Conclusion
At the end of this learning outcome, the trainee should be able to describe the components of
information systems, outline types of information systems, explain emerging trends in information
systems and recommend information systems for different scenarios
Further reading
Information systems for business and beyond: A look at the technology, people, and processes of
information systems; 2014 -by David T. Bourgeois, Ph.D. and Bourgeois
7.3.2.3 Self-Assessment
Written assessment
1. What are the five components that make up an information system?
2. What are three examples of information system hardware?
3. Microsoft Windows is an example of which component of information systems?
4. What roles do people play in information systems?
Oral assessment
1. Outline types of information systems
2. What is a database in the context of Information Systems?
3. What does the term authentication mean?
Practical assessment
Research on business application areas of the various types of information systems and indicate
their benefits
7.3.2.5 References
398
1. https://saylordotorg.github.io/text_business-information-systems-design-an-app-for-
that/index.html
2. https://edugeneral.org/blog/business/types-of-information-systems/
399
7.3.3 Learning outcome 2: Understand the Software Development Process
7.3.3.1 Learning Activities
Learning Outcome 2: Understand the Software Development Process
Learning Activities Special Instructions
Introduction:
This learning outcome covers explaining the Software Development Life Cycle and software
development methodologies and demonstrating modeling techniques using CASE tools.
1. Preliminary Analysis: In this phase, a review is done of the request. This step is
important in determining if the project should even get started.
2. System Analysis: In this phase, one or more system analysts work with different
stakeholder groups to determine the specific requirements for the new system. No
programming is done in this step. Instead, procedures are documented, key players are
interviewed, and data requirements are developed in order to get an overall picture of
exactly what the system is supposed to do. The result of this phase is a system-
requirements document.
3. System Design: In this phase, a designer takes the system-requirements document
created in the previous phase and develops the specific technical details required for
the system. It is in this phase that the business requirements are translated into specific
technical requirements. The design for the user interface, database, data inputs and
outputs, and reporting are developed here. The result of this phase is a system-design
400
document. This document will have everything a programmer will need to actually
create the system.
4. Programming: The code finally gets written in the programming phase. Using the
system-design document as a guide, a programmer (or team of programmers) develops
the program. The result of this phase is an initial working program that meets the
requirements laid out in the system-analysis phase and the design developed in the
system-design phase.
5. Testing: In the testing phase, the software program developed in the previous phase
is put through a series of structured tests. The first is a unit test, which tests individual
parts of the code for errors or bugs. Next is a system test, where the different
components of the system are tested to ensure that they work together properly.
Finally, the user-acceptance test allows those that will be using the software to test the
system to ensure that it meets their standards. Any bugs, errors, or problems found
during testing are addressed and then tested again.
6. Implementation: Once the new system is developed and tested, it has to be
implemented in the organization. This phase includes training the users, providing
documentation, and conversion from any previous system to the new system.
7. Maintenance: This final phase takes place once the implementation phase is
complete. In this phase, the system has a structured support process in place: reported
bugs are fixed and requests for new features are evaluated and implemented; system
updates and backups are performed on a regular basis.
401
to large, resource-intensive projects. RAD makes more sense for smaller projects that are less
resource-intensive and need to be developed quickly.
ii) User Design. In this phase, representatives of the users work with the system analysts,
designers, and programmers to interactively create the design of the system. One technique
for working with all of these various stakeholders is the so-called JAD session. JAD is an
acronym for joint application development. A JAD session gets all of the stakeholders
together to have a structured discussion about the design of the system. Application
developers also sit in on this meeting and observe, trying to understand the essence of the
requirements.
iii) Construction. In the construction phase, the application developers, working with the
users, build the next version of the system. This is an interactive process, and changes can be
made as developers are working on the program. This step is executed in parallel with the
User Design step in an iterative fashion, until an acceptable version of the product is
developed.
iv) Cutover. In this step, which is similar to the implementation step of the SDLC, the system
goes live. All steps required to move from the previous state to the use of the new system are
completed here.
Agile Methodologies
Agile methodologies are a group of methodologies that utilize incremental changes with a
focus on quality and attention to detail. Each increment is released in a specified period of
time (called a time box), creating a regular release schedule with very specific objectives.
While considered a separate methodology from RAD, they share some of the same principles:
402
iterative development, user interaction, ability to change. The agile methodologies are based
on the “Agile Manifesto,” first released in 2001.
Modeling techniques
Models are forms of description often adopted in software development. They are abstractions used
to represent and communicate what is important, devoid of unnecessary detail, and to help developers
deal with the complexity of the problem being investigated or the solution being developed.
The visual representation makes it a good communication tool between User and System designer.
Structure of DFD allows starting from a broad overview and expand it to a hierarchy of detailed
diagrams. DFD has often been used due to the following reasons:
i) Logical information flow of the system
ii) Determination of physical system construction requirements
iii) Simplicity of notation
iv) Establishment of manual and automated systems requirements
2. Data flow: A data-flow is a path for data to move from one part of the
information system to another. A data-flow may represent a single data
403
element such as the Customer ID or it can represent a set of data element (or a
data structure).
Example:
Customer_info (LastName, FirstName, SS#, Tel #, etc.)
Order_info (OrderId, Item#, OrderDate, CustomerID, etc.)
Notation: Straight lines with incoming arrows are input data flow; Straight
lines with outgoing arrows are output data flows
3. Data Store: A data store or data repository is used in a data-flow diagram to
represent a situation when the system must retain data because one or more
processes need to use the stored data in a later time.
Notation: Data can be written into the data store, which is depicted by an
outgoing arrow; Data can be read from a data store, which is depicted by an
incoming arrow.
Examples are: inventory, Accounts receivables, Orders, and Daily Payments.
404
An ER diagram is a means of visualizing how the information a system produces is
related. There are five main components of an ERD:
2. Actions, which are represented by diamond shapes, show how two entities
share information in the database.
4. Connecting lines, solid lines that connect attributes to show the relationships
of entities in the diagram.
5. Cardinality specifies how many instances of an entity relate to one instance
of another entity. Ordinality is also closely linked to cardinality. While
cardinality specifies the occurrences of a relationship, ordinality describes the
relationship as either mandatory or optional. In other words, cardinality
specifies the maximum number of relationships and ordinality specifies the
absolute minimum number of relationships.
405
Notation styles that express cardinality
Bachman Style:
Chen Style:
406
Figure 89:Entity Modeling notations
UML diagrams
• UML stands for Unified Modeling language.
• UML is a way of visualizing a software program using a collection of
diagrams.
• These diagrams are organized into two distinct groups: structural diagrams
and behavioral or interaction diagrams.
CASE tools are set of software application programs, which are used to automate SDLC activities.
CASE tools are used by software project managers, analysts and engineers to develop software
system.
There are number of CASE tools available to simplify various stages of Software Development Life
Cycle such as Analysis tools, Design tools, Project management tools, Database Management tools,
Documentation tools are to name a few.
Use of CASE tools accelerates the development of project to produce desired result and helps to
uncover flaws before moving ahead with next stage in software development.
CASE tools can be grouped together if they have similar functionality, process activities and
capability of getting integrated with other tools.
408
Project Management Tools
These tools are used for project planning, cost and effort estimation, project scheduling and resource
planning. Managers have to strictly comply project execution with every mentioned step in software
project management. Project management tools help in storing and sharing project information in
real-time throughout the organization. For example, Creative Pro Office, Trac Project, Basecamp.
Documentation Tools
Documentation in a software project starts prior to the software process, goes throughout all phases
of SDLC and after the completion of the project.
Documentation tools generate documents for technical users and end users. Technical users are
mostly in-house professionals of the development team who refer to system manual, reference
manual, training manual, installation manuals etc. The end user documents describe the functioning
and how-to of the system such as user manual. For example, Doxygen, DrExplain, Adobe RoboHelp
for documentation.
Analysis Tools
These tools help to gather requirements, automatically check for any inconsistency, inaccuracy in
the diagrams, data redundancies or erroneous omissions. For example, Accept 360, Accompa,
CaseComplete for requirement analysis, Visible Analyst for total analysis.
Design Tools
These tools help software designers to design the block structure of the software, which may further
be broken down in smaller modules using refinement techniques. These tools provides detailing of
each module and interconnections among modules. For example, Animated Software Design
Programming Tools
These tools consist of programming environments like IDE (Integrated Development Environment),
in-built modules library and simulation tools. These tools provide comprehensive aid in building
software product and include features for simulation and testing. For example, Cscope to search
code in C, Eclipse.
Prototyping Tools
Software prototype is simulated version of the intended software product. Prototype provides initial
look and feel of the product and simulates few aspect of actual product.
Prototyping CASE tools essentially come with graphical libraries. They can create hardware
independent user interfaces and design. These tools help us to build rapid prototypes based on
existing information. In addition, they provide simulation of software prototype. For example,
Serena prototype composer, Mockup Builder.
409
These tools assist in designing web pages with all allied elements like forms, text, and script, graphic
and so on. Web tools also provide live preview of what is being developed and how will it look after
completion. For example, Fontello, Adobe Edge Inspect, Foundation 3, Brackets.
Maintenance Tools
Software maintenance includes modifications in the software product after it is delivered. Automatic
logging and error reporting techniques, automatic error ticket generation and root cause Analysis are
few CASE tools, which help software organization in maintenance phase of SDLC. For example,
Bugzilla for defect tracking, HP Quality Center.
Conclusion
At the end of the learning outcome, the trainee should be able to explain the software
development life cycle and software development methodologies and demonstrate modeling
techniques using CASE tools.
Further reading
• https://bus206.pressbooks.com/chapter/chapter-10-information-systems-development/
7.3.3.3 Self-Assessment
Written assessment
1. Explain Software Development Life Cycle
2. What is RAD software development?
3. State at least 4 rules of data flows in a DFD
4. What is a CASE tool?
5. Why is information systems modeling important?
Oral assessment
1. Explain Software Development Methodologies
2. Explain all the symbols in a DFD
Practical assessment
1. Install StarUML software
2. Demonstrate the various UML diagrams, indicating the scenarios that call for each diagram.
7.3.3.5 References
411
7.3.4 Learning outcome 3: Demonstrate Human Computer Interaction Principles
7.3.4.1 Learning Activities
Learning Outcome 3: Demonstrate Human Computer Interaction Principles
Learning Activities Special Instructions
Introduction
This learning outcome covers explaining the Human Computer Interaction and interaction design
principles and demonstrating interface design using a design software.
412
3D: Physical objects or space
Through what physical objects do users interact with the product? A laptop, with a mouse or
touchpad? Or a smartphone, with the user’s fingers? And within what kind of physical space
does the user do so? For instance, is the user standing in a crowded train while using the app
on a smartphone, or sitting on a desk in the office surfing the website? These all affect the
interaction between the user and the product.
4D: Time
While this dimension sounds a little abstract, it mostly refers to media that changes with
time (animation, videos, sounds). Motion and sounds play a crucial role in giving visual and
audio feedback to users’ interactions. Also of concern is the amount of time a user spends
interacting with the product: can users track their progress, or resume their interaction some
time later?
5D: Behaviour
This includes the mechanism of a product: how do users perform actions on the website?
How do users operate the product? In other words, it’s how the previous dimensions define
the interactions of a product. It also includes the reactions—for instance emotional
responses or feedback—of users and the product.
413
important information and thereby refresh the user’s memory
6. Prevent Errors/Reversal of Action: For instance, having the system require the user to
choose from possibilities (e.g., menu system) is generally a safer approach than to rely on
recall
7. Naturalness: Naturalness refers to a trait that is reflective of various operations in our
everyday life
414
2. Adobe Experience Design
• Runs on OS X, Windows, Android, iOS
• Prototypes for: All
With Adobe XD, you can draw, reuse, and remix vector and build artwork to create wireframes,
screen layouts, interactive prototypes, and production-ready assets all in the same app.
3. Axure
• Runs on OS X, Windows
• Prototypes for: All OS’s
Conclusion
At the end of the learning outcome, the trainee should be able to explain the Human Computer
Interaction and interaction design principles and demonstrate interface design using a design
software.
Further reading
https://www.interaction-design.org/literature/book/the-encyclopedia-of-human-computer-
interaction-2nd-ed/human-computer-interaction-brief-intro
7.3.4.3 Self-Assessment
Written assessment
1. Explain possible mistakes in interaction design
2. What is HCI?
3. Why is consistency important in interface design?
4. How should the naturalness principle apply in interface design?
5. What range of computer users should HCI design cover?
Oral assessment
How should HCI design cover the needs of special users such as children and the physically
challenged?
Practical assessment
1. Install a UI/UX design software
2. Demonstrate interface interaction design using the design software
7.3.4.5 References
416
7.3.5 Learning outcome 4: Understand the VB.NET programming environment
7.3.5.1 Learning Activities
Learning Outcome 4: Understand the VB.NET programming environment
Learning Activities Special Instructions
7.3.5.2 Information Sheet No. 7/LO4: Understand the VB.NET programming environment
Introduction
This learning outcome covers explaining the .NET framework, installing Visual Studio, outlining
features of VB.NET, explaining the VB.NET IDE environment, explaining VB.NET program
structure and creating and compiling a VB.NET project
The .Net framework is a revolutionary platform that helps you to write the following types of
applications −
i) Windows applications
ii) Web applications
iii) Web services
The .Net framework applications are multi-platform applications. The framework has been designed
in such a way that it can be used from any of the following languages: Visual Basic, C#, C++, Jscript,
and COBOL, etc.
All these languages can access the framework as well as communicate with each other.
The .Net framework consists of an enormous library of codes used by the client languages like
VB.Net. These languages use object-oriented methodology.
417
3. Common Language Specification
4. Common Type System
5. Metadata and Assemblies
6. Windows Forms
7. ASP.Net and ASP.Net AJAX
8. ADO.Net
9. Windows Workflow Foundation (WF)
10. Windows Presentation Foundation
11. Windows Communication Foundation (WCF)
12. LINQ
It gets automatically installed in your machine. Please note that you need an active internet connection
for installing
Before you start learning more about VB.NET programming, it is important to understand the
development environment and identify some of the frequently using programming tools in Visual
Studio IDE.
418
Figure 90:Visual Studio IDE
1. Menu Bar
2. Standard Toolbar
3. ToolBox
4. Forms Designer
5. Output Window
6. Solution Explorer
7. Properties Window
Visual Basic.NET IDE is built out of a collection of different windows. Some windows are used for
writing code, some for designing interfaces, and others for getting a general overview of files or
classes in your application.
Visual Studio organizes your work in projects and solutions. A solution can contain more than one
project, such as a DLL and an executable that references that DLL. From the following chapters you
will learn how to use these Visual Studio features for your programming needs.
Let us look at a simple code that would print the words "Hello World"
419
Imports System
Module Module1
'This program will display Hello World
Sub Main()
Console.WriteLine("Hello World")
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Hello, World!
You can compile a VB.Net program by using the command line instead of the Visual Studio IDE −
• Open a text editor and add the above mentioned code.
• Save the file as helloworld.vb
• Open the command prompt tool and go to the directory where you saved the file.
• Type vbc helloworld.vb and press enter to compile your code.
• If there are no errors in your code the command prompt will take you to the next line and
would generate helloworld.exe executable file.
• Next, type helloworld to execute your program.
• You will be able to see "Hello World" printed on the screen.
• Object − Objects have states and behaviors. Example: A dog has states - color, name, breed
as well as behaviors - wagging, barking, eating, etc. An object is an instance of a class.
• Class − A class can be defined as a template/blueprint that describes the behaviors/states that
objects of its type support.
• Methods − A method is basically a behavior. A class can contain many methods. It is in
methods where the logics are written, data is manipulated and all the actions are executed.
• Instance Variables − Each object has its unique set of instance variables. An object's state
is created by the values assigned to these instance variables.
421
Let us look at an implementation of a Rectangle class and discuss VB.Net basic syntax on the basis
of our observations in it −
Imports System
Public Class Rectangle
Private length As Double
Private width As Double
'Public methods
Public Sub AcceptDetails()
length = 4.5
width = 3.5
End Sub
Public Function GetArea() As Double
GetArea = length * width
End Function
Public Sub Display()
Console.WriteLine("Length: {0}", length)
Console.WriteLine("Width: {0}", width)
Console.WriteLine("Area: {0}", GetArea())
End Sub
Shared Sub Main()
Dim r As New Rectangle()
r.Acceptdetails()
r.Display()
Console.ReadLine()
End Sub
End Class
When the above code is compiled and executed, it produces the following result −
Length: 4.5
Width: 3.5
Area: 15.75
Sub Main indicates the entry point of VB.Net program. Here, we are using Class that contains both
code and data. You use classes to create objects. For example, in the code, r is a Rectangle object.
422
A class may have members that can be accessible from outside class, if so specified. Data members
are called fields and procedure members are called methods.
Shared methods or static methods can be invoked without creating an object of the class. Instance
methods are invoked through an object of the class −
Shared Sub Main()
Dim r As New Rectangle()
r.Acceptdetails()
r.Display()
Console.ReadLine()
End Sub
You may also change the .net framework that you are targeting on the middle top part of the “New
Project” screen. However, the default .net Framework 2.0 should work for light-weight programs.
423
At the bottom, you will see a textbox for naming your project; just use a self descriptive name like
‘MyFirstApp’. Also, you need to select a folder where your project’s file will be saved. The solution
name will be filled by default and you can leave it that way. Then click ‘OK’ to start the new project.
Windows Forms
VB.Net programmers have made extensive use of forms to build user interfaces. Each time you create
a Windows application, Visual Studio will display a default blank form, onto which you can drag and
drop controls from the Visual Studio Toolbox window.
The first step is to start a new project and build a form. Open your Visual Studio and select File-
>NewProject and select Visual Basic from the New project dialog box and select Windows Forms
Application. Enter your project name instead of WindowsApplication1 in the bottom of the dialog
box and click OK button. The following picture shows how to create a new Form in Visual Studio.
424
When you add a Windows Form to your project, many of the forms properties are set by default.
Although these values are convenient, they will not always suit your programming needs. The
following picture shows what the default Form looks like.
At the top of the form there is a title bar which displays the forms title. Form1 is the default name,
you can change the name to your convenience . The title bar also includes the control box, which
holds the minimize, maximize, and close buttons.
If you want to set any properties of the Form, you can use Visual Studio Property window to change
it.
Conclusion
At the end of the learning outcome, the trainee should be able to explain the .NET framework, install
Visual Studio, outline features of VB.NET, explain the VB.NET IDE environment, explain the
VB.NET program structure and create and compile a VB.NET project
Further reading
https://www.tutorialspoint.com/vb.net/
7.3.5.3 Self-Assessment
Written assessment
1. What are the components of the VB.NET IDE environment?
2. What is namespace?
3. Which data types does VB.NET support?
4. What is the role of a method in a VB.NET program
425
5. When is “new” keyword used in a VB.NET program?
Oral assessment
What are the .Net framework components?
Practical assessment
1. Write and compile VB.NET code to declare a variable to store the age of a person.
Then the output of the program is as an example shown below:
You are 20 years old.
2. Write VB.NET code to prompt a user to input his/her name and then the output will be shown
as shown in the example below:
Hello John!
7.3.5.5 References
1. https://visualstudio.microsoft.com/
2. http://vb.net-informations.com/gui/vb.net_vside.htm
3. http://vb.net-informations.com/gui/windows_forms.htm
426
7.3.6 Learning outcome 5: Develop and test a VB.NET application
7.3.6.1 Learning Activities
Learning Outcome 5: Develop and test a VB.NET application
Learning Activities Special Instructions
5.1 Basic VB.Net Controls are outlined Activities may be carried out in
5.2 Elements of a control are explained groups or as individual
5.3 Basic VB.Net Controls’ Properties, Methods and Events
are demonstrated
5.4 Event handling is demonstrated
5.5 Forms design using HCI principles is demonstrated
5.6 Connection of VB.Net applications to a database is
demonstrated
Introduction
This learning outcome covers outlining Basic VB.Net Controls, explaining elements of a control,
demonstrating basic VB.Net Controls’ Properties, Methods and Events event handling and forms
design using HCI principles and connection of VB.Net applications to a database.
Elements of a control
Basic control consists of three important elements −
● Properties which describe the object,
● Methods cause an object to do something and
● Events are what happens when an object does something.
Control Properties
All the Visual Basic Objects can be moved, resized or customized by setting their properties. A
property is a value or characteristic held by a Visual Basic object, such as Caption or Fore Color.
Properties can be set at design time by using the Properties window or at run time by using statements
in the program code. Object.Property=Value
Where
427
● Object is the name of the object you're customizing.
● Property is the characteristic you want to change.
● Value is the new property setting.
Control Methods
A method is a procedure created as a member of a class and they cause an object to do something.
Methods are used to access or manipulate the characteristics of an object or a variable. There are
mainly two categories of methods you will use in your classes −
● If you are using a control such as one of those provided by the Toolbox, you can call any of
its public methods. The requirements of such a method depend on the class being used.
● If none of the existing methods can perform your desired task, you can add a method to a
class.
For example, the MessageBox control has a method named Show, which is called in the code snippet
below
Control Events
An event is a signal that informs an application that something important has occurred. For example,
when a user clicks a control on a form, the form can raise a Click event and call a procedure that
handles the event. There are various types of events associated with a Form like click, double click,
close, load, resize, etc.
Following is the default structure of a form Load event handler subroutine. You can see this code by
double clicking the code which will give you a complete list of the all events associated with Form
control −
Here, Handles MyBase.Load indicates that Form1_Load() subroutine handles Load event. Similar
way, you can check stub code for click, double click. If you want to initialize some variables like
properties, etc., then you will keep such code inside Form1_Load() subroutine. Here, important point
to note is the name of the event handler, which is by default Form1_Load, but you can change this
name based on your naming convention you use in your application programming.
428
Form Design Using Basic Controls
VB.Net provides a huge variety of controls that help you to create rich user interface. Functionalities
of all these controls are defined in the respective control classes. The control classes are defined in
the System.Windows.Forms namespace.
Event Handling
Events are basically a user action like key press, clicks, mouse movements, etc., or some occurrence
like system generated notifications. Applications need to respond to events when they occur.
Clicking on a button, or entering some text in a text box, or clicking on a menu item, all are examples
of events. An event is an action that calls a function or may cause another event. Event handlers are
functions that tell how to respond to an event.
429
• MouseLeave − it occurs when the mouse pointer leaves the control
• MouseMove − it occurs when the mouse pointer moves over the control
• MouseUp − it occurs when the mouse pointer is over the control and the mouse button is
released
• MouseWheel − it occurs when the mouse wheel moves and the control has focus
The event handlers of the mouse events get an argument of type MouseEventArgs. The
MouseEventArgs object is used for handling mouse events. It has the following properties −
• Buttons − indicates the mouse button pressed
• Clicks − indicates the number of clicks
• Delta − indicates the number of detents the mouse wheel rotated
• X − indicates the x-coordinate of mouse click
• Y − indicates the y-coordinate of mouse click
Example:
Following is an example, which shows how to handle mouse events. Take the following steps −
• Add three labels, three text boxes and a button control in the form.
• Change the text properties of the labels to - Customer ID, Name and Address, respectively.
• Change the name properties of the text boxes to txtID, txtName and txtAddress, respectively.
• Change the text property of the button to 'Submit'.
• Add the following code in the code editor window −
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Set the caption bar text of the form.
Me.Text = "tutorialspont.com"
End Sub
430
Private Sub txtName_MouseEnter(sender As Object, e As EventArgs) _
Handles txtName.MouseEnter
'code for handling mouse enter on Name textbox
txtName.BackColor = Color.CornflowerBlue
txtName.ForeColor = Color.White
End Sub
431
Try to enter text in the text boxes and check the mouse events −
The event handlers of the KeyDown and KeyUp events get an argument of type KeyEventArgs.
This object has the following properties −
• Alt − it indicates whether the ALT key is pressed
• Control − it indicates whether the CTRL key is pressed
• Handled − it indicates whether the event is handled
• KeyCode − stores the keyboard code for the event
• KeyData − stores the keyboard data for the event
• KeyValue − stores the keyboard value for the event
• Modifiers − it indicates which modifier keys (Ctrl, Shift, and/or Alt) are pressed
• Shift − it indicates if the Shift key is pressed
The event handlers of the KeyDown and KeyUp events get an argument of type KeyEventArgs.
This object has the following properties −
432
• Handled − indicates if the KeyPress event is handled
• KeyChar − stores the character corresponding to the key pressed
Example
Let us continue with the previous example to show how to handle keyboard events. The code will
verify that the user enters some numbers for his customer ID and age.
• Add a label with text Property as 'Age' and add a corresponding text box named txtAge.
• Add the following codes for handling the KeyUP events of the text box txtID.
433
If you leave the text for age or ID as blank or enter some non-numeric data, it gives a warning
message box and clears the respective text −
The data residing in a data store or database is retrieved through the data provider. Various
components of the data provider retrieve data for the application and update data.
An application accesses data either through a dataset or a data reader.
434
• Datasets store data in a disconnected cache and the application retrieves data from it.
• Data readers provide data to the application in a read-only and forward-only mode.
Data Provider
A data provider is used for connecting to a database, executing commands and retrieving data,
storing it in a dataset, reading the retrieved data and updating the database.
The data provider in ADO.Net consists of the following four objects −
. Objects & Description
1 Connection
This component is used to set up a connection with a data source.
2 Command
A command is a SQL statement or a stored procedure used to retrieve, insert, delete
or modify data in a data source.
3 DataReader
Data reader is used to retrieve data from a data source in a read-only and forward-
only mode.
4 DataAdapter
This is integral to the working of ADO.Net since data is transferred to and from a
database through a data adapter. It retrieves data from a database into a dataset and
updates the database. When changes are made to the dataset, the changes in the
database are actually done by the data adapter.
DataSet
DataSet is an in-memory representation of data. It is a disconnected, cached set of records that are
retrieved from a database. When a connection is established with the database, the data adapter
creates a dataset and stores data in it. After the data is retrieved and stored in a dataset, the connection
with the database is closed. This is called the 'disconnected architecture'. The dataset works as a
virtual database containing tables, rows, and columns.
435
The following diagram shows the dataset object model −
The DataSet class is present in the System.Data namespace. The following table describes all the
components of DataSet −
Components & Description
1 DataTableCollection
It contains all the tables retrieved from the data source.
2 DataRelationCollection
It contains relationships and the links between tables in a data set.
3 ExtendedProperties
It contains additional information, like the SQL statement for retrieving data, time
of retrieval, etc.
4 DataTable
It represents a table in the DataTableCollection of a dataset. It consists of the
DataRow and DataColumn objects. The DataTable objects are case-sensitive.
5 DataRelation
It represents a relationship in the DataRelationshipCollection of the dataset. It is
used to relate two DataTable objects to each other through the DataColumn objects.
6 DataRowCollection
It contains all the rows in a DataTable.
7 DataView
436
It represents a fixed customized view of a DataTable for sorting, filtering,
searching, editing and navigation.
8 PrimaryKey
It represents the column that uniquely identifies a row in a DataTable.
9 DataRow
It represents a row in the DataTable. The DataRow object and its properties and
methods are used to retrieve, evaluate, insert, delete, and update values in the
DataTable. The NewRow method is used to create a new row and the Add method
adds a row to the table.
10 DataColumnCollection
It represents all the columns in a DataTable.
11 DataColumn
It consists of the number of columns that comprise a DataTable.
Connecting to a Database
The .Net Framework provides two types of Connection classes −
• SqlConnection − designed for connecting to Microsoft SQL Server.
• OleDbConnection − designed for connecting to a wide range of databases, like Microsoft
Access and Oracle.
Example 1
We have a table stored in Microsoft SQL Server, named Customers, in a database named testDB.
Please consult 'SQL Server' tutorial for creating databases and database tables in SQL Server.
• Select a server name and the database name in the Add Connection dialog box.
437
• Click on the Test Connection button to check if the connection succeeded.
438
• This opens the Data Source Configuration Wizard.
• Select Database as the data source type
439
• Save the connection string.
• Choose the database object, Customers table in our example, and click the Finish button.
• Select the Preview Data link to see the data in the Results grid −
440
When the application is run using Start button available at the Microsoft Visual Studio tool bar, it
will show the following window −
Example 2
In this example, let us access data in a DataGridView control using code. Take the following steps
−
• Add a DataGridView control and a button in the form.
• Change the text of the button control to 'Fill'.
• Double click the button control to add the required code for the Click event of the button, as
shown below −
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) _
Handles MyBase.Load
'TODO: This line of code loads data into the 'TestDBDataSet.CUSTOMERS'
table.
You can move, or remove it, as needed.
441
Me.CUSTOMERSTableAdapter.Fill(Me.TestDBDataSet.CUSTOMERS)
' Set the caption bar text of the form.
Me.Text = "VB.NET "
End Sub
• Clicking the Fill button displays the table on the data grid view control −
442
Creating Table, Columns and Rows
We have discussed that the DataSet components like DataTable, DataColumn and DataRow allow
us to create tables, columns and rows, respectively.
The following example demonstrates the concept −
Example 3
So far, we have used tables and databases already existing in our computer. In this example, we will
create a table, add columns, rows and data into it and display the table using a DataGridView object.
Take the following steps −
• Add a DataGridView control and a button in the form.
• Change the text of the button control to 'Fill'.
• Add the following code in the code editor.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Set the caption bar text of the form.
Me.Text = "tutorialspont.com"
End Sub
445
copied to the target computer to a folder you specified when you created the installer. In
addition, entries are added to the Start menu and optionally to the desktop so that the end
user can run the application. The installer will also copy related support files such as Help
files, data files, or other informational files. The target computer need not have Visual
Studio installed. This is one of the main goals of building a Setup project
Deployment Steps
To deploy an application so that the end user can install it on the target computer, you begin by
opening an existing Visual Basic solution and project. No matter the type of project being deployed,
you perform a similar set of steps, as described in the following list:
1. Open an existing solution containing one or more projects.
2. Create a Setup project within the solution.
3. Configure the Setup project by specifying the type of project being deployed along with any
support files that need to be deployed with the project. In addition, it is possible to define where
the executable files will be placed on the target computer, and any items to be created on the target
computer’s Start menu.
4. Build the Setup project to create the installer (Setup.exe and related files). Note that you build a
Setup project in the same way that you build a Windows Application project.
5. Test the Setup project on the local computer.
6. Distribute the Setup.exe program and any necessary files to the end user via removable media,
the Internet, or a company intranet.
Conclusion
At the end of the learning outcome, the trainee should be able to demonstrate basic VB.Net basic
controls’ properties, methods and events, event handling, connection of VB.Net applications to a
database and deployment of VB.NET applications.
Further reading
https://www.tutorialspoint.com/vb.net
7.3.6.3 Self-Assessment
Written assessment
1. Outline Basic VB.Net Controls
2. Explain Elements of a control
3. What are the standard naming conventions for controls
4. What is an event handler?
5. Why does a VB.NET application require deployment?
446
Oral Assessment
Outline the steps of connecting a VB.NET application to a database
Practical Assessment
Develop a simple VB.NET application to capture a student’s details. Using it demonstrate simple
but useful event handling, database connectivity and deployment.
7.3.6.5 References
https://www.tutorialspoint.com/vb.net/
447
CHAPTER 8: NETWORKING AND DISTRIBUTED SYSTEMS
8.1 Introduction
This unit covers the competencies required to understand network and distributed systems. It
involves understanding networking and distributed systems concepts, understanding distributed
systems architectures, understanding distributed processing and file management, setting up a
network in a distributed environment and troubleshooting a network.
448
8.3.2 Learning Outcome 1: Understand networking and distributed systems concepts
8.3.2.1 Learning Activities
Learning Outcome No.1: Understand networking and distributed systems concepts
·
8.3.2.1 Information Sheet No. 8/LO1: Understand networking and distributed systems concepts
Introduction
Fundamentals of networking
Definition of network
A network consists of two or more computers that are linked in order to share resources (such as
printers and CDs), exchange files, or allow electronic communications. The computers on a
network may be linked through cables, telephone lines, radio waves, satellites, or infrared light
beams.
449
LAN
It stands for Local Area Network and covers a small area such as a small office or home. It
physically connects all the computers located in the premises.
Internet
It is a computer network system that connects the computers of the world. It is normally connecting
through WAN and LAN.
Intranet
It is a close room computer network system, as it covers a small area and only authorized people
can access it.
Extranet
It is also a sort of Internet the access to which is granted only to a few.
Web log
It is a sort of online inventory (normally on a specialized topics) that consists of a series of entries.
These entries are arranged in opposite chronological order. The person who maintains the weblog
regularly update it with a new information.
Podcast
It is a digital file that normally contains audio or video record and is available on the Internet as
well.
Chat Rooms
It is a dedicated area on the Internet that facilitates users to communicate.
450
Public Switched Telephone Network (PSTN)
It is a technical expression for public telephone system.
Download
It is a process that saves data from Internet onto a personal computer.
Upload
It is a process that transfers the saved data from a personal computer to Internet server.
Dial-up
It is a technique in which a phone line is used in order to connect to the Internet.
Broadband
It is a wide bandwidth data transmission that transports multiple signals and traffic types swiftly.
Network components
451
NIC is a device that helps the computer to communicate with another device. The network interface
card contains the hardware addresses, the data-link layer protocol use this address to identify the
system on the network so that it transfers the data to the correct destination.
There are two types of NIC: wireless NIC and wired NIC.
Wireless NIC: All the modern laptops use the wireless NIC. In Wireless NIC, a connection is made
using the antenna that employs the radio wave technology. Wired NIC: cables use the wired NIC
to transfer the data over the medium.
Hub
Hub is a central device that splits the network connection into multiple devices. When computer
requests for information from a computer, it sends the request to the Hub. Hub distributes this
request to all the interconnected computers.
Switches
Switch is a networking device that groups all the devices over the network to transfer the data to
another device. A switch is better than Hub as it does not broadcast the message over the network,
i.e., it sends the message to the device for which it belongs to. Therefore, we can say that switch
sends the message directly from source to the destination.
Twisted pair cable: It is a high-speed cable that transmits the data over 1Gbps or more.
Coaxial cable: Coaxial cable resembles like a TV installation cable. Coaxial cable is more
expensive than twisted pair cable, but it provides the high data transmission speed.
Fibre optic cable: Fibre optic cable is a high-speed cable that transmits the data using light beams.
It provides high data transmission speed as compared to other cables. It is more expensive as
compared to other cables, so it is installed at the government level.
Router
Router is a device that connects the LAN to the internet. The router is mainly used to connect the
distinct networks or connect the internet to multiple computers.
Modem
Modem connects the computer to the internet over the existing telephone line. A modem is not
integrated with the computer motherboard. A modem is a separate part on the PC slot found on the
motherboard.
452
• Resource sharing: Resource sharing is the sharing of resources such as programs, printers,
and data among the users on the network without the requirement of the physical location
of the resource and user.
• Server-Client model: Computer networking is used in the server-client model. A server is
a central computer used to store the information and maintained by the system
administrator. Clients are the machines used to access the information stored in the server
remotely.
• Communication medium: Computer network behaves as a communication medium
among the users. For example, a company contains more than one computer has an email
system which the employees use for daily communication.
• E-commerce: Computer network is also important in businesses. We can do the business
over the internet. For example, amazon.com is doing their business over the internet, i.e.,
they are doing their business over the internet.
Types of networks
Local Area Network (LAN)
• LAN is a group of computers connected to each other in a small area such as building,
office.
• Used for connecting two or more personal computers through a communication medium
such as twisted pair, coaxial cable, etc.
• It is less costly as it is built with inexpensive hardware such as hubs, network adapters,
and Ethernet cables.
• The data is transferred at an extremely faster rate.
• LAN provides higher security.
Figure 95:LAN
Figure 96:MAN
Figure 97:WAN
Network topologies
Topology defines the structure of the network of how all the components are interconnected to each
other. There are two types of topology: physical and logical topology.
Star topology
• Star topology is an arrangement of the network in which every node is connected to the
central hub, switch or a central computer.
• The central computer is known as a server, and the peripheral devices attached to the
server are known as clients.
• Coaxial cable or RJ-45 cables are used to connect the computers.
• Hubs or Switches are mainly used as connection devices in a physical star topology.
• Star topology is the most popular topology in network implementation.
Ring topology
• Ring topology is like a bus topology, but with connected ends.
• The node that receives the message from the previous computer will retransmit to the next
node.
• The data flows in one direction, i.e., it is unidirectional.
• The data flows in a single loop continuously known as an endless loop.
• It has no terminated ends, i.e., each node is connected to other node and having no
termination point.
• The data in a ring topology flow in a clockwise direction.
• The most common access method of the ring topology is token passing.
Token passing: It is a network access method in which token is passed from one node to another
node.
Token: It is a frame that circulates around the network.
Mesh topology
• Mesh technology is an arrangement of the network in which computers are interconnected
with each other through various redundant connections.
• There are multiple paths from one computer to another computer.
• It does not contain the switch, hub or any central computer which acts as a central point of
communication.
• The Internet is an example of the mesh topology.
• Mesh topology is mainly used for WAN implementations where communication failures
are a critical concern.
• Mesh topology is mainly used for wireless networks.
• Mesh topology can be formed by using the formula:
Number of cables = (n*(n-1))/2;
• Where n is the number of nodes that represents the network.
457
Figure 101:Mesh topology
Bus topology
• The bus topology is designed in such a way that all the stations are connected through a
single cable known as a backbone cable.
• Each node is either connected to the backbone cable by drop cable or directly connected
to the backbone cable.
• When a node wants to send a message over the network, it puts a message over the
network. All the stations available in the network will receive the message whether it has
been addressed or not.
• The bus topology is mainly used in 802.3 (Ethernet) and 802.4 standard networks.
• The configuration of a bus topology is quite simpler as compared to other topologies.
• The backbone cable is considered as a "single lane" through which the message is
broadcast to all the stations.
458
• The most common access method of the bus topologies is CSMA (Carrier Sense Multiple
Access).
• CSMA: It is a media access control used to control the data flow so that data integrity is
maintained, i.e., the packets do not get lost. There are two alternative ways of handling
the problems that occur when two nodes send the messages simultaneously.
• CSMA CD: CSMA CD (Collision detection) is an access method used to detect the
collision. Once the collision is detected, the sender will stop transmitting the data.
Therefore, it works on "recovery after the collision".
• CSMA CA: CSMA CA (Collision Avoidance) is an access method used to avoid the
collision by checking whether the transmission media is busy or not. If busy, then the
sender waits until the media becomes idle. This technique effectively reduces the
possibility of the collision. It does not work on "recovery after the collision".
459
• Attenuation: Attenuation is a loss of signal leads to communication issues. Repeaters are
used to regenerate the signal.
Transmission media
Transmission media is a communication channel that carries the information from the sender to
the receiver. Data is transmitted through the electromagnetic signals.
Wired media
Also referred to as guided media. Signals being transmitted are directed and confined in a narrow
pathway by using physical links.
Features:
• High Speed
• Secure
• Used for comparatively shorter distances
There are 3 major types of Wired Media:
• Twisted pair cables
• Coaxial cables
• Optic fibre cables
(i) Twisted Pair Cable
It consists of 2 separately insulated conductor wires wound about each other. Generally, several
such pairs are bundled together in a protective sheath. They are the most widely used
transmission Media.
Advantages:
• Least expensive
• Easy to install
• High speed capacity
Disadvantages:
• Susceptible to external interference
• Lower capacity and performance in comparison to STP
• Short distance transmission due to attenuation
b) Shielded Twisted Pair (STP):
This type of cable consists of a special jacket to block external interference. It is used in fast-
data-rate Ethernet and in voice and data channels of telephone lines.
Advantages:
460
• Better performance at a higher data rate in comparison to UTP
• Eliminates crosstalk
• Comparatively faster
Disadvantages:
• Comparatively difficult to install and manufacture
• More expensive
• Bulky
(ii) Coaxial Cable
It has an outer plastic covering containing 2 parallel conductors each having a separate insulated
protection cover. Coaxial cable transmits information in two modes:
• Baseband mode(dedicated cable bandwidth) and;
• Broadband mode (cable bandwidth is split into separate ranges). Cable TVs and analog
television networks widely use Coaxial cables.
Advantages:
• High Bandwidth
• Better noise Immunity
• Easy to install and expand
• Inexpensive
Disadvantages:
• Single cable failure can disrupt the entire network
(iii) Optical Fibre Cable
It uses the concept of reflection of light through a core made up of glass or plastic. The core is
surrounded by a less dense glass or plastic covering called the cladding. It is used for
transmission of large volumes of data.
Advantages:
• Increased capacity and bandwidth
• Light weight
• Less signal attenuation
• Immunity to electromagnetic interference
• Resistance to corrosive materials
Disadvantages:
• Difficult to install and maintain
• High cost
• Fragile
• unidirectional, i.e., will need another fibre, if we need bidirectional communication
Wireless media
It is also referred to as unguided or unbounded transmission media. No physical medium is
required for the transmission of electromagnetic signals.
Features:
• Signal is broadcasted through air
461
• Less Secure
• Used for larger distances
(ii) Microwaves
• It is a line of sight transmission i.e. the sending and receiving antennas need to be
properly aligned with each other.
• The distance covered by the signal is directly proportional to the height of the antenna.
Frequency Range:1GHz – 300GHz.
• These are majorly used for mobile phone communication and television distribution.
(iii) Infrared
• Infrared waves are used for very short distance communication.
• They cannot penetrate through obstacles.
• This prevents interference between systems. Frequency Range: 300GHz – 400THz. It is
used in TV remotes, wireless mouse, keyboard, printer, etc.
Distributed systems
Definition
A distributed system contains multiple nodes that are physically separate but linked together
using the network. All the nodes in this system communicate with each other and handle
processes in tandem. Each of these nodes contains a small part of the distributed operating system
software.
Computing
• Distributed computing is a computing concept that, in its most general sense, refers to
multiple computer systems working on a single problem.
• In distributed computing, a single problem is divided into many parts, and each part is
solved by different computers. As long as the computers are networked, they can
communicate with each other to solve the problem. If done properly, the computers
perform like a single entity.
462
• The ultimate goal of distributed computing is to maximize performance by connecting
users and IT resources in a cost-effective, transparent and reliable manner.
• It also ensures fault tolerance and enables resource accessibility in the event that one of
the components fails.
Information
• A set of information systems physically distributed over multiple sites, which are
connected with some kind of communication network.
• A system where, applications (cooperative among one another) stay on different
elaborative nodes and the information property, unique, is hosted on different elaborative
nodes
Pervasive
• Pervasive computing, also called ubiquitous computing, is the growing trend of
embedding computational capability (generally in the form of microprocessors) into
everyday objects to make them effectively communicate and perform useful tasks in a
way that minimizes the end user's need to interact with computers as computers.
• Pervasive computing devices are network-connected and constantly available.
• Unlike desktop computing, pervasive computing can occur with any device, at any time,
in any place and in any data format across any network and can hand tasks from one
computer to another as, for example, a user moves from his car to his office. Pervasive
computing devices have evolved to include:
o laptops;
o notebooks;
o smartphones;
o tablets;
o wearable devices;
o And sensors (for example, on fleet management and pipeline components, lighting
systems, appliances).
Architectural model
Architectural model describes responsibilities distributed between system components and how
are these components placed.
a) Client-Server Model
• The model is structured as a set of processes, called servers that offer services to the
users, called clients.
463
• The client-server model is usually based on a simple request/reply protocol, implemented
with send/receive primitives or using remote procedure calls (RPC) or remote method
invocation (RMI):
• The client sends a request (invocation) message to the server asking for some service;
• The server does the work and returns a result (e.g. the data requested) or an error code if
the work could not be performed.
A server can itself request services from other servers; thus, in this new relation, the server itself
acts like a client.
b) Peer-to-peer model
• All processes (objects) play similar role.
• Processes (objects) interact without particular distinction between clients and servers.
• The pattern of communication depends on the particular application.
• A large number of data objects are shared; any individual computer holds only a small
part of the application database.
• Processing and communication loads for access to objects are distributed across many
computers and access links.
• This is the most general and flexible model.
464
Figure 104:Peer-to-peer Distributed Model
Interaction model
Interaction model are for handling time i. e. for process execution, message delivery, clock drifts
etc.
Main features:
• Lower and upper bounds on execution time of processes can be set.
• Transmitted messages are received within a known bounded time.
• Drift rates between local clocks have a known bound.
Important consequences:
• In a synchronous distributed system there is a notion of global physical time (with a
known relative precision depending on the drift rate).
• Only synchronous distributed systems have a predictable behavior in terms of timing.
Only such systems can be used for hard real-time applications.
• In a synchronous distributed system it is possible and safe to use timeouts in order to
detect failures of a process or communication link.
• It is difficult and costly to implement synchronous distributed systems.
Important consequences:
• In an asynchronous distributed system there is no global physical time. Reasoning can be
only in terms of logical time (see lecture on time and state).
• Asynchronous distributed systems are unpredictable in terms of timing.
465
• No timeouts can be used.
• Asynchronous systems are widely and successfully used in practice.
• In practice timeouts are used with asynchronous systems for failure detection.
• However, additional measures have to be applied in order to avoid duplicated messages,
duplicated execution of operations, etc.
Fault model
• Failures can occur both in processes and communication channels. The reason can be both
software and hardware faults.
• Fault models are needed in order to build systems with predictable behavior in case of
faults (systems which are fault tolerant).
• Such a system will function according to the predictions, only as long as the real faults
behave as defined by the “fault model”.
Wired networks also offer security advantages over wireless networks, but most of the security
risks of wireless networks can be mitigated with advanced encryption and other wireless security
options.
The main advantage to deploying a wireless network, on the other hand, is simply the lack of
needing any wiring at all.
In most cases, a combination of both wired and wireless network connections will serve you best,
especially if your facility is already wired.
Once you've settled on a wireless standard you'll want to start researching and purchasing the
equipment you'll need for your wireless and/or wired network.
Note that in many cases you can purchase multi-function devices that combine router, access
point and hub or switch functionality in one single component.
2) Type of topology
Network topology refers to the physical configuration of a set of interconnected computing
devices. It details not just how devices on the network are connected but also how data moves
from one node to another.
a) Budget
• A rule of thumb is to never make technology procurement decisions based on price alone.
If a topology is unaffordable, it’s off the table no matter how perfectly suited it might be
for your situation.
• In any case, irrespective of what your preferred topology is, there’ll almost always be a
lower-priced alternative that’s nearly as effective. On pricing matters, bus and ring
topologies are quite cost-effective while star, mesh, tree and hybrid topologies are
expensive.
b) Hardware Resources
467
• Certain network topologies work best with certain hardware. And vise-versa. So before
you make a decision on the topology to adopt, perform an inventory of your current
hardware.
• You may also already have the hardware needed to implement a certain type of topology.
So as opposed to buying everything from scratch, such existing resources give you a head
start.
• For instance, you may have hardware limitations such as the length of the network cable.
In that case, you’d go for a topology that requires the least amount of cable for connecting
nodes. Bus and star topologies perform pretty well in this regard.
c) Ease of Implementation
• If you’ll contract a third party to install and/or maintain your network, then the
complexity of the network topology you choose is perhaps a non-issue. A competent
networking professional will have the education and experience needed to comprehend
what each topology entails and implement it accordingly.
• However, if you expect to leave network implementation in the hands of novices or
individuals without the requisite IT training, then the ease of the topology should be a
major factor in your choice. In this case, the bus and star topologies score pretty well. The
mesh, tree and hybrid, on the other hand, are complex and difficult for a layman to install
or understand.
d) Size of Network
• How many devices are going to be on your network? How geographically dispersed are
they? How far from the ‘center’ is the furthest device?
• Some topologies are inadequate or expensive when applied to large networks. A topology
that works perfectly for a 5-device network may prove a disaster when applied to a
10,000-device organization.
• Part of the inventorying process we referred to in point 2 should include determining the
total number of devices to be interconnected. Armed with this information, you can
choose the topology that would best serve the purpose.
• The tree topology works well with large networks. The bus topology is best suited for
small organizations.
d) Reliability
• When it comes to reliability, network topologies aren’t created equal. If you are looking
for high reliability because you are in an industry where even brief downtime and delays
are frowned upon (e.g. banking), then network reliability is a fundamental consideration.
Choose the topology that delivers the highest reliability.
• Ring topology performs pretty well under heavy loads but is prone to a single point of
failure. Star topology doesn’t depend on any node but the network will collapse if the hub
fails. Mesh and hybrid topologies score highest on the reliability front.
e) Future Expansion
468
• If you expect your organization to grow in size in the medium to long-term, opt for a
network topology that’s readily scalable. Identify the topology that’s easy to add new
nodes to, without negatively affecting network performance or the user experience of
other devices on the network.
• The tree topology is perhaps the most compatible with future expansion requirements as
it’s fairly easy to extend or shrink the network. The bus topology is also easy to expand
but only to a certain extent which is why it would only work for small networks.
• Choosing a network topology is one of the most important decisions you’ll make for your
technology infrastructure and will have far-reaching ramifications over the long-term. A
wrong choice can prove to be an expensive mistake. It’s a decision that requires careful
thought in order to get it right from the start.
3) Devices
• The backbone of your network is your hardware. All of the communications of your
network flow through your routers and switches.
• When these items aren't communicating at levels that you require, business is affected.
Very often, a negatively impacted network has financial ramifications.
• If you are building a network from scratch, purchasing the hardware that best fits your
business needs will set your network infrastructure up for success.
• If you are considering making hardware changes to an existing network, you need to be
able to prioritize your hardware upgrade needs. This prioritization process must reflect the
needs of your network.
4) Routers
Your router is where your internal network meets the outside world. It is an integral piece of your
network. All traffic destined for the outside world must travel through your routing equipment.
There are many different things to consider while choosing the best router for your business.
a) Class Level
Will a consumer or small office router work for your business? Or do you need a more expensive
product that offers more features? Cutting costs where you can is often a good idea, but is this the
spot to do it? Here are some things you consider in regards to router classes.
b) Maximum throughput. What speed capabilities does your business need? Some internet service
providers offer up to a gigabyte of internet bandwidth. Can your router handle anything close to
that? How are speeds affected when security services are enabled?
c) Level of support. What kind of support package does your router's manufacturer offer? Is it
included with purchase? If not, what is the pricing on support packages? When you run into
issues managing your router, it's good to know how to find help. You need to have an idea of the
level of support that you can expect.
469
d) Configurability. Consumer routers come with a lower level of configuration options than
enterprise-class routers. These options could include VPN configuration and port forwarding, to
name just a few.
e) Security Options
Your network's security is of the highest importance. While almost all routers come with at least a
basic level of security options and features, it's important to know that your router's features will
meet your needs.
5) Switches
While all traffic to and from the outside world goes through your router, all local communications
are handled by network switches. They are truly the backbone of your network.
It's important to know how manageable you need your switches to be, and the speeds and number
of ports that you will require.
a) Speeds
When shopping for switches, one oft-touted specification is link speed. There are three speed
classifications to consider, and only one that you should really be shopping for most of the time.
i) 10/100 mbps. This was once a usable speed on most networks, but is now
considered a slower option. Switches that offer these speeds can currently be
found on many networks running on older infrastructure. New network
installations should avoid using switches at these speeds.
ii) 1000 mbps (or 1 Gbps). This speed specification is a good meeting point
between speed requirements and cost effectiveness. While these switches
may cost more than the 10/100 mbps ones, most newer networks are able to
utilize these speeds, making the upgrade worth it.
470
iii) 10 Gbps. While these switches can be found in niche enterprise
environments, they are usually not necessary for an average business
network.
b) Management Features
There are two basic levels of management features for network switches: managed and
unmanaged. There are a few different reasons why you might choose one or the other.
6) Wireless Networks
More and more, network administrators are seeing wireless networks move from being an
ancillary part of the network to one that is just as important as the wired network. Administrators
should have a good understanding of wireless coverage through their network via mapping.
Additionally, they should take into consideration speed and security.
a) Network Map
Building a map helps administrators gain an understanding of the wireless coverage within their
network. Here's what you're looking to accomplish with your map.
• Wireless coverage. You need to have an understanding of what locations within your
building will have issues getting a strong connection to your wireless devices. With this
information, you can make adjustments to reduce these issues.
• Access point placement. Administrators need to know how many access points they will
need, and where they need to be placed within a network. Having a map helps to display
the best placement for these devices.
b) Wireless Speeds
471
As wireless technology develops, speed capabilities have become faster and faster. With the
growing demands of wireless networks in a business setting, it's almost always worth it to invest
in the fastest infrastructure possible.
There are 3 different speed classifications that most administrators work with today.
i) 802.11ac. As of today, this is the fastest speed classification available. Network administrators
who are purchasing new access points should be sure that the equipment they shop for supports
this technology.
ii) 802.11n. While this specification is quite fast, it is still slower than 802.11ac technology.
Existing infrastructure running at these speeds doesn’t necessarily need to be replaced, but it
should not be purchased for new installations.
iii) 802.11b/g. This specification is now fairly old, and fairly slow. Network administrators
should be actively replacing equipment that communicates at these speeds.
c) Security Considerations
Because your wireless network naturally increases the vulnerability of your infrastructure,
security must be taken extremely seriously.
7) Proprietary Hardware
Many businesses today must purchase proprietary hardware, as required by the industry that they
are working in. Choosing the right equipment can be difficult.
Conclusion
At the end of this learning outcome, the learner should be able to explain fundamentals of
networking, illustrate types of networks, network topologies, outline transmission media, explain
distributed systems, illustrate types of distributed systems and models in distributed systems and
specify network requirements for a site.
Further Reading
1. https://www.geeksforgeeks.org/types-of-area-networks-lan-man-and-wan/
2. http://ecomputernotes.com/computernetworkingnotes/computer-network/how-many-type-
of-computer-networking
3. https://fcit.usf.edu/network/chap1/chap1.htm
8.3.2.3 Self-Assessment
Written Assessment
Oral Assessment
1. What is a network and what are they key network components?
2. What are the main types of network and network topologies in networking?
3. What do you understand by the term distributed computing?
4. What are the main types of distributed computing systems?
5. What are the benefits and applications of networking?
6. Why would you design a system as a distributed system? List some advantages of
distributed systems.
Practical Assessment
Design network to demonstrate the following topologies below
• Star
• Ring
474
• Mesh
• Bus
8.3.2.5 References
1. https://www.javatpoint.com/types-of-computer-network
2. https://www.techopedia.com/definition/7/distributed-computing-system
3. https://techdifferences.com/difference-between-active-and-passive-attacks.html
4. https://www.us-cert.gov/ncas/tips/ST05-003
5. https://www.meldium.com/6-factors-when-choosing-a-network-topology/
475
8.3.3 Learning Outcome 2: Understand Distributed Systems Architectures
8.3.3.1 Learning Activities
Learning Outcome No.2: Understand Distributed Systems Architectures
Introduction
This learning outcome covers illustrating distributed architecture, architecture styles, types of
distributed system architectures and specifying distributed system architecture requirements for a
simulated site.
Distributed architecture
Definitions
Distributed architecture
Distributed system architectures are bundled up with components and connectors. Components can
be individual nodes or important components in the architecture whereas connectors are the ones
that connect each of these components.
Component: A modular unit with well-defined interfaces; replaceable; reusable
Connector: A communication link between modules which mediates coordination or cooperation
among components
Application: Distributed application is software that is executed or run on multiple computers within
a network. These applications interact in order to achieve a specific goal or task. Traditional
applications relied on a single system to run them. Even in the client-server model, the application
software had to run on either the client, or the server that the client was accessing. However,
distributed applications run on both simultaneously.
With distributed applications, if a node that is running a particular application goes down, another
node can resume the task.
Architecture styles:
476
Layered Architecture
● The layered architecture separates layers of components from each other, giving it a
much more modular approach.
● A well-known example for this is the OSI model that incorporates a layered
architecture when interacting with each of the components. Each interaction is
sequential where a layer will contact the adjacent layer and this process continues,
until the request is been catered to.
● In certain cases, the implementation can be made so that some layers will be
skipped, which is called cross-layer coordination. Through cross-layer coordination,
one can obtain better results due to performance increase.
● The layers on the bottom provide a service to the layers on the top. The request
flows from top to bottom, whereas the response is sent from bottom to top.
● The advantage of using this approach is that, the calls always follow a predefined
path, and that each layer can be easily replaced or modified without affecting the
entire architecture.
● This architecture style is based on loosely coupled arrangement of objects. This has
no specific architecture like layers.
● Like in layers, this does not have a sequential set of steps that needs to be carried out
for a given call.
● Each of the components are referred to as objects, where each object can interact
with other objects through a given connector or interface. These are much more
direct where all the different components can interact directly with other components
through a direct method call.
● This architecture style is less structured.
○ component = object
○ connector = RPC or RMI
Some popular examples are Java RMI, Web Services and REST API Calls. This has the following
properties.
Data-centered Architecture
477
● All the information related to the nodes in the system are stored in this persistent
storage. In event-based architectures, data is only sent and received by those
components who have already subscribed.
● Some popular examples are distributed file systems, producer consumer, and web
based data services.
Hybrid
479
Many distributed systems combine architectural features. Below we look at the edge-server model
which client-server solutions are combined with decentralized architectures.
Edge-Server Systems
● An important class of distributed systems that is organized according to a hybrid
architecture is formed by edge-server systems.
● These systems are deployed on the Internet where servers are placed "at the edge" of
the network. This edge is formed by the boundary between enterprise networks and
the actual Internet, for example, as provided by an Internet Service Provider (ISP).
● Likewise, where end users at home connect to the Internet through their ISP, the ISP
can be considered as residing at the edge of the Internet. This leads to a general
organization as shown in figure below.
Viewing the Internet as consisting of a collection of edge servers.
● End users, or clients in general, connect to the Internet by means of an edge server.
The edge server's main purpose is to serve content, possibly after applying filtering
and transcoding functions.
● The basic model is that for a specific organization, one edge server acts as an origin
server from which all content originates. That server can use other edge servers for
replicating Web pages and such.
a) Quality of Service
● Reliability (the ability of a system to perform and maintain its function in every
circumstance).
● Performance
● Adaptability (the ability of a system to adapt itself efficiently and fast to changed
circumstances)
● Resource Availability
480
● Some applications handle time-critical data– streams of data that are required to be
processed or transferred from one process to another at a fixed rate.
b) Caching and Replication
● Cached copies of resources should be kept up-to-date when the resource at a server
is updated.
● A variety of cache-coherency protocols are used to suit different applications.
c) Web Caching Protocol
● Web browsers and proxy servers cache responses to client requests from web servers
● The cache-consistency protocol can provide browsers with fresh copies of the
resources held by the web server, but for performance reasons the freshness
condition can be relaxed.
● A browser or proxy can validate a datum with the server.
● Web servers assign approximate expiry times to their resources
● The expiry time of the resource and the current time at the server are attached to the
response.
d) Dependability Issues
● Dependable applications should continue to function correctly in the presence of
faults in hardware, software and networks.
e) Attributes
● Availability – readiness for correct service
● The ratio of the total time a functional unit is capable of being used during a given
interval to the length of the interval
● Reliability
● The probability that a device will perform its intended function during a specified
period of time under stated conditions
● Replication
● Multiple computers – multiple communication paths
● Retransmission of messages, etc.
f) Safety – absence of incorrect behavior
g) Integrity – absence of improper system alteration
h) Maintainability – ability to undergo modifications and repairs,
Correct defects, meet new requirements
i) Performance Issues
● Response Time – time system takes to process a request.
● Responsiveness – how quickly system acknowledges a request (as opposed to
processing it)
● Throughput – rate at which work gets done
● Latency – time needed to accomplish remote requests
● Note that “performance” can be viewed from conflicting perspectives (throughput
vs. response time)
ii) Type of distributed system architectures
i) Performance
481
● While defining the functions or services that make up a solution, the developers
should be aware if they have significant processing, memory or storage
requirements. It might be wise to look at these functions closely to learn if that can
be further subdivided or decomposed.
● Further segmentation would allow an increase in parallelization which would
potentially offer performance improvements. The trade off, of course, is that this
approach also increases complexity and, potentially, makes them harder to manage
and to make secure.
ii) Reliability
● In high stakes enterprise environments, solution reliability is essential. The
developer must consider when it is acceptable to force people to re-enter data, re-run
a function, or when a function can be unavailable.
● Functions must be designed to totally complete or roll back intermediate updates. In
critical message passing systems, messages must be stored until an
acknowledgement that a message has been received comes in. If such a message
isn’t received, the original message must be resent and a failure must be reported to
the management system.
iii) Manageability
● All distributed functions must be fully equipped to allow administrators to
understand their current state. After all, distributed systems are inherently more
complex and have more moving parts than the monolithic systems they replace.
iv) Security
● Distributed system security is an order of magnitude more difficult than security in a
monolithic environment.
● Each function must be made secure separately and the communication links between
and among the functions must also be made secure. As the network grows in size
and complexity, developers must consider how to control access to functions, how to
make sure than only authorized users can access these function, and to isolate
services from one other.
● Security is a critical element that must be built into every function, not added on
later. Unauthorized access to functions and data must be prevented and reported.
v) Privacy
● Privacy is the subject of an increasing number of regulations around the world.
Examples like the European Union’s GDPR and the U.S. HIPPA regulations are
important considerations for any developer of customer-facing systems.
Conclusion
At the end of this learning outcome, the learner should be able to illustrate distributed architecture,
architecture styles, and types of distributed system architectures and specify distributed system
architecture requirements for a simulated site.
Further Reading
https://study.com/academy/lesson/architectural-patterns-for-distributed-systems-definition-
importance.html
482
8.3.3.3 Self-Assessment
Written Assessment
1. Architectural styles is composed of which of the following?
a) A set of component types that perform some function at run-time
b) A topological layout of these components indicating their run-time inter relationships
c) A set of semantic constraints
d) All of the mentioned
2. Which of the following term is best defined by the statement “In a distributed system, several
processes may operate at the same time on separate computers on the network.”?
a) Concurrency
b) Openness
c) Resource sharing
d) Fault tolerance
3. Which of the following is not a dimension of scalability?
a) Size
b) Distribution
c) Manageability
d) Interception
4. QoS stands for
a) Quality of security
b) Quality of system
c) Quality of service
d) None of the mentioned
5. Which architecture decentralized architectures in which there are no distinguished clients and
servers?
a) Multi-tier client–server architecture
b) Master-slave architecture
c) Distributed component architecture
d) Peer-to-peer architecture
6. Interprocessor communication takes place via
a) Shared memory
b) Message passing
c) Centralized memory
d) Both A and B
7. Providing Quality Service (QoS) assurance, even under failure conditions, is the responsibility of
a) Adaptation
b) Flexibility
c) Dependability
d) Efficiency
8. What role do peers serve as in a peer to peer architecture?
a) servers
b) middle system
483
c) clients
d) both A and B
Oral Assessment
1. What is the difference in the distributed architectures below?
● Layered Architecture
● Object Based Architecture
● Data-centred Architecture
Practical Assessment
Specify the distributed architecture requirements for microfinance bank with three branches across
three towns including the headquarters branch. There are the twenty users at the headquarters and
other 30 spread across the other two towns. There is a requirement to store and share data securely
across all branches as well as the need to efficiently communicate.
8.3.3.5 References
● https://keetmalin.wixsite.com/keetmalin/post/2017/09/27/distributed-system-architectures-
and-architectural-styles
484
8.3.4 Learning Outcome 3: Understand Distributed Processing and File Management
8.3.4.1Learning Activities
Learning Outcome No.3: Understand Distributed Processing and File Management
3.1 Types of distributed processing are Activities may be carried out in groups or as
illustrated individual
3.2 Types of file systems are illustrated
3.3 File sharing and accessing methods are
illustrated ·
3.4 Distributed file sharing and access is
demonstrated
8.3.4.2 Information Sheet No. 8/LO3: Understand Distributed Processing and File
Management
Introduction
This learning outcome covers illustrating types of distributed processing, types of file systems, file
sharing and accessing methods and demonstrating distributed file sharing.
Parallel processing
● The simultaneous use of more than one CPU to execute a program. Ideally, parallel
processing makes a program run faster because there are more engines (CPUs)
485
running it. In practice, it is often difficult to divide a program in such a way that
separate CPUs can execute different portions without interfering with each other.
● Most computers have just one CPU, but some models have several. There are even
computers with thousands of CPUs. With single-CPU computers, it is possible to
perform parallel processing by connecting the computers in a network. However,
this type of parallel processing requires very sophisticated software called distributed
processing software.
● Note that parallel processing differs from multitasking, in which a single CPU
executes several programs at once.
The type of file system is used to determine how data and programs are accessed. It also determines
the level of accessibility available to users.
Security
● FAT does not support local and folder security. A user logged on a computer locally
has full access to the files and folders in FAT partitions of the computer.
Quick Access to files
● FAT provides quick access to files. The speed of file access depends on file type, file
size, partition size, fragmentation and number of files in a folder.
486
FAT32 is an advanced version of FAT file system. It can be used on drives from 512 MB to 2TB
in size. One of the most important features of FAT and FAT32 is that they offer compatibility with
operating systems other than Windows 2000.
Access Speed
● FAT32 provides good file access in partition sizes less than 500 MB or greater than
2 GB. It provides better disk space utilization.
Security
● NTFS provides file and folder security. Files and folders are safer than FAT.
Security is maintained by assigning NTFS permissions to files and folders.
● Security is maintained at the local level and the network level.
● The permissions can be assigned to individual files and folders. Each file or folder in
an NTFS partition has an Access Control List. It contains the users and group
security identifier (SID) and the privileges granted to them.
Partition Size
● The NTFS partition and file sizes are much bigger than FAT partitions and files.
● The maximum size of an NTFS partition or file can be 16 Exabyte. However, the
practical limitation is two Terabytes. The file size can be in the range of 4GB to
64GB.
File compression
● NTFS provides file compression of as much as 50%.
High reliability
● NTFS is highly reliable. It is recoverable file system. It uses transaction logs to
update the file and folders logs automatically.
487
● The system also has a great amount of fault tolerance. It means that if transaction
fails due to power or system failure, the logged transactions are used to recover the
data.
You can access items in the cache using an indexer and may control the lifetime of objects in the
cache and set up links between the cached objects and their physical sources.
The design and implementation of a distributed file system is more complex than a conventional
file system due to the fact that the users and storage devices are physically dispersed.
In addition to the functions of the file system of a single-processor system, the distributed file
system supports the following:
1. Remote information sharing- Any node, irrespective of the physical location of the file, can
access the file.
2. User mobility- User should be permitted to work on different nodes.
3. Availability- For better fault-tolerance, files should be available for use even in the event of
temporary failure of one or more nodes of the system. Thus the system should maintain multiple
copies of the files, the existence of which should be transparent to the user.
488
4. Diskless workstations- A distributed file system, with its transparent remote-file accessing
capability, allows the use of diskless workstations in a system.
489
● A highly reliable and scalable distributed file system should have multiple and
independent file servers controlling multiple and independent storage devices.
7. High reliability
● Probability of loss of stored data should be minimized. System should automatically
generate backup copies of critical files.
8. Data integrity
● Concurrent access requests from multiple users who are competing to access the file
must be properly synchronized by the use of some form of concurrency control
mechanism. Atomic transactions can also be provided.
9. Security
● Users should be confident of the privacy of their data.
10. Heterogeneity
● There should be easy access to shared data on diverse platforms
Conclusion
At the end of this learning outcome, the learner should be able to illustrate types of distributed
processing, types of file systems, file sharing and accessing methods and demonstrate distributed
file sharing.
Further Reading
1. https://byte-notes.com/types-of-file-systems/
2. https://www.webopedia.com/TERM/D/distributed_processing.html
8.3.4.3 Self-Assessment
Written Assessment
1. ______ is a unique tag, usually a number identifies the file within the file system.
a) File identifier
b) File name
c) File type
d) None of the mentioned
490
a) complex
b) simple
c) sequential
d) combinational
5. A paradigm of multiple autonomous computers, having a private memory, communicating
through a computer network, is known as
a) Distributed computing
b) Cloud computing
c) Centralized computing
d) Parallel computing
6. What is the characteristics of NFS protocol?
a) search for file within directory
b) read asset of directory entries
c) manipulate links and directories
d) all of the mentioned
7. What are the advantages of file replication?
a) Decreases performance
b) Improves availability and performance
c) Improves speed
d) They are consistent
Oral Assessment
Practical Assessment
From a LAN set up, verify the file system being used. Additionally verify how file location and
naming transparency is implemented in the set up to confirm that it is a distributed set up.
491
8.3.5 Learning Outcome 4: Set up a Network in a Distributed Environment
8.3.5.1 Learning Activities
4.1 Tools, materials and devices for network set up are Activities may be carried out in
identified according to the network type groups or as individual
4.2 The network devices are connected and configured
according to local and international standards
4.3 Network software is installed and configured according ·
to the user manual
4.4 Network performance is tested
Introduction
This learning outcome covers identifying tools, materials and devices for network setup,
connecting and configuring network devices, installing and configuring network software and
testing network performance.
Network equipment is used to combine, split, switch, boost, or direct packets of information along
a computer or telecommunications network. This product area includes hubs, switches, routers,
bridges, gateways, multiplexers, transceivers and firewalls. In addition to device type, network
equipment is defined by protocol (e.g., Ethernet) and port or interface type (e.g., T1).
In wireless networks, devices communicate via radio waves and do not require physical
connections. In wired networks, cables are used. These cables are equipped with connectors for a
specific port or interface type. For example, attachment unit interface (AUI) cables are equipped
with 15-pin connectors that mate with a 15-pin receptacle on network transceivers.
492
Computer networks handle data according to protocols that are fundamental mechanisms for
network communications. Network protocols specify the software attributes of data
communications, including the structure of packets and the information contained therein.
Depending upon the type of network, packets may be called blocks, cells, frames or segments.
Network protocols may also prescribe some or all of the operational characteristics of the network
hardware on which they run.
493
● Bridges are used to interconnect local or remote networks. They centralize network
administration.
● Gateways can interconnect networks with different, incompatible communications
protocols.
● Multiplexers combine multiple signal inputs into one output.
● Transceivers connect nodes and send and receive signals. They are sometimes
called medium access units (MAU).
● Firewalls safeguard a network against unauthorized access.
Other network devices such as wireless access points (WAP) and modular platforms
are also available.
Network equipment may be designed for local area networks (LAN), metropolitan area networks
(MAN), or wide area networks (WAN).
Networks
Processor type, speed, and computer memory are other important product parameters. Form factors
include chips, boards or cards, and stand-alone or enclosed modules.
Performance specifications include data rate and operating temperature, the number of users and
concurrent connections that devices can support, and the total number of media access control
(MAC) addressed that can be stored.
Network equipment may be designed or suitable for particular applications. For example, hardened
products are often used in telecommunications applications. Their casings provide protection from
weather-related conditions and can act as a heat sink, directing high temperatures away from
sensitive components.
Hubs
● Hubs connect computers together in a star topology network. Due to their design,
they increase the chances for collisions.
● Hubs operate in the physical layer of the OSI model and have no intelligence. Hubs
flood incoming packets to all ports all the time. For this reason, if a network is
494
connected using hubs, the chances of a collision increases linearly with the number
of computers (assuming equal bandwidth use).
● Hubs pose a security risk since all packets are flooded to all ports all the time. If a
user has packet sniffing software, they can extract data from the network and
potentially decode it and use it. Hubs make it easy to "spy" on users on the same
LAN as you.
Figure 108:Hub
Repeater
● A repeater is an electronic device that receives a signal and retransmits it at a higher
level and/or higher power, or onto the other side of an obstruction, so that the signal
can cover longer distances without degradation.
● Because repeaters work with the actual physical signal, and do not attempt to
interpret the data being transmitted, they operate on the physical layer, the first layer
of the OSI model.
● Repeaters are majorly employed in long distance transmission to reduce the effect of
attenuation. It is important to note that repeaters do not amplify the original signal
but simply regenerate it.
Modem
● Modem (from modulator-demodulator) is a device that turns the digital 1s and 0s of
a personal computer into sounds that can be transmitted over the telephone lines of
Plain Old Telephone Systems (POTS), and once received on the other side, converts
those sounds back into a form used by a USB, Ethernet, serial, or network
connection.
● Modems are generally classified by the amount of data they can send in a given time,
normally measured in bits per second, or "bps".
Media converters
● Media converters are simple networking devices that make it possible to connect two
dissimilar media types such as twisted pair with fiber optic cabling. They are
important in interconnecting fiber optic cabling-based systems with existing copper-
based, structured cabling systems.
● Media converters support many different data communication protocols including
Ethernet, T1/E1, T3/E3, as well as multiple cabling types such as coaxial, twisted
pair, multimode and single-mode fiber optics. When expanding the reach of a Local
Area Network to span multiple locations, media converters are useful in connecting
multiple LANs to form one large "campus area network" that spans over a limited
geographic area.
Switches
● Similar to a hub, switches provide a central connection between two or more
computers on a network, but with some intelligence.
● They provide traffic control for packets; rather than forwarding data to all the
connected ports, a switch forwards data only to the port on which the destination
system is connected. They use a database of MAC addresses to determine where
computers are located and very efficiently send packets only where they need to go.
The database is created dynamically as computers communicate on the network.
● The switch simply watches the incoming packets and memorizes the MAC address
and port a packet arrives on. If a packet arrives with a destination computer that the
switch does not have an address for in its MAC address table, it will flood the packet
out all connected ports. A switch creates separate collision domains for each
physical connection.
496
Figure 109: How a switch works
Bridge
● Bridges can be identified by the fact that they operate at the data link layer of the
OSI model. Bridges have intelligence and can "bridge" two of their ports together at
very high speed. They use a database of MAC addresses to determine where
computers are located and very efficiently send frames only where they need to go.
The database is created dynamically as computers communicate on the network.
● A bridge simply watches the incoming frame and memorizes the MAC address and
port a frame arrives on. It uses this information to locate a computer if a packet
comes in that must be forwarded to it. If a frame arrives at the bridge and the bridge
does not know where to send it, the bridge will flood the frame just like a hub does.
497
● A Hot Spot is a common public application of WAPs, where wireless clients can
connect to the Internet without regard for the particular networks to which they have
attached for the moment. A collection of connected Hot Spots can be referred to as a
lily-pad network.
Router
● Routers operate at the network layer of the OSI model and efficiently route
information between Local Area Networks. Since routers operate in the third layer,
the network layer, they must understand layer 3 addressing such as TCP/IP.
● A router will divide a broadcast domain by not forwarding broadcasts on one
connected network to another connected network.
● Routers operate in two different planes: the control plane, in which the router learns
the outgoing interface that is most appropriate for forwarding specific packets to
specific destinations, and the forwarding plane, which is responsible for the actual
process of sending a packet received on a logical interface to an outbound logical
interface.
Figure 112:Router
Firewall
● A firewall is a part of a computer system or network that is designed to block
unauthorized access while permitting outward communication. It is also a device or
set of devices configured to permit, deny, encrypt, decrypt, or proxy all computer
traffic between different security domains based upon a set of rules and other
criteria.
● Firewalls can be implemented in both hardware and software, or a combination of
both. Firewalls are frequently used to prevent unauthorized Internet users from
accessing private networks connected to the Internet.
498
● All messages entering or leaving the Local Area Network pass through the firewall,
which examines each message and blocks those that do not meet the specified
security criteria.
To begin the installation, insert the DVD distribution media in the server’s DVD drive and then
restart the server. This causes the server to boot directly from the distribution media, which initiates
the setup program.
As the setup program proceeds, it leads you through two distinct installation phases: Collecting
Information and Installing Windows. The following sections describe these installation phases in
greater detail.
500
The following list describes the server configuration settings available from this wizard:
● Set the Administrator Password: The very first thing you should do after installing
Windows is set a secure administrator password.
● Set the Time Zone: This is necessary only if the indicated time zone is incorrect.
● Configure Networking: The default network settings are usually appropriate, but
you can use this option to change the defaults if you wish.
● Provide Computer Name and Domain: This option lets you change the server’s
computer name and join a domain.
● Enable Automatic Updating: Use this option if you want to let the server
automatically check for operating system updates.
● Download and Install Updates: Use this option to check for critical operating
system updates.
● Add Roles: This option launches the Add Roles Wizard, which lets you configure
important roles for your server.
● Add Features: This option lets you add more operating system features.
● Enable Remote Desktop: Use this option to enable the Remote Desktop feature,
which lets you administer this server from another computer.
● Configure Windows Firewall: If you want to use the built-in Windows firewall,
this option lets you configure it.
Network testing is an investigation conducted to provide stakeholders with information about the
quality of the product or service under test.
501
Network testing can also provide an objective, independent view of the network to allow the
business to appreciate and understand the risks of network implementation.
A second connectivity test is TRACERT which traces the route to the target computer and returns
a list of routers through which your request travels to reach the destination.
To use TRACERT:
● Open a command prompt
● For Windows XP: Click Start, select Run, type cmd and press Enter or select OK
button. For higher Windows versions: type cmd into the Start menu search box and
select it from the Programs list that appears OR if you have the Run option enabled
on your Start Menu, then click Start, select Run, type cmd and press Enter or select
OK button.
● From the command prompt, type
TRACERT servername
or
TRACERTserverIP
where servername is the name of the server or serverIP is the IP address of the server
with which you want to communicate.
502
● The default settings for TRACERT will test over a maximum of 30 hops.
● If your TRACERT uses all 30 hops and receives many responses of * rather than a
time in ms (milliseconds) at each hop, you can expect communication with the target
computer to be inefficient.
Conclusion
At the end of this learning outcome, the learner should be able to identify tools, materials and
devices for network setup, connect and configure network devices, install and configure network
software and test network performance.
Further Reading
https://www.globalspec.com/learnmore/networking_communication_equipment/networking_equi
pment/networking_equipment
8.3.5.3 Self-Assessment
Written Assessment
1. In distributed systems, link and site failure is detected by?
a) token passing
b) polling
c) handshaking
d) none of the above
2. Internet provides----- for remote login.
a) rpc
b) ftp
c) telnet
d) http
3. The capability of a system to adapt the increased service load is called ------------
a) Scalability
b) tolerance
c) capacity
d) none of the above
4. Logical extension of computation migration is------------
a) System migration
b) Thread Migration
c) Process migration
d) Data migration
5. Processes on the remote systems are identified by?
a) Host name and identifier
b) Host ID
c) Process ID
d) Identifier
6. Which routing technique is used in a distributed system?
a) virtual routing
503
b) Dynamic routing
c) Fixed routing
d) All of the above
7. What does each processer have in a distributed system?
a) Clock
b) Local memory
c) Both Local memory and clock
d) None of the above
8. Network operating system runs on?
a) Every system
b) Server
c) Both a and b
d) None of the above.
8. In distributed systems link and site failure is detected by
a) token passing
b) polling
c) handshaking
d) None of the above
9. Internet provides ------ for remote login
a) http
b) rock
c) ftp
d) telnet
10. The capability of the system to adapt the increased service load is called
a) Tolerance
b) Capacity
c) Scalability
d) None of above
Oral Assessment
1. What is the difference between a router and a switch?
2. What role does a gateway serve in a network?
3. What is wireless hotspot?
Practical Assessment
Set up a Star LAN using two computers, install the NOS and test the network set up.
8.3.5.5 References
https://www.globalspec.com/learnmore/networking_communication_equipment/networking_equi
pment/networking_equipment
505
8.3.6 Learning Outcome 5: Understand Data Communication Standards and IP Addressing
8.3.6.1 Learning Activities
Learning Outcome No.5: Understand Data Communication Standards and IP Addressing
Introduction
This learning outcome covers outlining the OSI model, explaining data communication
components and demonstrating network address classes.
OSI model:
Definition
OSI stands for Open Systems Interconnection. It has been developed by ISO – ‘International
Organization of Standardization‘, in the year 1984. It is a 7 layer architecture with each layer
having specific functionality to perform. All these 7 layers work collaboratively to transmit the data
from one person to another across the globe.
506
Functions of different OSI model layers
The packet received from Network layer is further divided into frames depending on the frame size
of NIC (Network Interface Card). DLL also encapsulates Sender and Receiver’s MAC address in
the header.
507
The Receiver’s MAC address is obtained by placing an ARP(Address Resolution Protocol) request
onto the wire asking “Who has that IP address?” and the destination host will reply with its MAC
address.
508
of the complete message. The transport layer also provides the acknowledgement of the
successful data transmission and re-transmits the data if an error is found.
• At sender’s side:
Transport layer receives the formatted data from the upper layers, performs Segmentation and
also implements Flow & Error control to ensure proper data transmission. It also adds Source
and Destination port number in its header and forwards the segmented data to the Network Layer.
Note: The sender need to know the port number associated with the receiver’s application.
Generally, this destination port number is configured, either by default or manually. For example,
when a web application makes a request to a web server, it typically uses port number 80,
because this is the default port assigned to web applications. Many applications have default port
assigned.
• At receiver’s side:
Transport Layer reads the port number from its header and forwards the Data which it has
received to the respective application. It also performs sequencing and reassembling of the
segmented data.
The functions of the transport layer are:
● Segmentation and Reassembly: This layer accepts the message from the (session)
layer, breaks the message into smaller units. Each of the segment produced has a
header associated with it. The transport layer at the destination station reassembles
the message.
● Service Point Addressing: In order to deliver the message to correct process,
transport layer header includes a type of address called service point address or port
address. Thus by specifying this address, transport layer makes sure that the message
is delivered to the correct process.
In this type of transmission, the receiving device sends an acknowledgement, back to the source
after a packet or group of packet is received. This type of transmission is reliable and secure.
Connection less service: It is a one-phase process and includes Data Transfer. In this type of
transmission, the receiver does not acknowledge receipt of a packet. This approach allows for
much faster communication between devices. Connection-oriented service is more reliable than
connectionless Service.
509
Transport layer is operated by the Operating System. It is a part of the OS and communicates
with the Application Layer by making system calls.
Implementation of these 3 layers is done by the network application itself. These are also known
as Upper Layers or Software Layers.
SCENARIO:
Let’s consider a scenario where a user wants to send a message through some Messenger
application running in his browser. The “Messenger” here acts as the application layer which
provides the user with an interface to create the data. This message or so-called Data is
compressed, encrypted (if any secure data) and converted into bits (0’s and 1’s) so that it can be
transmitted.
510
The functions of the presentation layer are:
● Translation: For example, ASCII to EBCDIC.
● Encryption/ Decryption: Data encryption translates the data into another form or
code. The encrypted data is known as the cipher text and the decrypted data is
known as plain text. A key value is used for encrypting as well as decrypting data.
● Compression: Reduces the number of bits that need to be transmitted on the
network.
Data and information are received by each layer from an upper layer.
After the required processing, this layer then passes the information on to the next lower layer. A
header is added to the forwarded message for the convenience of the next layer. Each header
consists of information such as source and destination addresses, protocol used, sequence number
and other flow-control related data.
The following are the OSI protocols used in the seven layers of the OSI Model:
Layer 1, the Physical Layer: This layer deals with the hardware of networks such as cabling. The
major protocols used by this layer include Bluetooth, PON, OTN, DSL, IEEE.802.11,
IEEE.802.3, L431 and TIA 449.
Layer 2, the Data Link Layer: This layer receives data from the physical layer and compiles it
into a transform form called framing or frame. The protocols are used by the Data Link Layer
include: ARP, CSLIP, HDLC, IEEE.802.3, PPP, X-25, SLIP, ATM, SDLS and PLIP.
511
Layer 3, the Network Layer: This is the most important layer of the OSI model, which performs
real time processing and transfers data from nodes to nodes. Routers and switches are the devices
used for this layer. The network layer assists the following protocols: Internet Protocol (IPv4),
Internet Protocol (IPv6), IPX, AppleTalk, ICMP, IPSec and IGMP.
Layer 4, the Transport Layer: The transport layer works on two determined communication
modes: Connection oriented and connectionless. This layer transmits data from source to
destination node. It uses the most important protocols of OSI protocol family, which are:
Transmission Control Protocol (TCP), UDP, SPX, DCCP and SCTP.
Layer 5, the Session Layer: The session layer creates a session between the source and the
destination nodes and terminates sessions on completion of the communication process. The
protocols used are: PPTP, SAP, L2TP and NetBIOS.
Layer 6, the Presentation Layer: The functions of encryption and decryption are defined on this
layer. It converts data formats into a format readable by the application layer. The following are
the presentation layer protocols: XDR, TLS, SSL and MIME.
Layer 7, the Application Layer: This layer works at the user end to interact with user applications.
QoS (quality of service), file transfer and email are the major popular services of the application
layer. This layer uses following protocols: HTTP, SMTP, DHCP, FTP, Telnet, SNMP and SMPP.
Message
The message is the information (data) to be communicated. Popular forms of information include
text, numbers, pictures, audio, and video.
Sender
The sender is the device that sends the data message. It can be a computer, workstation, telephone
handset, video camera, and so on.
Receiver
The receiver is the device that receives the message. It can be a computer, workstation, telephone
handset, television, and so on.
Medium
The transmission medium is the physical path by which a message travels from sender to
receiver. Some examples of transmission media include twisted-pair wire, coaxial cable, fiber-
optic cable, and radio waves.
Protocol
512
A protocol is a set of rules that govern data communications. It represents an agreement between
the communicating devices. Without a protocol, two devices may be connected but not
communicating, just as a person speaking French cannot be understood by a person who speaks
only Japanese.
Class A Address
The first bit of the first octet is always set to 0 (zero). Thus the first octet ranges from 1 – 127, i.e.
Class A addresses only include IP starting from 1.x.x.x to 126.x.x.x only. The IP range 127.x.x.x
is reserved for loopback IP addresses.
The default subnet mask for Class A IP address is 255.0.0.0 which implies that Class A
addressing can have 126 networks (27-2) and 16777214 hosts (224-2).
Class A IP address format is thus: 0NNNNNNN.HHHHHHHH.HHHHHHHH.HHHHHHHH
Class B Address
An IP address which belongs to class B has the first two bits in the first octet set to 10, i.e.
Class B IP Addresses range from 128.0.x.x to 191.255.x.x. The default subnet mask for Class B is
255.255.x.x.
Class B has 16384 (214) Network addresses and 65534 (216-2) Host addresses.
Class B IP address format is: 10NNNNNN.NNNNNNNN.HHHHHHHH.HHHHHHHH
Class C Address
The first octet of Class C IP address has its first 3 bits set to 110, that is −
Class C IP addresses range from 192.0.0.x to 223.255.255.x. The default subnet mask for Class C
is 255.255.255.x.
Class C gives 2097152 (221) Network addresses and 254 (28-2) Host addresses.
Class C IP address format is: 110NNNNN.NNNNNNNN.NNNNNNNN.HHHHHHHH
Public IP address
513
● A public IP address is the address that is assigned to a computing device to allow
direct access over the Internet.
● A web server, email server and any server device directly accessible from the
Internet are candidate for a public IP address.
● A public IP address is globally unique, and can only be assigned to a unique device.
Private IP address
● A private IP address is the address space allocated by InterNIC to allow
organizations to create their own private network. There are three IP blocks (1 class
A, 1 class B and 1 class C) reserved for a private use.
● The computers, tablets and smartphones sitting behind your home, and the personal
computers within an organizations are usually assigned private IP addresses. A
network printer residing in your home is assigned a private address so that only your
family can print to your local printer.
● When a computer is assigned a private IP address, the local devices see this
computer via its private IP address. However, the devices residing outside of your
local network cannot directly communicate via the private IP address, but uses your
router's public IP address to communicate.
Conclusion
At the end of this learning outcome, the learner should be able to outline the OSI model, explain
data communication components and demonstrate network address classes.
Further Reading
1. https://www.geeksforgeeks.org/layers-of-osi-model/
2. http://www.myreadingroom.co.in/notes-and-studymaterial/68-dcn/675-components-of-data-
communication.html
8.3.6.3 Self-Assessment
514
Written Assessment
1. The number of layers in ISO OSI reference model is __________
a) 4
b) 5
c) 6
d) 7
2. OSI stands for __________
a) open system interconnection
b) operating system interface
c) optical service implementation
d) open service Internet
3. Which layer is used to link the network support layers and user support layers?
a) session layer
b) data link layer
c) transport layer
d) network layer
4. 14.23.120.8 address lies in which class
a) class A
b) class B
c) class D
d) class E
5. Addresses of classes A, B and C are
a) Multicast
b) Reserved
c) Unicast
d) All of the above
6. The design of the internet protocol suites adhere to the ---------principle
a) Connection oriented
b) End to end principle
c) Data corruption
d) Reliability
7. How many version/s of IPs are there
a) 1
b) 2
c) 3
d) 4
8 VLSM stands for
a) Variable length subnet masking
b) Variable length surface masking
c) Version length subnet masking
d) Version length surface masking
9. Many desk tops and operating systems include which protocol
a) Ipv6
515
b) Ipv4
c) Both a and b
d) Ipv3
10. How many bits does version 6 of IP address have?
a) 128
b) 32
c) 64
d) 256
Oral Assessment
1. What is OSI Model?
2. Which are the seven layers of OSI model, the protocols in each layer?
3. Which are the main data communication components?
4. Which scenario is Automatic Private IP Address used?
5. What are the default subnet mask for Class A, B and C IP addresses?
Practical Assessment
1. Configure the computers in the LAN set up in Learning outcome 4 to have static addresses.
Test the addresses by launching a web browser.
2. Configure Automatic Private IP Addressing for the LAN set up in Learning outcome 4
Practical Assessment. Test the addresses by launching a web browser.
● Networking toolkit
● Computers
● Essential networking devices
● Stationery
● Internet
● Instruction material
8.3.6.5 References
1. https://www.tutorialspoint.com/ipv4/ipv4_address_classes.htm
2. https://www.iplocation.net/public-vs-private-ip-address
3. https://www.pcmag.com/encyclopedia/term/apipa
516
8.3.7 Learning Outcome 6: Troubleshoot a Network
8.3.7.1 Learning Activities
Learning Outcome No.6: Troubleshoot a Network
Introduction
This learning outcome covers explaining troubleshooting, demonstrating troubleshooting tools and
troubleshooting of a network as per IEEE standards.
Troubleshooting:
Definition
Network troubleshooting is the collective measures and processes used to identify, diagnose and
resolve problems and issues within a computer network.
It is a systematic process that aims to resolve problems and restore normal network operations
within the network.
Troubleshooting Techniques:
The most important part of troubleshooting is developing a good technique. This excerpt from
"Network troubleshooting and diagnostics" lays the foundation for developing a good technique by
examining approaches such as using the OSI model as a troubleshooting framework and how
network administrators can approach troubleshooting.
1. SolarWinds Port Scanner (FREE DOWNLOAD) – Free tool to check the ports on your
network devices to ensure that you don’t have unattended ports open.
2. Ping – Simple command line utility that checks on the speed of connections.
517
3. Tracert – Free command line utility that lists the probable hops to a network or internet
destination address.
4. Ipconfig – This command line tool reports the IPv4 and IPv6 addresses, subnets, and default
gateways for all network adapters on a PC.
5. Netstat – This tool displays active connections on your computer.
6. Nslookup – Available for Windows, Unix, Linux, and Mac OS, this tool gives you DNS
server diagnostics.
7. Speed and up/down test sites – A list of websites that will test your internet connections.
8. Sysinternals – Set of Microsoft tools for Windows that help troubleshoot and configure
Active Directory.
9. Wireshark – Free packet sniffer that will help you analyze traffic flows.
10. Nmap – Network security and monitoring tool that needs a companion utility, Zenmap, as a
user interface.
Troubleshooting Procedures:
● Check the hardware. When you’re beginning the troubleshooting process, check all
your hardware to make sure it’s connected properly, turned on, and working. If a
cord has come loose or somebody has switched off an important router, this could be
the problem behind your networking issues. There’s no point in going through the
process of troubleshooting network issues if all you need to do is plug a cord in.
Make sure all switches are in the correct positions and haven’t been bumped
accidentally.
● Next, turn the hardware off and back on again. This is the mainstay of IT
troubleshooting, and while it might sound simplistic, often it really does solve the
problem. Power cycling your modem, router, and PC can solve simple issues—just
be sure to leave each device off for at least 60 seconds before you turn it back on.
● Use ipconfig. Open the command prompt and type “ipconfig” (without the quotes)
into the terminal. The Default Gateway (listed last) is your router’s IP. Your
computer’s IP address is the number next to “IP Address.” If your computer’s IP
address starts with 169, the computer is not receiving a valid IP address. If it starts
with anything other than 169, your computer is being allocated a valid IP address
from your router.
Try typing in “ipconfig /release” followed by “ipconfig /renew” to get rid of your
current IP address and request a new one. This will in some cases solve the problem.
If you still can’t get a valid IP from your router, try plugging your computer straight
into the modem using an Ethernet cable. If it works, the problem lies with the router.
● Use ping and tracert. If your router is working fine, and you have an IP address
starting with something other than 169, the problems most likely located between
your router and the internet. At this point, it’s time to use the ping tool. Try sending
518
a ping to a well-known, large server, such as Google, to see if it can connect with
your router. You can ping Google DNS servers by opening the command prompt and
typing “ping 8.8.8.8”; you can also add “-t” to the end (ping 8.8.8.8 -t) to get it to
keep pinging the servers while you troubleshoot. If the pings fail to send, the
command prompt will return basic information about the issue.
You can use the tracert command to do the same thing, by typing “tracert 8.8.8.8”;
this will show you each step, or “hop,” between your router and the Google DNS
servers. You can see where along the pathway the error is arising. If the error comes
up early along the pathway, the issue is more likely somewhere in your local
network.
● Perform a DNS check. Use the command “nslookup” to determine whether there’s
a problem with the server you’re trying to connect to. If you perform a DNS check
on, for example, google.com and receive results such as “Timed Out,” “Server
Failure,” “Refused,” “No Response from Server,” or “Network Is Unreachable,” it
may indicate the problem originates in the DNS server for your destination. (You
can also use nslookup to check your own DNS server.)
● Contact the ISP. If all of the above turn up no problems, try contacting your
internet service provider to see if they’re having issues. You can also look up outage
maps and related information on a smartphone to see if others in your area are
having the same problem.
● Check on virus and malware protection. Next, make sure your virus and malware
tools are running correctly, and they haven’t flagged anything that could be affecting
part of your network and stopping it from functioning.
● Review database logs. Review all your database logs to make sure the databases are
functioning as expected. If your network is working but your database is full or
malfunctioning, it could be causing problems that flow on and affect your network
performance.
a) Collect information. To best support your end users, you first need to make sure you’re clear
on what the problem is. Collect enough information from both the people who are experiencing
network issues and the network itself, so you can replicate or diagnose the problem. Take care not
to mistake symptoms for the root cause, as what initially looks like the problem could be part of a
larger issue.
519
b) Customize logs. Make sure your event and security logs are customized to provide you with
information to support your troubleshooting efforts. Each log should have a clear description of
which items or events are being logged, the date and time, and information on the source of the log
(MAC or IP address).
c) Check access and security. Ensure no access or security issues have come up by checking all
access permissions are as they should be, and nobody has accidentally altered a sensitive part of
the network they weren’t supposed to be able to touch. Check all firewalls, antivirus software, and
malware software to ensure they’re working correctly, and no security issues are affecting your
users’ ability to work.
d) Follow an escalation framework. There’s nothing worse than going to the IT help desk and
being directed to another person, who then directs you to another person, who directs you to yet
another. Have a clear escalation framework of who is responsible for which issues, including the
final person in the chain who can be approached for resolution. All your end users should know
who they can go to about a given issue, so time isn’t wasted talking to five different people who
cannot fix the problem.
e) Use monitoring tools. Troubleshooting can be done manually but can become time-consuming
if you go through each step. When you have a bunch of people knocking on your office door or
sending you frantic emails, it can be overwhelming to try to find the problem, let alone fix it. In
business and enterprise situations, it’s best to use monitoring tools to make sure you’re getting all
the relevant network information and aren’t missing anything vital, not to mention avoiding
exposing the company to unnecessary risk.
Troubleshooting tools:
Ping
The most commonly used network tool is the ping utility. This utility is used to provide a basic
connectivity test between the requesting host and a destination host. This is done by using the
Internet Control Message Protocol (ICMP) which has the ability to send an echo packet to a
destination host and a mechanism to listen for a response from this host. Simply stated, if the
requesting host receives a response from the destination host, this host is reachable. This utility is
commonly used to provide a basic picture of where a specific networking problem may exist.
For example, if an Internet connection is down at an office, the ping utility can be used to figure
out whether the problem exists within the office or within the network of the Internet provider. The
figure elow shows an example of the ping utility being used to obtain the reachability status of the
locally connected router.
520
Figure 115:Ping utility
Tracert/traceroute
Typically, once the ping utility has been used to determine basic connectivity, the tracert/traceroute
utility can used to determine more specific information about the path to the destination host
including the route the packet takes and the response time of these intermediate hosts.
The figure below shows an example of the tracert utility being used to find the path from a host
inside an office to www.google.com. The tracert utility and traceroute utilities perform the same
function but operate on different operating systems, Tracert for Windows machines and traceroute
for Linux/*nix based machines.
Nslookup
Some of the most common networking issues revolve around issues with Dynamic Name System
(DNS) address resolution issues. DNS is used by everyone using the Internet to resolve commonly
known domain names (i.e. google.com) to commonly unknown IP addresses (i.e. 74.125.115.147).
When this system does not work, most of the functionality that people are used to goes away, as
there is no way to resolve this information. The nslookup utility can be used to lookup the specific
521
IP address (es) associated with a domain name. If this utility is unable to resolve this information,
there is a DNS issue.
Along with simple lookup, the nslookup utility is able to query specific DNS servers to determine
an issue with the default DNS servers configured on a host. The figure below shows an example of
how the nslookup utility can be used to query the associated IP address information.
Netstat
Often, one of the things that are required to be figured out is the current state of the active network
connections on a host. This is very important information to find for a variety of reasons. For
example, when verifying the status of a listening port on a host or to check and see what remote
hosts are connected to a local host on a specific port.
It is also possible to use the netstat utility to determine which services on a host that is associated
with specific active ports. The figure below shows an example of the netstat utility being used to
display the currently active ports on a Linux machine.
522
Figure 117:Netstat utility
Pathping/mtr
In an effort to take advantage of the benefits of both the ping and tracert/traceroute commands, the
pathping and mtr utilities were developed. Both of these tools take the functionality and information
that can be obtained from these types of tools and provide a more detailed single picture of the path
characteristics from a specific host to a specific destination.
The figures below show examples of these two tools and what information they provide.
523
524
Figure 118:Pathping utility
With the robust improvement of the Internet, there are lots of network issues existing in the network
systems. Many research works proposed different approaches to resolve the network issues in order
to enhance the performance of network management and guarantee the user's QoE (Quality of
Experience).
Network Troubleshooting
When an issue appears, network administrators do not know which kinds of issues and its locations.
The issues can result from network service providers (NSP) or application service providers (ASP).
In this section, we classify the issues into network issues which caused by NSP and application
issues which result from ASP. The detail is described in the figure below
The transient reachability issues can be caused by some transient events (e.g. link flaps). The non-
transient reachability issues, which are more difficult to be resolved, result from the failures of
physic links, router misconfigurations.So many research works focus on this kind of issue.
Tracing framework that provides the global overview through reconstructing the task tree of all
sub-operations making up the tasks. This can help to understand the causal paths in the network
protocols to point out the location of the issues and make suitable decisions for network
troubleshooting.
ii) Congestion is the result of network routes becoming too full when there are many requests on
these network routes. Net-Replay, a method re-transmits the packets and receives the feedback of
the network elements related to the congestion and the location of issues. When the receivers inform
the senders that some arrival packets are in high delay, the receivers then replay the delayed
packets, and the senders will parse the annotations in these packets to identify the location of issues.
A method using the packet retransmission to locate the congestion in the network, called Automatic
Test Packet Generation (ATPG). If the congestion exists, ATPG generates the congestion test to
evaluate the latency between the pair packets in order to locate the location of congestion.
Net-Replay can point out the position of packet re-ordering and packet loss in the network. Packet
re-ordering is the network behavior when the order of some packets in the flows is confused during
the packet transmission in the network. In the packet re-ordering issues, the router where the change
takes place will be remarked in the replayed packets. Packet loss is the issue that occurs when the
packet transmission across the network fail to reach their destinations. For the packet loss issues,
Net-Replay uses the NotFoundAt field in the replayed packet to inform the receivers about the
location of packet loss.
iii) Link failure is the issue which is caused by many factors such as a cable being unplugged,
misconfiguration or denial of service attack, etc. Duffield et al. [13] [14] presented an approach
using smallest consistent failure set (SCFS) rule to detect the failed links.
iv) Security policy violation (SPV) is one of the most important issues in the network systems.
This can be caused by many factors including malware, botnet or DDoS attack. These are the
implicit threats causing to other network issues including congestion, packet loss, unreachability
that can reduce the quality of service (QoS) and quality of experience (QoE). Nowadays, the DDoS
attack can result from malware and botnet.
526
Beyond the above issues, there are another network issues including high router CPU utilization
(HRCU), and forwarding loop. The high router CPU utilization can result from different reasons
such as interrupts, processes, software encryption, and fragmentation. For the forwarding loop,
these errors, which occur in the routing algorithm, lead to the looping in the path to the destinations.
All the above issues relate to the network symptoms while there is some issues caused by
administrators such as router misconfiguration. Feamster proposed a router configuration checker
that can detect the errors in BGP configuration using static analysis. This tool can detect two kinds
of faults including route validity faults, and path visibility faults. Route validity faults are the issues
where the routers learn the route that is not in usable paths while path visibility faults are the issues
where the routers can fail to learn existing routes in the network.
b. Application Issues
When the errors appear, this can relate to the application faults. For example, the poor quality of
some video call services do not result from the network issues, but it can be caused by the faults in
the server of these services.
Conclusion
At the end of this learning outcome, the learner should be able to explain troubleshooting,
demonstrate troubleshooting tools and troubleshoot a network as per IEEE standards
Further Reading
https://www.pluralsight.com/blog/it-ops/network-troubleshooting-tools
8.3.7.3 Self-Assessment
Written Assessment
1. You are the new IT admin, and you need to find the network configuration. What should you
use?
a. ipconfig
b. cmd
c. netchange
d. newnet
2. You want to find out the IP address of a hostname, like google.com, you should use...
a. nslookup
b. ping
c. tracert /ping
d. cmd
3. You want to find out different IP statistics such as current connections and any active ports, try
using...
a. netstat
b. nslookup
527
c. ping
d. cmd
4. The computer is experiencing a network problem. The first thing you do is determine that the
Broadcom Ethernet NIC is working by checking Device Manager. This is also known as...
a. Verify the network adapter
b. Verify physical connectivity
c. Verify the IP configuration
d. Verify network connectivity
5. You are given a laptop that "has no internet" - it's older and likely running Windows Xp/Vista.
What is the MOST likely issue?
a. answer choices
b. wireless switch is off
c. does not have wifi capabilities
d. user typed in bad password
6. You are the new IT admin and you need to find the network configuration. What should you
use?
a. ipconfig
b. netchange
c. cmd
d. new net
7. The Ip config switch requests new Ip information from DHCP server.
a. Release
b. Re-run
c. Re-new
d. Return
8. Which command send a request out and expects a response, indicating that both hosts are
communicating
a. ping
b. tracert
c. nslookup
d. Ip config/renew
9. Which command do youy use top get the most detailed configuration
a. Ipconfig
b. Ipconfig/most
c. Ipconfig/all
d. Ipconfig/renew
10. If you want to find out address of a host name like google.com, what should you use?
a. ping
b. tracert/ping
c. nslookup
d cmd
528
Oral Assessment
1. What is network troubleshooting and what are the best troubleshooting techniques?
2. What are the most useful network troubleshooting tools and how do they work?
3. When can tracert tool be most useful in network troubleshooting?
4. What do you understand by active and passive troubleshooting methods?
Practical Assessment
Demonstrate how the following tools are used in network troubleshooting
• Ping
• Tracert/traceroute
• Nslookup
• Netstat
• Pathping/mtr
8.3.7.4 Tools, Equipment, Supplies and Materials
● Networking tool kit
● Essential networking devices
● Computers in a LAN set up.
● Stationery
● Internet
● Instruction material
8.3.7.5 References
1. https://www.dnsstuff.com/network-troubleshooting-steps
2. https://ieeexplore.ieee.org/abstract/document/8585610
529
CHAPTER 9: ARTIFICIAL INTELLIGENCE
9.1 Introduction
This unit covers the competencies required to understand artificial intelligence fundamentals. It
involves understanding concepts of Artificial Intelligence, understanding problem solving
techniques, understanding Python programming environment and developing Artificial Intelligence
programs using Python
530
9.3.2 Learning Outcome 1: Understand Artificial Intelligence fundamentals
9.3.2.1 Learning Activities
Learning Outcome 1: Understand Artificial Intelligence fundamentals
Learning Activities Special Instructions
Introduction
This learning outcome covers defining AI, explaining the history of AI, foundations of A1,
applications of AI, intelligence agents and recognising applications of AI in real life.
John McCarthy coined the term Artificial Intelligence. Demonstration of the first
1956
running AI program at Carnegie Mellon University.
531
Danny Bob row’s dissertation at MIT showed that computers can understand
1964
natural language well enough to solve algebra word problems correctly.
The Assembly Robotics group at Edinburgh University built Freddy, the Famous
1973
Scottish Robot, capable of using vision to locate and assemble models.
1979 The first computer-controlled autonomous vehicle, Stanford Cart, was built.
1985 Harold Cohen created and demonstrated the drawing program, Aaron.
The Deep Blue Chess Program beats the then world chess champion, Garry
1997
Kasparov.
Expert Systems
An expert system (ES) is an artificial agent which leverages pre-programmed knowledge to offer
advice or make decisions.
Computer Vision
Computer vision (CV) is the automatic extraction, analysis, and interpretation of images or videos.
CV converts photos and videos into numerical arrays, enabling ML algorithms to draw inferences,
make predictions, and even generate new images based on user-defined inputs.
Robotics
Robotics is the science of designing, constructing, operating, and applying robots to solve human
problems. Robots come in thousands of shapes and sizes, making it difficult to nail down the precise
meaning of the term.
Intelligent agents
What is an intelligent agent?
An intelligent agent is anything that can make decisions about how to react or respond based on
how it perceives its environment and its experiences. Siri is able to retrieve information about the
weather, scores, or world capitals (or anything you ask) based on its perception of its environment.
533
An Agent runs in the cycle of perceiving, thinking, and acting. An agent can be:
Human-Agent A human agent has eyes, ears, and other organs which work for sensors
and hand, legs, vocal tract work for actuators
Robotic Agent A robotic agent can have cameras, infrared range finder, NLP for sensors
and various motors for actuators
Software Agent Software agent can have keystrokes, file contents as sensory input and act
on those inputs and display output on the screen
• Sensor: Sensor is a device which detects the change in the environment and sends the
information to other electronic devices. An agent observes its environment through
sensors.
• Actuators: Actuators are the component of machines that converts energy into motion.
The actuators are only responsible for moving and controlling a system. An actuator can
be an electric motor, gears, rails, etc.
• Effectors: Effectors are the devices which affect the environment. Effectors can be legs,
wheels, arms, fingers, wings, fins, and display screen.
534
Agent Performance Environment Actuators Sensors
measure
535
• Natural Language Processing − It is possible to interact with the computer that understands
natural language spoken by humans.
• Vision Systems − these systems understand, interpret, and comprehend visual input on the
computer. For example:
o Doctors use clinical expert system to diagnose the patient.
o Police use computer software that can recognize the face of criminal with the stored
portrait made by forensic artist.
• Speech Recognition − some intelligent systems are capable of hearing and comprehending
the language in terms of sentences and their meanings while humans talk to it. It can handle
different accents, slang words, noise in the background, change in human’s noise due to cold,
etc.
• Handwriting Recognition − the handwriting recognition software reads the text written on
paper by a pen or on screen by a stylus. It can recognize the shapes of the letters and convert
it into editable text.
Conclusion
At the end of this learning outcome, the learner should be able to define AI, explain the history of
AI, foundations of A1, applications of AI and intelligence agents and recognise applications of AI
in real life.
Further Reading
• https://techtrendske.co.ke/understanding-zuri-safaricom-ai-chatbot/
• https://www.apple.com/siri/
• https://support.microsoft.com/en-us/help/17214/cortana-what-is
• https://assistant.google.com/
• https://support.microsoft.com/en-us/help/17214/cortana-what-is
9.3.2.3 Self-Assessment
Written assessment
1. Identify the statement best describes the role of a sensor in an intelligent agent
a) Detects the change in the environment and sends the information to other electronic
devices.
b) Converts energy into motion
c) Affect the environment
d) Provide power
2. Using business examples, explain how chatbots simplify business operations
536
3. Which AI applications would you advise disaster management workers to detect and identify
problems?
4. How can use of AI systems help security agencies in crime management?
5. What is machine learning?
Oral Assessment
1. Which (any two) ethical issues can emerge from using Artificial Intelligence?
2. Justify the widely shared opinion that Artificial intelligence systems reduce human error to a
great degree in many fields.
Practical Assessment
1. Using Windows 10, launch Windows Cortana application.
2. Test the application for
a) Setting a reminder
b) Getting a weather forecast of the city nearest to you.
9.3.2.5 References
1. https://www.investopedia.com/terms/w/weak-ai.asp
2. https://www.investopedia.com/terms/s/strong-ai.asp
3. https://www.netapp.com/us/info/what-is-artificial-intelligence-ai.aspx
4. https://www.tutorialspoint.com/artificial_intelligence/index.htm
5. https://en.wikipedia.org/wiki/Superintelligence
6. https://www.javatpoint.com/agents-in-ai
7. https://study.com/academy/lesson/intelligent-agents-definition-types-examples.html
537
9.3.3 Learning outcome 2: Understand problem solving techniques
9.3.3.1 Learning Activities
Learning Outcome 2: Understand problem solving techniques
Learning Activities Special Instructions
Introduction
This learning outcome covers outlining logical operators, explaining Prepositional and Predicate
Logic, explaining types of inferencing, defining machine learning, explaining types of machine
learning and recognising applications of different types of inferencing.
Logical operators
A logical operator is a special symbol or word that connects two or more phrases of information. We
have a range of the logic/ logical operators which include:
OR
The OR logic operation returns True if either its inputs are True. If all inputs are false, the output is
also false. In computer programming, the OR operation is usually written as || (two vertical bars). In
Boolean algebra, the OR value of two inputs A and B can be written as A+B.
AND
The AND logic operation returns True only if either of its inputs are True. If either of the inputs is
False the output is also false. In computer programming, the AND operation is usually written as
&& (two ampersands). In Boolean algebra, the AND operation of two inputs A and B can be written
as AB.
NOT
The NOT logic operation returns True if its input is False, and False if its input is True. In computer
programming, the NOT operation is usually written as ! (an exclamation mark). In Boolean algebra,
the NOT value of an input A can be written as A̅ (A with an overscore).
538
Propositional Logic and Predicate logic
The rules of mathematical logic specify methods of reasoning mathematical statements.
Logical reasoning provides the theoretical base for many areas of mathematics and consequently
computer science. It has many practical applications in computer science like design of computing
machines, artificial intelligence, definition of data structures for programming languages etc.
Propositional Logic
A proposition is a collection of declarative statements that has either a truth value "true" or a truth
value "false". A propositional consists of propositional variables and connectives. We denote the
propositional variables by capital letters (A, B, etc.). The connectives connect the propositional
variables.
Connectives
In propositional logic generally we use five connectives which are −
• OR ( ∨)
• AND ( ∧)
• Negation/ NOT ( ¬)
• Implication / if-then ( →)
• If and only if ( ⇔).
OR ( ∨) − The OR operation of two propositions A and B (written as A∨B) is true if at least any of
the propositional variable A or B is true.
The truth table is as follows −
A B A∨B
539
True False True
True False
False True
Implication / if-then ( →) − An implication A→B is the proposition “if A, then B”. It is false if A
is true and B is false. The rest cases are true.
The truth table is as follows −
A B A→B
540
True True True
A predicate is an expression of one or more variables defined on some specific domain. A predicate
with variables can be made a proposition by either assigning a value to the variable or by quantifying
the variable.
Quantifiers
The variable of predicates is quantified by quantifiers. There are two types of quantifier in predicate
logic − Universal Quantifier and Existential Quantifier.
Universal Quantifier
Universal quantifier states that the statements within its scope are true for every value of the specific
variable. It is denoted by the symbol ∀
.
∀xP(x) is read as for every value of x, P(x) is true.
Example − "Man is mortal" can be transformed into the propositional form ∀xP(x) where P(x) is
the predicate which denotes x is mortal and the universe of discourse is all men.
Existential Quantifier
Existential quantifier states that the statements within its scope are true for some values of the
specific variable. It is denoted by the symbol ∃.
541
∃xP(x) is read as for some values of x, P(x) is true.
Example − "Some people are dishonest" can be transformed into the propositional
form ∃xP(x) where P(x) is the predicate which denotes x is dishonest and the universe of discourse
is some people.
Types of Inferencing in AI
In artificial intelligence, we need intelligent computers which can create new logic from old logic or
by evidence, so generating the conclusions from evidence and facts is termed as Inference.
Inference rules:
Inference rules are the templates for generating valid arguments. Inference rules are applied to
derive proofs in artificial intelligence, and the proof is a sequence of the conclusion that leads to the
desired goal.
In inference rules, the implication among all the connectives plays an important role.
Hence from the above truth table, we can prove that P → Q is equivalent to ¬ Q → ¬ P, and Q→ P
is equivalent to ¬ P → ¬ Q.
542
Example:
Statement-1: "If I am sleepy then I go to bed" ==> P→ Q
Statement-2: "I am sleepy" ==> P
Conclusion: "I go to bed." ==> Q.
Hence, we can say that, if P→ Q is true and P is true then Q will be true
.
Proof by Truth table:
2. Modus Tollens:
The Modus Tollens rule state that if P→ Q is true and ¬ Q is true, then ¬ P will also true. It can be
represented as:
3. Hypothetical Syllogism:
The Hypothetical Syllogism rule state that if P→R is true whenever P→Q is true, and Q→R is true.
It can be represented as the following notation:
Example:
Statement-1: If you have my home key then you can unlock my home. P→Q
Statement-2: If you can unlock my home then you can take my money. Q→R
Conclusion: If you have my home key then you can take my money. P→R
543
4. Disjunctive Syllogism:
The Disjunctive syllogism rule state that if P∨Q is true, and ¬P is true, then Q will be true. It can be
represented as:
Example:
Statement-1: Today is Sunday or Monday. ==>P∨Q
Statement-2: Today is not Sunday. ==> ¬P
Conclusion: Today is Monday. ==> Q
Proof by truth-table:
5. Addition:
The Addition rule is one the common inference rule, and it states that If P is true, then P∨Q will be
true.
Example:
Statement: I have a vanilla ice-cream. ==> P
Statement-2: I have Chocolate ice-cream.
Conclusion: I have vanilla or chocolate ice-cream. ==> (P∨Q)
Proof by Truth-Table:
544
6. Simplification:
The simplification rule state that if P∧ Q is true, then Q or P will also be true. It can be represented
as:
Proof by Truth-Table:
7. Resolution:
The Resolution rule state that if P∨Q and ¬ P∧R is true, then Q∨R will also be true. It can be
represented as
Proof by Truth-Table:
✓ Machine Learning
Machine learning is an application of artificial intelligence (AI) that provides systems the
ability to automatically learn and improve from experience without being explicitly
programmed.
545
The primary aim is to allow the computers learn automatically without human intervention or
assistance and adjust actions accordingly.
The process of learning begins with observations or data, such as examples, direct experience,
or instruction, in order to look for patterns in data and make better decisions in the future
based on the examples that we provide.
ML uses ideas and techniques from the fields of statistics, artificial intelligence, and computer
science.
546
Conclusion
At the end of this learning outcome, the learner should be able to outline logical operators, explain
Prepositional and Predicate Logic, explain types of inferencing, define machine learning, explain
types of machine learning and recognise applications of different types of inferencing.
Further Reading
1. J. Kelly, The Essence of Logic (Prentice Hall, Englewood Cliffs NJ, 1997)
2. https://www.cs.odu.edu/~toida/nerzic/content/logic/pred_logic/inference/infer_intro.html
3. https://www.site.uottawa.ca/~lucia/courses/2101-
10/lecturenotes/04InferenceRulesProofMethods.pdf
9.3.3.3 Self-Assessment
Written assessment
1. What is the difference between prepositional and Predicate logic
2. Why do we need Mathematical logic in AI?
3. Which are the basic logical operators?
4. How is unsupervised learning used to solve AI problems?
Oral assessment
What are the common real life applications of supervised learning?
Practical assessment
Conduct Internet research to justify the claim that social media platforms use machine learning to
learn user’s preferences for targeted content delivery.
9.3.3.5 References
547
1. https://www.tutorialspoint.com/discrete_mathematics/rules_of_inference.htm
2. https://www.javatpoint.com/rules-of-inference-in-artificial-intelligence
548
9.3.4 Learning outcome 3: Understand Python programming environment
9.3.4.1 Learning Activities
Learning Outcome 3: Understand Python programming environment
Learning Activities Special Instructions
Introduction
This learning outcome covers using Python language. It entails demonstrating installation of
Python, syntax, data types, control structures, functions, object orientation and scientific modules.
Python Installation
Python is an object-oriented programming language created by Guido Rossum in 1989. It is ideally
designed for rapid prototyping of complex applications. It has interfaces to many OS system calls
and libraries and is extensible to C or C++. Many large companies use the Python programming
language include NASA, Google, YouTube and BitTorrent.
Step 1: Download
Before you start, you will need Python on your computer.
Check whether you already have an up to date version of Python installed by entering python in a
command line window. If you see a response from a Python interpreter it will include a version
number in its initial display. Generally, any Python 3.x version will do, as Python makes every
attempt to maintain backwards compatibility within major Python versions.
If you need to install Python, you may as well download the most recent stable version. This is the
one with the highest number that isn't marked as an alpha or beta release.
See the Python downloads page (http://www.python.org/downloads/) for the most up to date
versions of Python.
On Windows you have a choice between 32-bit (labeled x86) and 64-bit (labeled x86-64) versions,
and several flavors of installer for each.
549
Step 2: Run the install
Once the download is complete, run the exe for install Python. Now click on Install Now.
550
Step 4: When it finishes, you can see a screen that says the Setup was successful. Now click on
"Close".
Python Syntax
The syntax of the Python programming language is the set of rules which defines how a Python
program will be written. A Python program is divided into a number of logical lines and every
logical line is terminated by the token NEWLINE. A logical line is created from one or more
physical lines.
A line that contains only spaces, tabs, form feeds, possibly a comment is known as a blank line, and
Python interpreter ignores it. A physical line is a sequence of characters terminated by an end-of-
line sequence (in windows it is called CR LF or return followed by a linefeed and in Unix, it is
called LF or linefeed). See the following example.
Indentation
Python uses whitespace (spaces and tabs) to define program blocks whereas other languages like
C, C++ use braces ({}) to indicate blocks of codes for class, functions or flow control. The number
of whitespaces (spaces and tabs) in the indentation is not fixed, but all statements within the block
551
must be the indented same amount. In the following program, the block statements have no
indentation.
552
Python variables and values
• A variable is a memory location where a programmer can store a value. Example: roll_no,
amount, name etc.
• Value is either string, numeric etc. Example: "Sara", 120, 25.36
• Variables are created when first assigned.
• Variables must be assigned before being referenced.
• The value stored in a variable can be accessed or updated later.
• No declaration required
• The type (string, int, float etc.) of the variable is determined by Python
• The interpreter allocates memory on the basis of the data type of a variable.
Python comments
A comment begins with a hash character (#) which is not a part of the string literal and ends at the
end of the physical line. All characters after the # character up to the end of the line are part of the
comment and the Python interpreter ignores them. See the following example. It should be noted
that Python has no multi-lines or block comments facility.
553
Data Types in Python
Type represents the kind of value and determines how the value can be used. All data values in
Python are encapsulated in relevant object classes. Everything in Python is an object and every
object has an identity, a type, and a value. Like another object-oriented language such as Java or
C++, there are several data types which are built into Python.
Numeric
A numeric value is any representation of data which has a numeric value. Python identifies three
types of numbers:
• Integer: Positive or negative whole numbers (without a fractional part)
• Float: Any real number with a floating-point representation in which a fractional
component is denoted by a decimal symbol or scientific notation
• Complex number: A number with a real and imaginary component represented as x+yj. x
and y are floats and j is -1(square root of -1 called an imaginary number)
Boolean
Data with one of two built-in values True or False. Notice that 'T' and 'F' are capital. True and false
are not valid Booleans and Python will throw an error for them.
Sequence Type
A sequence is an ordered collection of similar or different data types. Python has the following
built-in sequence data types:
• String: A string value is a collection of one or more characters put in single, double or triple
quotes.
• List: A list object is an ordered collection of one or more data items, not necessarily of the
same type, put in square brackets.
• Tuple: A Tuple object is an ordered collection of one or more data items, not necessarily of
the same type, put in parentheses.
Dictionary
A dictionary object is an unordered collection of data in a key: value pair form. A collection of
such pairs is enclosed in curly brackets. For example: {1:"Steve", 2:"Bill", 3:"Ram", 4: "Farha"}
type() function
Python has an in-built function type() to ascertain the data type of a certain value. For example,
enter type (1234) in Python shell and it will return <class 'int'>, which means 1234 is an integer
value. Try and verify the data type of different values in Python shell, as shown below.
554
A set is a collection of data types in Python, same as the list and tuple. However, it is not an ordered
collection of objects. The set is a Python implementation of the set in Mathematics. A set object
has suitable methods to perform mathematical set operations like union, intersection, difference,
etc.
A set object contains one or more items, not necessarily of the same type, which are separated by
comma and enclosed in curly brackets {}.
Python if
If statement is the simplest decision-making statement. It is used to decide whether a certain
statement or block of statements will be executed or not i.e. if a certain condition is true then a
block of statement is executed otherwise not.
Syntax:
555
Here, condition after evaluation will be either true or false. If statement accepts Boolean values –
if the value is true then it will execute the block of statements below it otherwise not. We can use
condition with bracket ‘(‘ ‘)’ also.
As we know, python uses indentation to identify a block. So, the block under an if statement will
be identified as shown in the below example:
i = 10
if (i > 15):
print ("10 is less than 15")
print ("I am Not in if")
if- else
The if statement alone tells us that if a condition is true it will execute a block of statements and if
the condition is false it won’t. But what if we want to do something else if the condition is false.
Here comes the else statement. We can use the else statement with if statement to execute a block
of code when the condition is false.
Syntax:
556
i = 20;
if (i < 15):
print ("i is smaller than 15")
print ("i'm in if Block")
else:
print ("i is greater than 15")
print ("i'm in else Block")
print ("i'm not in if and not in else Block")
Nested-if
A nested if is an if statement that is the target of another if statement. Nested if statements mean an
if statement inside another if statement. Yes, Python allows us to nest if statements within if
statements. i.e. we can place an if statement inside another if statement.
Syntax:
557
if-elif-else ladder
Here, a user can decide among multiple options. The if statements are executed from the top down.
As soon as one of the conditions controlling the if is true, the statement associated with that if is
executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else
statement will be executed.
Syntax: -
Condition-Controlled loop uses a true/false condition to control the number of times that it repeats
- while.
558
While loops
• While a condition is true, do some task.
• while loop is known as a pretest loop, which means it tests its condition before performing
an iteration
• The boolean_expression in these formats is sometimes known as the loop continuation
condition
• The loop body must be a block, or a single statement (like with the if-statements)
• How it works
o The boolean expression is a test condition that is evaluated to decide whether the
loop should repeat or not.
▪ true means run the loop body again.
▪ false means quit.
559
How it works
• The first line is called the for clause
• In the for clause, variable is the name of a variable.
• Inside the brackets is a sequence of values, that is comma separated. (in Python this is called
a list).
• Executing is as follows:
1. The variable is assigned the first value in the list.
2. The statements in the block are executed.
3. The variable is assigned the next value in the list, if any repeat step 2 else the loop
terminates.
• The variable can be used in the loop.
Definition
A procedure allows us to group a block of code under a name, known as a procedure name. We c
an call the block of code from anywhere in the program to execute the instructions it contains. W
e can also pass values to the procedure to change how it works.
A function is a block of code which is executed when it is called from somewhere in the
program. A function will return a value.
Functions are perfect for abstraction. They allow us to write blocks of code which can be reused i
n different ways and in different programs.
560
Role of procedures and functions
Output
showMenu() is an example of a procedure call. We can call the procedure as many times as we wi
sh in the program.A procedure needs to be defined earlier in the program than when it is called.
Syntax
Example 1
Output
Example 2
561
Output:
Output
562
Output:
Parameters
Parameters are part of a function definition (def or lambda). There are five different kinds of
parameters:
• Positional-or-keyword: Normal parameters in a function definition, with or without default
values.
Each has a name and an index, and can accept a positional argument with the same index, or a
keyword argument with the same name, or (if it has a default value) nothing.
Technically, every parameter before the first bare *, var-positional, or var-keyword is a positional-
or-keyword parameter.
• Positional-only: Only found in built-in/extension functions.
Each has a name and an index, but only accepts positional arguments with the same index.
• Var-positional: This is the *args.
This accepts a sequence consisting of all positional arguments whose index is larger than any
positional-or-keyword or positional-only parameter. (Note that you can also specify a bare * here.
In that case, you don't take variable positional arguments. You do this to set off keyword-only from
positional-or-keyword parameters.)
• Keyword-only: These are parameters that come after a * or *args, with or without default
values.
Each has a name only, and accepts only keyword arguments with the same name.
Technically, every parameter after the first bare * or var-positional, but before the var-keyword (if
any), is a keyword-only parameter.
• Var-keyword: This is the **args.
This accepts a mapping consisting of all keyword arguments whose name does not match any
positional-or-keyword or keyword-only parameter.
Examples
In the following example:
>>> def func(spam, eggs=1, *args, foo, bar=2, **kwargs):
... print(spam, eggs, args, foo, bar, kwargs)
>>> func(1, 2, 3, 4, foo=5, bar=6, baz=7)
1 2 (3, 4) 5 6 {'baz': 7}
>>> func(baz=1, bar=2, foo=3, eggs=4, spam=5)
5 4 () 3 2 {'baz': 1}
>>> func(foo=1, spam=2)
2 1 () 1 2 {}
564
spam is a positional-or-keyword parameter with no default value. This means any call must pass
either at least one positional argument (as in the first call), or a keyword argument with name
"spam" (as in the other two).
eggs is a positional-or-keyword parameter with a default value. This means a call may pass either
at least two positional arguments (as in the first call), or a keyword argument with name "eggs"
(as in the second), or neither (as in the third).
args is a var-positional parameter. Because there is such a parameter, it's legal to pass more than
two positional arguments, in which case it will get all of the excess (as in the first call), but of
course it's not required (as in the other two).
foo is a keyword-only parameter with no default value. This means any call must pass a keyword
argument with the name "foo" (as in all three calls).
bar is a keyword-only argument with a default value. This means a call may pass a keyword
argument with the name "bar" (as in the first two calls), or not (as in the third).
kwargs is a var-keyword parameter. Because there is such a parameter, it's legal to pass keyword
arguments whose names don't match any parameter (as in the first two calls), but of course it's not
required (as in the third).
For instance, an object could represent a person with a name property, age, address, etc., with
behaviors like walking, talking, breathing, and running. Or an email with properties like recipient
list, subject, body, etc., and behaviors like adding attachments and sending.
Classes in Python
565
Focusing first on the data, each thing or object is an instance of some class.
Classes are used to create new user-defined data structures that contain arbitrary information about
something.
A class just provides structure—it’s a blueprint for how something should be defined, but it doesn’t
actually provide any real content itself..
You start with the class keyword to indicate that you are creating a class, then you add the name
of the class
Also, we used the Python keyword pass here. This is very often used as a place holder where code
will eventually go. It allows us to run this code without throwing an error.
The (object) part in parentheses specifies the parent class that you are inheriting from (more on
this below.)
Instance Attributes
All classes create objects, and all objects contain characteristics called attributes (referred to as
properties in the opening paragraph). Use the __init__ () method to initialize (e.g., specify) an
object’s initial attributes by giving them their default value (or state). This method must have at
least one argument as well as the ‘self’ variable, which refers to the object itself (e.g., Dog).
In the case of our Dog() class, each dog has a specific name and age, which is obviously important
to know for when you start actually creating different dogs.
566
Similarly, the ‘self’ variable is also an instance of the class. Since instances of a class have
varying values, we could state Dog.name = name rather than self.name = name. But since not
all dogs share the same name, we need to be able to assign different values to different instances.
Hence the need for the special ‘self’ variable, which will help to keep track of individual instances
of each class.
Class Attributes
While instance attributes are specific to each object, class attributes are the same for all instances—
which in this case is all dogs.
So, while each dog has a unique name and age, every dog will be a mammal.
Instantiating Objects
Instantiating is a fancy term for creating a new, unique instance of a class.
For example:
We started by defining a new Dog() class, then created two new dogs, each assigned to different
objects. So, to create an instance of a class, you use the class name, followed by parentheses.
567
Then to demonstrate that each instance is actually different, we instantiated two more dogs,
assigning each to a variable, then tested if those variables are equal.
The output:
568
Instance Methods
Instance methods are defined inside a class and are used to get the contents of an instance. They
can also be used to perform operations with the attributes of our objects. Like the __init__ method,
the first argument is always self:
The Output:
In the latter method, speak(), we are defining behavior. What other behaviors could you assign to
a dog? Look back to the beginning paragraph to see some example behaviors for other objects.
569
Other Concepts in OOP
In addition to classes and objects, other objects in OOP are
• Inheritance
• Polymorphism
• Encapsulation
Scikit-learn
Scikit-learn is a python library that contains various classification, regression and clustering
algorithms including support vector machines, random forests, gradient boosting, k-means and
DBSCAN, and is designed to interoperate with the Python numerical and scientific libraries
NumPy and SciPy.
Scikit-learn is largely written in Python, and uses NumPy extensively for high-performance linear
algebra and array operations. Furthermore, some core algorithms are written in Cython to improve
performance.
Scikit-learn integrates well with many other Python libraries, such as matplotlib and plotly for
plotting, NumPy for array vectorization, pandas DataFrames, SciPy, and many more.
Theano
Theano is a Python library that allows you to define, optimize, and evaluate mathematical
expressions involving multi-dimensional arrays efficiently. extensive unit-testing and self-
verification – Detect and diagnose many types of errors
TensorFlow
TensorFlow is an end-to-end open source platform for machine learning. It has a comprehensive,
flexible ecosystem of tools, libraries and community resources that lets researchers push the state-
of-the-art in ML and developers easily build and deploy ML powered applications.
Keras
570
Keras is a high-level neural networks API, written in Python and capable of running on top of
TensorFlow and Theano. It was developed with a focus on enabling fast experimentation. Being
able to go from idea to result with the least possible delay is key to doing good research.
PyTorch
PyTorch is an open source machine learning library based on the Torch library, used for
applications in deep learning, computer vision and natural language processing. It is primarily
developed by Facebook's AI Research lab (FAIR). It is free and open-source software released
under the Modified BSD license.
Pandas
Pandas is a Python library for data manipulation and analysis. It offers data structures and
operations for manipulating numerical tables and time series.
Matplotlib
Matplotlib is a Python 2D plotting library which produces publication quality figures in a variety
of hardcopy formats and interactive environments across platforms.
Series
Pandas Series is a one-dimensional labeled array capable of holding data of any type for example:
integers, string, float, python objects, among others.
DataFrames
Pandas Series is a one-dimensional labeled array capable of holding data of any type for example
integer, string, float, python objects among others. The axis labels are collectively called index.
571
Creating a DataFrame in Pandas
Conclusion
At the end of this learning outcome, the learner should be able to demonstrate installation of Python,
syntax, data types, control structures, functions, object orientation and scientific modules.
Further Reading
https://docs.python.org/3/library/
9.3.4.3 Self-Assessment
Written assessment
1. Which are Python data types?
2. How is a python procedures created?
3. Why are functions used in a program?
4. How is a python variable declared
5. What is the role of the Numpy and Matplotlib libraries in Python?
Oral assessment
Why is it necessary to create a class before creating and using objects in a Python program?
Practical Assessment
1. Install Python in a computer.
2. Create an object based program from a class vehicle with two instance variables; colour and cost
and an instance method ReadData().
9.3.4.5 References
1. https://www.ics.uci.edu/~pattis/common/handouts/pythoneclipsejava/python.htm
573
9.3.5 Learning outcome 4: Develop Artificial Intelligence programs using Python
9.3.5.1 Learning Activities
Learning Outcome 4: Develop Artificial Intelligence programs using Python
Learning Activities Special Instructions
9.3.5.2 Information Sheet No. 9/LO5: Develop Artificial Intelligence programs using Python
Introduction
This learning outcome covers explaining Sci-Kit Learn, demonstrating machine learning with K-
Nearest Neighbours and Naïve Bayes Algorithm.
Sci-Kit Learn
Scikit-learn (Sklearn) is the most useful and robust library for machine learning in Python. It
provides a selection of efficient tools for machine learning and statistical modeling
This library, which is largely written in Python, is built upon NumPy, SciPy and Matplotlib.
The library is built upon the SciPy (Scientific Python) that must be installed before you can use scikit-
learn.
Prerequisites
Before using scikit-learn latest release, you first need to have Python and at least SciPy and Numpy
libraries installed.
The full steps are:
1. Install Python
2. Install Pip installed (If it is not already installed, download and install
pip: https://pip.pypa.io/en/stable/installing/)
3. Install numpy- pip install numpy
4. Install scipy: pip install scipy
5. Install sklearn: pip install sklearn
574
Test installation by opening a python interpreter and importing sklearn:
python
import sklearn
The principle behind nearest neighbor methods is to find a predefined number of training samples
closest in distance to the new point, and predict the label from these. The number of samples can be
a user-defined constant (k-nearest neighbor learning), or vary based on the local density of points
(radius-based neighbor learning).
The KNN algorithm assumes that similar things exist in close proximity. In other words, similar
things are near to each other.
Figure 123: K-Nearest Neighbour-Image showing how similar data points typically exist close to each other
575
3.1 Calculate the distance between the query example and the current example from
the data.
3.2 Add the distance and the index of the example to an ordered collection
4. Sort the ordered collection of distances and indices from smallest to largest (in
ascending order) by the distances
5. Pick the first K entries from the sorted collection
6. Get the labels of the selected K entries
7. If regression, return the mean of the K labels
8. If classification, return the mode of the K labels
For the simple task of finding the nearest neighbors between two sets of data, the unsupervised
algorithms within sklearn.neighbors can be used:
array([[0, 1],
[1, 0],
[2, 1],
[3, 4],
[4, 3],
[5, 4]]...)
>>> distances
array([[0. , 1. ],
[0. , 1. ],
[0. , 1.41421356],
[0. , 1. ],
[0. , 1. ],
[0. , 1.41421356]])
576
Because the query set matches the training set, the nearest neighbor of each point is the point itself,
at a distance of zero.
It is also possible to efficiently produce a sparse graph showing the connections between
neighboring points:
>>> nbrs.kneighbors_graph(X).toarray()
Consider a fictional dataset that describes the weather conditions for playing a game of
golf. Given the weather conditions, each tuple classifies the conditions as fit(“Yes”) or
unfit(“No”) for playing golf.
Here is a tabular representation of our dataset.
OUTLOOK TEMPERATURE HUMIDITY WINDY PLAY GOLF
577
OUTLOOK TEMPERATURE HUMIDITY WINDY PLAY GOLF
The dataset is divided into two parts, namely, feature matrix and the response vector.
• Feature matrix contains all the vectors(rows) of dataset in which each vector
consists of the value of dependent features. In above dataset, features are ‘Outlook’,
‘Temperature’, ‘Humidity’ and ‘Windy’.
• Response vector contains the value of class variable(prediction or output) for each
row of feature matrix. In above dataset, the class variable name is ‘Play golf’.
Assumption:
The fundamental Naive Bayes assumption is that each feature makes an:
• independent
• equal
Note: The assumptions made by Naive Bayes are not generally correct in real-world
situations. In-fact, the independence assumption is never correct but often works well in
practice.
578
>>> print(clf.predict([[-0.8, -1]]))
[1]
[1]
Conclusion
At the end of this learning outcome, the learner should be able to explain Sci-Kit Learn and
demonstrate machine learning with K-Nearest Neighbours and Naïve Bayes Algorithms.
Further Reading
1. https://docs.python.org/3/library/
2. https://scikit-learn.org/stable/modules/generated/sklearn.naive_bayes.GaussianNB.html
3. https://www.geeksforgeeks.org/naive-bayes-classifiers/
9.3.5.3 Self-Assessment
Written assessment
1. What are the pre-requisites for installing Scikit-learn?
2. What is the principle behind the KNN algorithm?
3. Which of the following is true about Naive Bayes?
a) Assumes that all the features in a dataset are equally important
b) Assumes that all the features in a dataset are independent
c) Both A and B
d) None of the above options
Oral assessment
What is the purpose of the SciKit-Learn library
Practical assessment
Demonstrate Machine Learning with K-Nearest Neighbours using a numpy array of your choice.
579
• Computer
• Python IDE
• Internet
• SciPy, Numpy, SciKit-Learn libraries
• Stationery
• Instruction material
9.3.5.5 References
1. Statistics, Data Mining, and Machine Learning in Astronomy: A Practical Python Guide for
the Analysis of Survey Data (2014)
2. https://www.dataquest.io/blog/sci-kit-learn-tutorial/
580
CHAPTER 10: ALGORITHMS AND DATA STRUCTURES
10.1 Introduction
This unit covers the competencies required to cover the key ideas involved in designing algorithms.
The unit explains how algorithms depend on the design of suitable data structures, and how some
structures and algorithms are more efficient than others. It involves studying some key data
structures, such as arrays, lists, queues and stacks, and their use in a range of different searching
and sorting algorithms.
581
10.3.2 Learning outcome 1: Understand fundamental principles of algorithms
10.3.2.1 Learning activities
Introduction
Definition of an Algorithm
An algorithm is a step by step method of solving a problem. It is commonly used for data
processing, calculation and other related computer and mathematical operations.
Characteristics of an Algorithm
1. Input specified
2. Output specified
3. Definiteness
4. Effectiveness
5. Finiteness
6. Independent
582
Algorithm Analysis
The analysis of algorithms is the determination of the amount of resources (such as time and
storage) necessary to execute them.
Complexities of algorithms
Suppose X is treated as an algorithm and N is treated as the size of input data, the time and space
implemented by the Algorithm X are the two main factors which determine the efficiency of X.
✓ Space
Space complexity is the space that is calculated or measured by counting the maximum memory space
required by the algorithm
✓ Time
Time complexity is the time that is calculated or measured by counting the number of key operations
such as comparisons in sorting algorithm.
Greedy algorithms
This is an algorithm is designed to achieve optimum solution for a given problem. In greedy algorithm
approach, decisions are made from the given solution domain. As being greedy, the closest solution
that seems to provide an optimum solution is chosen.
Greedy algorithms try to find a localized optimum solution, which may eventually lead to globally
optimized solutions. However, generally greedy algorithms do not provide globally optimized
solutions.
583
Divide and conquer algorithms
This is an algorithmic paradigm. A typical Divide and Conquer algorithm solves a problem using
following three steps.
1. Divide: Break the given problem into subproblems of same type.
2. Conquer: Recursively solve these subproblems
3. Combine: Appropriately combine the answers
✓ Divide /break
Divide: Break the given problem into subproblems of same type. When the smaller sub-problems
are solved, this stage recursively combines them until they formulate a solution of the original
problem. This algorithmic approach works recursively and conquer & merge steps works so close
that they appear as one.
✓ Conquer/solve
A divide-and-conquer algorithm works by recursively breaking down a problem into two or more
sub-problems of the same or related type, until these become simple enough to be solved directly.
The solutions to the sub-problems are then combined to give a solution to the original problem.
✓ Merge/combine the solutions to the sub-problems into the solution for the original problem.
In this approach, most of the algorithms are designed using recursion, hence memory management
is very high. For recursive function stack is used, where function state needs to be stored.
584
Approach: To find the maximum and minimum element from a given array is an
application for divide and conquer. In this problem, we will find the maximum and
minimum elements in a given array. In this problem, we are using a divide and conquer
approach(DAC) which has three steps divide, conquer and combine.
For Maximum:
In this problem, we are using the recursive approach to find maximum where we will see
that only two elements are left and then we can easily using condition i.e.
if(a[index]>a[index+1].)
In a program line a[index] and a[index+1])condition will ensure only two elements in
left.
In the above condition, we have checked the left side condition to find out the maximum.
Now, we will see the right side condition to find the maximum.
Recursive function to check the right side at the current index of an array.
max = DAC_Max(a, index+1, l);
// Recursive call
• Now, we will compare the condition and check the right side at the current index of a
given array.
In the given program, we are going to implement this logic to check the condition on
the right side at the current index.
// Right element will be maximum.
if(a[index]>max)
return a[index];
// max will be maximum element in a given array.
else
585
return max;
}
For Minimum:
In this problem, we are going to implement the recursive approach to find the
minimum no. in a given array.
int DAC_Min(int a[], int index, int l)
//Recursive call function to find the minimum no. in a given array.
if(index >= l-2)
// to check the condition that there will be two-element in the left
then we can easily find the minimum element in a given array.
{
// here we will check the condition
if(a[index]<a[index+1])
return a[index];
else
return a[index+1];
}
Now, we will check the condition on the right side in a given array.
Now, we will check the condition to find the minimum on the right side.
// Right element will be minimum
if(a[index]<min)
return a[index];
Conclusion
At the end of this learning outcome, the trainee should be able define an algorithm, explain
characteristics of an algorithm, analyze algorithms and explain their complexities, outline greedy
algorithms and demonstrate divide and conquer algorithms.
Further Reading
586
1. https://www.techopedia.com/definition/3739/algorithm
2. https://www.tutorialspoint.com/time-and-space-complexity-in-data-structure
3. https://www.geeksforgeeks.org/find-minimum-number-of-coins-that-make-a-change/
4. https://en.wikipedia.org/wiki/Divide-and-conquer_algorithm
5. https://www.google.com/search?client=firefox-b-d&q=Divide+%2Fbreak+algorithm
10.3.2.3 Self-Assessment
Written Assessment
1. Which of the following algorithmic paradigm is used in the merge sort?
a) Dynamic programming
b) BackTracking
c) Greedy method
d) Divide and conquer
2. Which of the following sorting algorithm does not have a worst case running time of
O(n^2)?
a) Insertion sort
b) Merge sort
c) Quick sort
d) Bubble sort
3. Which of the following sorting algorithm is stable
a) Insertion sort
b) Bubble sort
c) Quick sort
d) Both (A) and (B)
Oral Assessment
1.What is an algorithm?
2.Describe one greedy algorithm that you know
Practical Assessment
Given a value N, if we want to make change for N cents, and we have infinite supply of each of S
= { S1, S2, .. , Sm} valued coins, how many ways can we make the change? The order of coins
doesn’t matter.
587
10.3.2.5 References
1. https://www.tutorialspoint.com/design_and_analysis_of_algorithms
2. https://www.tutorialspoint.com/data_structures_algorithms/greedy_algorithms.htm
3. https://www.geeksforgeeks.org/divide-and-conquer-algorithm-introduction/
588
10.3.3 Learning Outcome 2: Understand fundamental concepts of data structures
10.3.3.1 Learning Activities
Learning Outcome No. 2: Understand fundamental concepts of data structures
2.1 Key concepts in data structures are explained · Activities may be carried out
2.2 Arrays are explained in groups or as individual
2.3 Array insertion operations are explained
2.4 Array delete, search and update are explained
2.5 Array operations are demonstrated using C++
This learning outcome covers explaining key concepts in data structures and explaining
arrays, inserting, deleting, searching and updating arrays and demonstrating array operations
using C++.
✓ Object
An object can be a variable, a data structure, a function, or a method, and as such, is
a value in memory referenced by an identifier.
✓ Data type
A set of values together with operations (specified as input-output behaviour). Example: integer,
date, string and others
Explanation of Arrays
An array is a data structure for storing more than one data item that has a similar data type. The
items of an array are allocated at adjacent memory locations. These memory locations are
called elements of that array. The total number of elements in an array is called length. The details
of an array are accessed about its position. This reference is called index or subscript.
589
Array insertion operations
✓ At the beginning
When the insertion happens at the beginning, it causes all the existing data items to shift one step
downward. Here, we design and implement an algorithm to insert an element at the beginning of
an array.
Arrays can be declared in various ways in different languages. For illustration, let's take C array
declaration.
590
As per the above illustration, following are the important points to be considered.
• Index starts with 0.
• Array length is 10 which means it can store 10 elements.
• Each element can be accessed via its index. For example, we can fetch an element at index 6
as 9.
Demonstrating Arrays in C++
Declaring Arrays
To declare an array specifies the type of the elements and the number of elements required by an
array as follows −
type arrayName [ arraySize ];
Input
Enter 5 numbers:
3
4
5
4
2
Output
18
#include <iostream>
using namespace std;
int main() {
int numbers[5], sum = 0;
cout << "Enter 5 numbers: ";
for (int i = 0; i < 5; ++i) {
cin >> numbers[i];
sum += numbers[i];
}
cout << "Sum = " << sum << endl;
return 0;
}
592
Given an array arr of size n, this article tells how to insert an element x in this array arr at a
specific position pos.
Approach:
1. First get the element to be inserted, say x
2. Then get the position at which this element is to be inserted, say pos
3. Then shift the array elements from this position to one position forward, and do this for all the
other elements next to pos.
4. Insert the element x now at the position pos, as this is now empty.
Below is the implementation of the above approach:
#include <iostream>
using namespace std;
593
for (i = n; i >= pos; i--)
arr[i] = arr[i - 1];
// insert x at pos
arr[pos - 1] = x;
return arr;
}
// Driver Code
int main()
{
int arr[100] = { 0 };
int i, x, pos, n = 10;
// element to be inserted
x = 50;
// Insert x at pos
insertX(n, arr, x, pos);
return 0;
}
Output:
594
1 2 3 4 5 6 7 8 9 10
1 2 3 4 50 5 6 7 8 9 10
Shifting an Element
We are taking the index we want deleted from the array and shifting all the elements after it one
position to the left and hence covering up that one vacant spot.
Take a look at the following code:
#include <iostream>
using namespace std;
int main()
{
int arr[5] = {}; //1
595
cout<<"Array is:\n"; //6
for(int i=0;i<5;i++)
{
if(arr[i]!='\0')
cout<<arr[i]<<" ";
}
}
Each part is described by using comments. A line breaks in the middle means that it’s the end of a
part.
Part 1:
We are creating an array of data type integer with name arr and size 5
We are declaring each variable to \0
Part 2:
Here we are accepting 5 elements from the user and storing them index wise into the array
Part 3:
We are defining 2 variables,
ind to store the index that wants to be deleted and
maxsize that stores the maximum size of the array
Part 4:
Here we are accepting the index that has to be deleted from the user and storing it in ind
Part 5:
Here we are first checking if the index is less than 0, which does not exist, or if it is greater than the
maximum size of the array which also does not exist
If the index is valid, we are starting a for loop from the index that needs to be deleted and going
until the max size of the array
In every iteration, we are moving the right side element one position to the left hence deleting the
unwanted element
But the last value gets filled with garbage. To prevent this, we are setting the last value to \0.
Part 6:
Here we are displaying the edited array.
The output of the above code is:
Enter 5 elements
1
2
3
596
4
5
Enter index to be deleted
2
Array is:
1245
// Header Files
#include <iostream>
#include<conio.h>
using namespace std;
#define ARRAY_SIZE 5
int main()
{
int numbers[ARRAY_SIZE], i ,search_key;
cout<<"Simple C++ Example Program for Simple Searching In Array\n";
// Read Input
for (i = 0; i < ARRAY_SIZE; i++)
{
cout<<"Enter the Number : "<< (i+1) <<" : ";
cin>>numbers[i];
}
Sample 1:
Sample 2:
Enter the Number : 1 : 45
Enter the Number : 2 : 67
Enter the Number : 3 : 48
Enter the Number : 4 : 35
Enter the Number : 5 : 78
Enter the key
23
Search Element is not in Array.
Conclusion
At the end of this learning outcome, the learner should be able to explain key concepts in data
structures and explain arrays, insert, delete, search and update arrays and demonstrate array
operations using C++.
Further Reading
1. https://www.computerhope.com/jargon/d/data.htm
2. https://www.guru99.com/array-data-structure.html
10.3.3.3 Self-Assessment
Written Assessment
1. Arrays are best data structures
a) For relatively permanent collections of data
598
b) For the size of the structure and the data in the structure are constantly changing
c) For both of the above situation
d) For none of the situation
2. The memory address of the first element of an array is called
a) Base address
b) Floor address
c) Foundation address
d) First address
3. Which of the following data structure is not linear data structure?
a) Arrays
b) Linked lists
c) Both of above
d) None of above
4. Finding the location of the element with a given value is:
a) Traversal
b) Search
c) Sort
d) None of above
5. Arrays are best data structures
a) For relatively permanent collection of data
b) For the size of the structure and the data in the structure are constantly changing
c) For both of the above situation
d) For none of the above situation
6. Finding the location of the element with a given array is:
a) Traversal
b) Search
c) Sort
d) None of the above
Oral Assessment
Explain hoe an element is deleted from an array using the shift method
Practical Assessment
Using an array of your choice, demonstrate how a simple search of an element can be done using
a C++ program.
599
10.3.3..5 References
1. https://www.tutorialspoint.com/data_structures_algorithms/array_insertion_algorithm.htm
2. https://www.tutorialspoint.com/data_structures_algorithms/array_data_structure.htm
600
10.3.4 Learning Outcome 3: Understand Linked lists
10.3.4.1 Learning Activities
Learning Outcome No. 3: Understand Linked lists
This learning outcome covers explaining linked lists, doubly linked lists, circular linked lists
and demonstrating basic operations for the various linked lists using C++
Linked lists
A linked list is a sequence of data structures, which are connected together via links. Linked List is
a sequence of links which contains items. Each link contains a connection to another link. Linked
list is the second most-used data structure after array. Following are the important terms to
understand the concept of Linked List.
• Link − each link of a linked list can store a data called an element.
• Next − each link of a linked list contains a link to the next link called Next.
• Linked List − A Linked List contains the connection link to the first link called First.
Linked list can be visualized as a chain of nodes, where every node points to the next node.
601
As per the above illustration, following are the important points to be considered.
• Linked List contains a link element called first.
• Each link carries a data field(s) and a link field called next.
• Each link is linked with its next link using its next link.
• Last link carries a link as null to mark the end of the list
✓ Basic operations
602
A circular linked list can be either singly linked or doubly linked.
• for singly linked list, next pointer of last item points to the first item
• In doubly linked list, prev pointer of first item points to last item as well.
✓ Basic operations
• insert − Inserts an element at the start of the list.
• delete − Deletes an element from the start of the list.
• display − Displays the list.
603
int main() {
insert(3);
insert(1);
insert(7);
insert(2);
insert(9);
cout<<"The doubly linked list is: ";
display();
return 0;
}
Output
The doubly linked list is: 9 2 7 1 3
Explanation
In the above program, the structure Node forms the doubly linked list node. It contains the data and
a pointer to the next and previous linked list node. This is given as follows.
struct Node {
int data;
struct Node *prev;
struct Node *next;
};
The function insert() inserts the data into the beginning of the doubly linked list. It creates a newnode
and inserts the number in the data field of the newnode. Then the prev pointer in newnode points to
NULL as it is entered at the beginning and the next pointer points to the head. If the head is not NULL
then prev pointer of head points to newnode. Finally the head is the newnode i.e. the linked list starts
from there. This is given below.
void insert(int newdata) {
struct Node* newnode = (struct Node*) malloc(sizeof(struct Node));
newnode->data = newdata;
newnode->prev = NULL;
newnode->next = head;
if(head != NULL)
head->prev = newnode ;
head = newnode;
}
The function display() displays the whole doubly linked list. First ptr points to head. Then it is
continuously forwarded to the next node until all the data values of the nodes are printed.
604
This is given below In the function main(), first various values are inserted into the doubly linked list
by calling insert(). Then the doubly linked list is displayed.
void display() {
struct Node* ptr;
ptr = head;
while(ptr != NULL) {
cout<< ptr->data <<" ";
ptr = ptr->next;
}
}
int main() {
insert(3);
insert(1);
insert(7);
insert(2);
insert(9);
cout<<"The doubly linked list is: ";
display();
return 0;
}
#include <iostream>
using namespace std;
struct Node {
int data;
struct Node *next;
};
struct Node* head = NULL;
void insert(int newdata) {
struct Node *newnode = (struct Node *)malloc(sizeof(struct Node));
struct Node *ptr = head;
newnode->data = newdata;
newnode->next = head;
605
if (head!= NULL) {
while (ptr->next != head)
ptr = ptr->next;
ptr->next = newnode;
} else
newnode->next = newnode;
head = newnode;
}
void display() {
struct Node* ptr;
ptr = head;
do {
cout<<ptr->data <<" ";
ptr = ptr->next;
} while(ptr != head);
}
int main() {
insert(3);
insert(1);
insert(7);
insert(2);
insert(9);
cout<<"The circular linked list is: ";
display();
return 0;
}
Output
The circular linked list is: 9 2 7 1 3
Explanation
In the above program, the structure Node forms the linked list node. It contains the data and a pointer
to the next linked list node. This is given as follows.
struct Node {
int data;
struct Node *next;
};
The function insert() inserts the data into the beginning of the linked list. It creates a newnode and
inserts the number in the data field of the newnode. If the head is NULL, then newnode points to
itself otherwise the last node in the circular linked list points to newnode. Then the head points to the
start of the list i.e. to the newnode. This is given below.
606
void insert(int newdata) {
struct Node *newnode = (struct Node *)malloc(sizeof(struct Node));
struct Node *ptr = head;
newnode->data = newdata;
newnode->next = head;
if (head!= NULL) {
while (ptr->next != head)
ptr = ptr->next;
ptr->next = newnode;
} else
newnode->next = newnode;
head = newnode;
}
The function display() displays the whole linked list. First ptr points to head. Then it is continuously
forwarded to the next node until all the data values of the nodes are printed. This is given below.
void display() {
struct Node* ptr;
ptr = head;
do {
cout<< ptr->data <<" ";
ptr = ptr->next;
} while(ptr != head);
}
In the function main(), first various values are inserted into the circular linked list by calling insert().
Then the linked list is displayed. This is given below.
int main() {
insert(3);
insert(1);
insert(7);
insert(2);
insert(9);
cout<<"The circular linked list is: ";
display();
return 0;
}
Conclusion
607
At the end of this learning outcome, the trainee should be able to explain linked lists, doubly linked
lists, circular linked lists and demonstrate basic operations for the various linked lists using C++.
Further Reading
https://www.tutorialride.com/data-structures/linked-list-types-in-data-structure.htm
10.3.4.3. Self-Assessment
Written Assessment
1. What Member function places a new node at the end of the linked list?
a) addNode
b) append Node
c) DisplayNode
d) StructNode
e) None of these
2. Linked lists are best suited
a) For relatively permanent collections of data
b) For the size of the structure and the data in the structure are constantly changing
c) Or both of above situation
d) For none of the above situation
3. How is linked list implemented
a) Nodes
b) Structure
c) Referential structures
d) None of these
4. The situation when in a linked list START=NULL is
a) Underflow
b) Overflow
c) Housefull
d) saturated
5. Linked lists are best suited for
a) Relatively permanent collections of data
b) The size of the structure and the data in the structure are constantly changing
c) Both of the above situation
d) None of the above situation
5. The operation of processing each element in the list is known as
a) Sorting
b) Merging
c) Inserting
d) Traversal
6. An object that can be used in accessing another object, is known to be
a) Pointer
608
b) Arrays
c) Structure
d) Reference
Oral Assessment
1. What is a circular linked list?
2. How is insertion operation performed in a singly linked list ?
Practical Assessment
Write a C++ program that implements circular doubly linked list.
10.3.4.5 References
1. https://www.tutorialspoint.com/cplusplus-program-to-implement-doubly-linked-list
2. https://www.tutorialspoint.com/cplusplus-program-to-implement-circular-singly-linked-list
609
10.3.5 Learning Outcome 4: Understand Stacks and Queues
10.3.5.1Learning Activities
Learning Outcome No. 4: Understand Stacks and Queues
4.1 Stacks and queues are defined · Activities may be carried out in groups
4.2 Stack and queue representation are outlined or as individual
4.3 Basic operations in stacks are explained
4.4 Basic operations in Queues are explained
4.5 4.5 Basic operations in stacks and queue are
demonstrated using C++
Definition of Stacks
Stacks are dynamic data structures that follow the Last In First Out (LIFO) principle. The last item
to be inserted into a stack is the first one to be deleted from it.
Representation of stacks
Basic operations
✓ Pop and push
610
❑ Definition of queues
Queue is an abstract data structure, somewhat similar to Stacks. Unlike stacks, a queue is open
at both its ends. One end is always used to insert data (enqueue) and the other is used to remove
data (dequeue). Queue follows First-In-First-Out methodology, i.e., the data item stored first
will be accessed first.
Representation of queues
Basic operations
✓ Enqueue
Queues maintain two data pointers, front and rear. Therefore, its operations are comparatively
difficult to implement than that of stacks.
The following steps should be taken to enqueue (insert) data into a queue −
• Step 1 − Check if the queue is full.
• Step 2 − If the queue is full, produce overflow error and exit.
• Step 3 − If the queue is not full, increment rear pointer to point the next empty space.
• Step 4 − Add data element to the queue location, where the rear is pointing.
• Step 5 − return success
✓ Dequeue
Accessing data from the queue is a process of two tasks − access the data where front is pointing
and remove the data after access. The following steps are taken to perform dequeue operation −
• Step 1 − Check if the queue is empty.
• Step 2 − If the queue is empty, produce underflow error and exit.
• Step 3 − If the queue is not empty, access the data where front is pointing.
611
• Step 4 − Increment front pointer to point to the next available data element.
• Step 5 − Return success.
Algorithm
push(item)
Begin
increase the top pointer by 1
insert item into the location top
End
pop()
Begin
item = top element from stack
reduce top pointer by 1
return item
End
peek()
Begin
item = top element from stack
return item
End
Example Code
#include <iostream>
using namespace std;
int stack[100], n = 100, top = -1;
void push(int val) {
612
if(top >= n-1)
cout<<"Stack Overflow"<<endl;
else {
top++;
stack[top] = val;
}
}
void pop() {
if(top <= -1)
cout<<"Stack Underflow"<<endl;
else {
cout<<"The popped element is "<< stack[top] <<endl;
top--;
}
}
void display() {
if(top>= 0) {
cout<<"Stack elements are:";
for(int i = top; i>= 0; i--)
cout<<stack[i]<<" ";
cout<<endl;
} else
cout<<"Stack is empty";
}
int main() {
int ch, val;
cout<<"1) Push in stack"<<endl;
cout<<"2) Pop from stack"<<endl;
cout<<"3) Display stack"<<endl;
cout<<"4) Exit"<<endl;
do {
cout<<"Enter choice: "<<endl;
cin>>ch;
switch(ch) {
case 1: {
cout<<"Enter value to be pushed:"<<endl;
cin>>val;
push(val);
break;
}
613
case 2: {
pop();
break;
}
case 3: {
display();
break;
}
case 4: {
cout<<"Exit"<<endl;
break;
}
default: {
cout<<"Invalid Choice"<<endl;
}
}
}while(ch! = 4);
return 0;
}
Output
1) Push in stack
2) Pop from stack
3) Display stack
4) Exit
Enter choice: 1
Enter value to be pushed: 2
Enter choice: 1
Enter value to be pushed: 6
Enter choice: 1
Enter value to be pushed: 8
Enter choice: 1
Enter value to be pushed: 7
Enter choice: 2
The popped element is 7
Enter choice: 3
Stack elements are:8 6 2
Enter choice: 5
Invalid Choice
Enter choice: 4
Exit
614
Demonstration of queues using C++
Queue operations are −
• EnQueue (int data) − Insertion at rear end
• int DeQueue()− Deletion from front end
Algorithm
Begin
function Enqueue() to insert elements in queue:
If queue is completely filled up then print “Overflow”.
Otherwise insert element at rear.
Update the value of rear
End
Begin
function Dequeue() to delete elements from queue:
If queue is completely empty then print “Underflow”.
Otherwise insert element from the front.
Update the value of rear.
End
Example Code
#include <bits/stdc++.h>
using namespace std;
struct Q {
int f, r, capacity;
int* q;
Q(int c) {
f = r= 0;
capacity = c;
q = new int;
}
~Q() { delete[] q; }
void Enqueue(int d) {
if (capacity == r) { //check if queue is empty or not
printf("\nQueue is full\n");
return;
} else {
q[r] = d; //insert data
r++; //update rear
}
615
return;
}
void Dequeue() {
if (f == r) {
printf("\nQueue is empty\n");
return;
} else {
for (int i = 0; i < r - 1; i++) {
q[i] = q[i + 1];
}
r--; //update rear
}
return;
}
void Display() //display the queue {
int i;
if (f == r) {
printf("\nQueue is Empty\n");
return;
}
for (i = f; i < r; i++) {
printf(" %d <-- ", q[i]);
}
return;
}
void Front() {
if (f == r) {
printf("\nQueue is Empty\n");
return;
}
printf("\nFront Element is: %d", q[f]); //print front element of queue
return;
}
};
int main(void) {
Q qu(3);
qu.Display();
cout<<"after inserting elements"<<endl;
qu.Enqueue(10);
qu.Enqueue(20);
qu.Enqueue(30);
qu.Display();
616
qu.Dequeue();
qu.Dequeue();
printf("\n\nafter two node deletion\n\n");
qu.Display();
qu.Front();
return 0;
}
Output
Queue is Empty
10 <-- 20 <-- 30 <--
30 <--
Front Element is: 30
Conclusion
At the end of this learning outcome, the trainee should be able to define stacks and queues, outline
stack and queue representations, explain basic operations of stacks and queues and demonstrate
basic operations in stacks using C++
Further Reading
1. https://www.google.com/search?client=firefox-b-d&q=stacks+and+queues
2. https://introcs.cs.princeton.edu/java/43stack/
3. https://www.guru99.com/c-sharp-queue.html
10.3.5.3 Self-Assessment
Written Assessment
.
1. The following data structure allows deleting data elements from front and inserting at rear
a) Stacks
b) Queues
c) Dequeue
d) Binary search tree
2. The stack uses which policy out of the following
a) LIFO
617
b) FIFO
c) Round robin
d) None of the above
3. The following name does not relate to stacks
a) FIFO lists
b) LIFO lists
c) Piles
d) Push-down lists
4. Basic mechanism for storing a large number of identically-typed objects are known to be
a) Arrays
b) Pointers
c) Stacks
d) Hash table
5. A linear list of elements in which deletion can be done from one end (front) and insertion
can take place only at the other end (rear) is known as a
a) Queue
b) Stack
c) Tree
d) Linked list
Oral Assessment
What operations are permitted for queues and stacks?
Practical Assessment
Demonstrate using C++ how elements are added to a queue
10.3.5.5 References
1. https://www.tutorialspoint.com/cplusplus-program-to-implement-queue
2. https://www.tutorialspoint.com/cplusplus-program-to-implement-stack
618
.
10.3.6 Learning Outcome 5: Understand Search Techniques
10.3.6.1 Learning Activities
Learning Outcome No. 5: Understand Search Techniques
This learning outcome covers defining Search, explaining linear and binary search and
demonstrating search techniques using C++
Definition of search
Searching is the process of finding a given value position in a list of values.
Linear Search
This is a sequential search made over all items one by one. Every item is checked and if a match is
found then that particular item is returned, otherwise the search continues till the end of the data
collection
Binary Search
Binary Search is a method to find the required element in a sorted array by repeatedly halving the
array and searching in the half.
This method is done by starting with the whole array. Then it is halved. If the required data value is
greater than the element at the middle of the array, then the upper half of the array is considered.
Otherwise, the lower half is considered. This is done continuously until either the required data value
is obtained or the remaining array is empty.
619
Input and Output
Input:
A list of data:
20 4 89 75 10 23 45 69
the search key 10
Output:
Item found at location: 4
Algorithm
linearSearch(array, size, key)
Input − An sorted array, size of the array and the search key
Output − location of the key (if found), otherwise wrong location.
Begin
for i := 0 to size -1 do
if array[i] = key then
return i
done
return invalid location
End
Example Code
#include<iostream>
using namespace std;
Binary search
#include<iostream>
using namespace std;
int binarySearch(int arr[], int p, int r, int num) {
if (p <= r) {
int mid = (p + r)/2;
if (arr[mid] == num)
return mid ;
if (arr[mid] > num)
return binarySearch(arr, p, mid-1, num);
if (arr[mid] > num)
return binarySearch(arr, mid+1, r, num);
}
return -1;
}
int main(void) {
int arr[] = {1, 3, 7, 15, 18, 20, 25, 33, 36, 40};
int n = sizeof(arr)/ sizeof(arr[0]);
int num = 33;
int index = binarySearch (arr, 0, n-1, num);
if(index == -1)
cout<< num <<" is not present in the array";
else
621
cout<< num <<" is present at index "<< index <<" in the array";
return 0;
}
Output
33 is present at index 7 in the array
In the above program, binarySearch() is a recursive function that is used to find the required element
in the array using binary search. The function takes the array, its lower bound and upper bound as
well as the number to be found as parameters. This is shown below.
Then the midpoint of the array is calculated. If the value at the midpoint is equal to num, then it is
returned. If the value is greater than num, then array calls itself recursively with the lower bound p
and upper bound mid-1. If the value is less than num, then array calls itself recursively with the lower
bound mid+1 and upper bound r. This can be seen by the following code snippet.
int binarySearch(int arr[], int p, int r, int num) {
if (p <= r) {
int mid = (p + r)/2;
if (arr[mid] == num)
return mid ;
if (arr[mid] > num)
return binarySearch(arr, p, mid-1, num);
if (arr[mid] < num)
return binarySearch(arr, mid+1, r, num);
}
return -1;
}
In the main() function, the array arr[] is defined. The size of the array is calculated and the
number to be found is specified. Then binarySearch() is called to find the index of the number. If
the value returned by binarySearch() is -1, then the number is not in the array. Otherwise the
index value is returned. This is given below.
int main(void) {
int arr[] = {1, 3, 7, 15, 18, 20, 25, 33, 36, 40};
int n = sizeof(arr)/ sizeof(arr[0]);
int num = 33;
int index = binarySearch (arr, 0, n-1, num);
if(index == -1)
622
cout<< num <<" is not present in the array";
else
cout<< num <<" is present at index "<< index <<" in the array";
return 0;
}
Conclusion
At the end of this learning outcome, the trainee should be able to define search, explain linear and
binary search and demonstrate search techniques using C++.
Further Reading
https://www.tutorialspoint.com/introduction-to-searching-algorithms
10.3.6.3 Self-Assessment
Written Assessment
1. What is searching?
2. Why is a binary search faster than a linear search search?
3. What is the key requirement to use a binary search method?
4. When is it best to use a linear search in a set of data?
5. Why is binary search considered a Divide and Conquer algorithm?
Oral Assessment
Explain How Binary Search Works
Practical Assessment
Write a C++ program that demonstrates how linear search would work with this array of numbers:
56, 3, 81, 34, 17, 40, and 21, to search for the value 17.
10.3.6.4 Tools, Equipment, Supplies and Materials
• Computers
• Internet
• Stationery
• C++ compiler
• Instruction material
10.3.6.5 References
1. https://www.tutorialspoint.com/Linear-Search\
2. https://www.tutorialspoint.com/binary-search-in-cplusplus
623
10.3.7 Learning Outcome 6: Understand Sorting Techniques
10.3.7.1 Learning Activities
Learning Outcome No. 6: Understand Sorting Techniques
This learning outcome covers defining sorting, outlining categories of sorting techniques,
explaining types of sorting algorithms and demonstrating sorting algorithm using C++.
Definition of Sorting
Sorting refers to ordering data in an increasing or decreasing fashion according to some linear
relationship among the data items
❑ Categories of sorting
✓ Stable and not stable sorting
Stable sorting algorithms preserve the relative order of equal elements, while unstable sorting
algorithms don’t. In other words, stable sorting maintains the position of two equals elements
relative to one another.
✓ Insertion sort
This algorithm can be best thought of as a sorting scheme which can be compared to that of sorting
a hand of playing cards, i.e., you take one card and then look at the rest with the intent of building
up an ordered set of cards in your hand
Algorithm
insertionSort(array, size)
Example Code
#include<iostream>
using namespace std;
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n]; //create an array with given number of elements
cout << "Enter elements:" << endl;
✓ Selection sort
The selection is a straightforward process of sorting values. In this method, to sort the data in
ascending order, the 0th element is compared with all other elements. If the 0th element is found to
be greater than the compared element, the two values get interchanged. In this way after the first
iteration, the smallest element is placed at 0th position. The technique is repeated until the full array
gets sorted.
Output
Given string is:: Tom, Boyaka, Matt, Luke
Selection Sorted::
Boyaka
Luke
Matt
Tom
Conclusion
628
At the end of this learning outcome, the trainee should be define sorting, outline categories of
sorting techniques, explain types of sorting algorithms and demonstrate sorting algorithm using
C++.
Further Reading
1. https://www.geeksforgeeks.org/sorting-algorithms/
2. https://www.softwaretestinghelp.com/sorting-techniques-in-cpp/
3. https://www.tutorialspoint.com/data_structures_algorithms/bubble_sort_algorithm.htm
10.3.7.3 Self-Assessment
Written Assessment
1. Which sorting algorithm is the slowest algorithm for large number of data?
a) Quick sort
b) Heap sort
c) Bubble sort
d) Shell sort
2. Which of the following is not a stable sorting algorithm?
a ) Insertion sort
b ) Selection sort
c ) Bubble sort
d ) Merge sort
3.If the number of records to be sorted is small, then …… sorting can be efficient.
a) Merge
b) Heap
c) Selection
d) Bubble
4.Which of the following is not an in-place sorting algorithm?
a) Selection sort
b) Heap sort
c) Quick sort
d) Merge sort
Oral Assessment
Using the following array, explain how it can be sorted using bubble sort: 56, 3, 81, 34, 17, 40, 21,
8, and 89
Practical Assessment
Write a C++ program to sort the above list using selection sort algorithm.
10.3.7.5 References
https://www.tutorialspoint.com/data_structures_algorithms/sorting_algorithms.htm
630
CHAPTER 11: WEB DESIGN SKILLS
11.1 Introduction
This unit covers the competencies required to demonstrate web design skills. It involves
understanding HTML basics, using HTML elements, demonstrating web page formatting, applying
styles, understanding JavaScript basics, using JavaScript data types, using JavaScript functions and
using JavaScript libraries.
631
11.3.2 Learning Outcome 1: Understand HTML basics
11.3.2.1 Learning Activities
Learning Outcome No. 1: Understand HTML basics
Learning Activities Special Instructions
Introduction
This learning outcome covers definition of the HTML and terminologies used in HTML, creation
of HTML file, explaining HTML core elements and adding HTML core elements to the file.
HTML Definition
HTML stands for Hypertext Markup Language
Hypertext Markup Language (HTML) is the standard markup language for documents designed to
be displayed in a web browser.
In simple terms it can be defined as the language used to create web pages.
HTML terminologies
1. Document-An HTML document is a file containing Hypertext Markup Language, and its
filename most often ends in the. Html extension.
2. Stylesheet -Stylesheet is a command or set of commands used to control the appearance and
layout of various elements on web pages, as well as simplify webpage design by avoiding
redundancy. Using stylesheets you can set the color and font of text, the size of form
textboxes, the margin between various elements on a webpage, and much more.
3. Element-An element is anything that appears on a webpage. An element could be a table, a
link, a textbox, a heading, etc.
An element consists of the grouping of a start tag, the element content, and an end tag.
4. Attribute-attributes are a modifier of an HTML element type. An attribute either modifies
the default functionality of an element type or provides functionality to certain element
types unable to function correctly without them. A attribute provides additional
information about an element. Attributes are always specified in the start tag.
<body>
The content of the document......
</body>
</html>
2. Saving as .html file
Save the file on your computer. Select File > Save as in the Notepad menu.
Name the file "index.htm" and set the encoding to UTF-8 (which is the preferred encoding for
HTML files).
633
<html>
<head>
<title>Title of the document</title>
</head>
<body>
The content of the document......
</body>
</html>
Save the file on your computer. Select File > Save as in the Notepad menu.
Name the file "index.htm" and set the encoding to UTF-8 .
Conclusion
At the end of this learning outcome, the learner should be able to define HTML and terminologies
used in HTML, create a HTML file, explain HTML core elements and add HTML core elements
to the file.
Further Reading
1. http://www.scriptingmaster.com/html/HTML-terms-glossary.asp
11.3.2.3 Self-Assessment
Written Assessment
1. What does HTML stand for?
a. Hyper Text Markup Language
b. Home Tool Markup Language
c. Hyperlinks and Text Markup Language
2. Which character is used to indicate an end tag?
a. <
b. <
c. /
d. *
3. Which HTML element defines the title of a document?
a. <meta>
b. <title>
c. <head>
4. Which HTML element defines information about the document?
a. <head>
634
b. <meta>
c. <title>
5. Which HTML element defines the content of the document?
a. <body>
b. <content>
c. <document>
6. Which HTML tag tag tells the browser that this is an HTML document?
a. <head>
b. <html>
c. <title>
Oral Assessment
1. What is Document type declaration in html and how is it declared?
2. What is the difference between <head> and <title> html elements?
Practical Assessment
1. Create an html code to show the following
a. Tittle -“ This is my first tittle”
b. Content –“ This is the content of the document”
2. Save the above document as .html file.
11.3.2.5 References
635
11.3.3 Learning Outcome 2: Use HTML Elements
11.3.3.1 Learning Activities
Learning Outcome No. 2: Use of HTML elements
Learning Activities Special Instructions
1.1 Basic HTML elements are explained Activities may be carried out
1.2 Basic HTML elements are added to a HTML document in groups or as individual
2.3 Attributes are defined Attributes are added to elements
Introduction
This learning outcome explains Basic HTML elements and how to add them to the document as
well as defining attributes and adding them to the elements.
636
Definition of attributes
1. Src - src attribute specifies the URL of the image. Note: When a web page loads; it is
the browser, at that moment that gets the image from a web server and inserts it into the
page. HTML images are defined with the <img> tag.The filename of the image source is
specified in the src attribute:
2. Alt –This attribute specifies an alternate text for an image, if the image cannot be
displayed. The alt attribute provides alternative information for an image if a user for
some reason cannot view it (because of slow connection, an error in the src attribute, or
if the user uses a screen reader).
3. Href- Specifies the URL (web address) for a link.HTML links are defined with
the <a> tag. The link address is specified in the href attribute.
<!DOCTYPE html>
<html>
<body>
<h1>The href Attribute</h1>
<p>HTML links are defined with the a tag. The link address is specified in the href attribute:</p>
<a href="https://www.education.go.ke/">This is a link</a>
<p>HTML images are defined with the img tag<br>and the filename of the image source is
specified in the src attribute:</p>
<img src="img_girl.jpg" width="100" height="150">
<p>The alt attribute should reflect the image content, so users who cannot see the image gets an
understanding of what the image contains:</p>
<img src="img_girl.jpg" alt="Girl with a jacket" width="100" height="150">
</body>
</html>
• Save the file on your computer. Select File > Save as in the Notepad menu.
• Name the file "index.htm" and set the encoding to UTF-8 .
Results for the above Example
637
Conclusion
At the end of this learning outcome, the learner should be able to explain basic HTML elements
and add them to the document as well as define attributes and add them to the elements.
Further Reading
1. https://www.w3schools.com/html/html_elements.asp
2. https://www.w3schools.com/html/html_attributes.asp
11.3.3.3 Self-Assessment
Oral Assessment
1. What are examples of HTML basic elements.
2. What are examples of HTML attributes.
Practical Assessment
1. Create a html program to demonstrate
i. Paragraph
ii. Line Breaking
iii. Line Heading
2. Create a html program to demonstrate the following attributes.
i. src
ii. alt
iii. href
639
11.3.3.5 References
640
11.3.4 Learning Outcome 3: Demonstrate Web Page Formatting
11.3.4.1 Learning Activities
Introduction
This learning outcome covers explaining layout elements, adding layout elements and adding
attributes to a HTML document.
Layout elements
1. <header> - Defines a header for a document or a section
2. <nav> - Defines a container for navigation links
3. <section> -Defines a section in a document
4. <footer> -Defines a footer for a document or a section
For Header
<!DOCTYPE html>
<html>
<body>
<article>
<header>
<h1>What Does WWF Do?</h1>
<p>WWF's mission:</p>
</header>
<p>WWF's mission is to stop the degradation of our planet's natural environment, and build a
future in which humans live in harmony with nature.</p>
</article>
</body>
641
</html>
For nav
Open notepad and type the following, and save as .html
<!DOCTYPE html>
<html>
<body>
<nav>
<a href="https://www.education.go.ke">TVET</a> |
<a href="https://www.education.go.ke">TVET 2</a> |
</nav>
</body>
</html>
For section
<!DOCTYPE html>
<html>
<body>
<section>
<h1>Section one</h1>
<p>The World Wide Fund for Nature .....</p>
</section>
<section>
<h1>Section 2 </h1>
<p>The .....</p>
</section>
</body>
</html>
For Footer
Open notepad and type the following, and save as .html
<!DOCTYPE html>
<html>
<body>
<footer>
642
<p>Posted by: Trancy </p>
<p>Contact information: <a href="mailto:[email protected]">
[email protected]</a>.</p>
</footer>
</body>
</html>
The class attribute specifies one or more class names for an element. The class attribute is mostly
used to point to a class in a style sheet. However, it can also be used by a JavaScript (via the HTML
DOM) to make changes to HTML elements with a specified class.
Example on class
<!DOCTYPE html>
<html>
<head>
<style>
h1.intro {
color: blue;
}
p.important {
color: green;
}
</style>
</head>
<body>
<h1 class="intro">Header 1</h1>
<p>A paragraph.</p>
<p class="important">Note that this is an important paragraph. :)</p>
</body>
</html>
Id-The id attribute specifies a unique id for an HTML element (the value must be unique within the
HTML document). The id attribute can be used on any HTML element and its id case-sensitive. The
id value must contain at least one character, and must not contain whitespace (spaces, tabs, etc.).The
id value can be used by CSS and JavaScript to perform certain tasks for the element with the specific
id value.
643
In CSS, to select an element with a specific id, write a hash (#) character, followed by the id of the
element:
Example of id
<!DOCTYPE html>
<html>
<head>
<style>
#myHeader {
background-color: lightblue;
color: black;
padding: 40px;
text-align: center;
}
</style>
</head>
<body>
<h2>The id Attribute</h2>
<p>Use CSS to style an element with the id "myHeader":</p>
<h1 id="myHeader">My Header</h1>
</body>
</html>
name -The name attribute specifies a name for the element. This name attribute can be used to
reference the element in a JavaScript. For form elements it is also used as a reference when the data
is submitted, For iframe element it can be used to target a form submission.
Example of name
<!DOCTYPE html>
<html>
<body>
<h1>The button name attribute</h1>
<form action="/action_page.php" method="get">
Choose your favorite subject:
<button name="subject" type="submit" value="HTML">HTML</button>
<button name="subject" type="submit" value="CSS">CSS</button>
</form>
</body>
</html>
Conclusion
At the end of this learning outcome, the learner should be able to explain layout elements, add
layout elements and add attributes to a HTML document.
644
Further Reading
1. https://www.w3schools.com/htmL/html_formatting.asp
11.3.4.3 Self-Assessment
1. Which one defines a header of a document?
a. <hi>
b. <head>
c. <header>
2. Which one specifies a navigation area for a html file?
a. <navigation>
b. <nav>
c. <navigate html>
3. Which one specifies a section in html?
a. <section>
b. <section in html>
c. <set>
4. Which one specifies a a footer of a document?
a. <footer>
b. <footer document>
c. <ft>
5. How do you specify id in html document?
a. <id="myHeader">
b. <id equals"myHeader">
c. id=myHeader
6. What does a name attribute specify?
Oral Assessment
1. What is the difference between class and id
2. What are examples of HTML attributes.
Practical Assessment
1. Create a html code to demonstrate the following
a. Class
b. Id
c. Name
2. Create a html code to demonstrate the following
a. section in a document
b. footer in a document
645
11.3.4.5 References
646
11.3.5 Learning Outcome 4: Apply Styles
11.3.5.1 Learning Activities
Introduction
This learning outcome covers explaining style concepts, applying internal styles and creating an
external CSS file.
Style Concepts
These describe how documents are presented on screens, in print, or perhaps how they are
pronounced.
1. background-Sets different background properties in one declaration. By default, your
webpage background is white in color. This can be changed either to put colours or
images.
Following is the syntax to use bgcolor attribute with any HTML tag.
<tagname bgcolor = "color_value"...>
2. padding- Used to add space inside the text field. When you have many inputs after
each other, you might also want to add some margin, to add more space outside of them.
The padding property allows you to specify how much space should appear between the
content of an element and its border −The value of this attribute should be either a
length, a percentage, or the word inherit. If the value is inherit, it will have the same
padding as its parent element. If a percentage is used, the percentage is of the containing
box.
The following CSS properties can be used to control lists. You can also set different
values for the padding on each side of the box using the following properties
• The padding-bottom specifies the bottom padding of an element.
647
• The padding-top specifies the top padding of an element.
• The padding-left specifies the left padding of an element.
• The padding-right specifies the right padding of an element.
• The padding serves as shorthand for the preceding properties.
3. Alignment- The align attribute specifies the horizontal alignment of the content inside a
<div> element.
Example
<h1 style="text-align:center;">Centered Heading</h1>
<p style="text-align:center;">Centered paragraph.</p>
4. Border- Sets the style of the borders for different elements. The values can be solid,
dotted , dashed , double , groove , ridge , inset and outset .
Example
h2 {
border-style: dashed;
border-width: 3px;
border-left-width: 10px;
border-right-width: 10px;
border-color: red;
}
But in the Internal CSS, we cannot control styles for multiple documents at once.
Internal style Sheet is applicable to the Page in which it is included.
Internal Style Sheet is used to style individual page.
Example
Internal styles are defined within the <style> element, inside the <head> section of an HTML
page:
<head>
<title>Internal css</title>
<style>
selector{
Property:value;
}
648
</style>
</title>
</head>
Example 2
<style>
P{
font-size: 20px;
font-weight: bold;
}
</style>
There is no limit to the number of external style sheets a single HTML page can use. Also, external
style sheets can be combined with embedded style sheets. Follow these steps to create an external
style sheet.
Steps:
1. Open notepad and write the code you want to execute. Eg
Hi {
Color :Orange
Text-align: Center
}
Save the document as style.css
2. Create a htm page and save it in the same folder you saved the document “style.css”
3. Link the two files. In the html page you created just before </head> add
<linkrel="stylesheet"href="style.css">
With an external style sheet, you can change the look of an entire website by changing just one file!
Example
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>This is a heading</h1>
649
<p>This is a paragraph.</p>
</body>
</html>
Conclusion
At the end of this learning outcome, the learner should be able to explain style concepts, apply
internal styles and create an external CSS file.
Further Reading
1. https://learnwebcode.com/how-to-create-your-first-css-file/
11.3.5.3 Self-Assessment
1. Where do we specify internal styled in html?
2. What does the padding-bottom specify?
3. What does the padding-top specify?
4. What does the padding-left specify?
5. What does the padding-right specify?
6. What is an external css file?
Oral Assessment
1. What are the padding properties?
2. What does the alignment property specify?
Practical Assessment
1. Write a html code to Set the top padding of <p> to "30px".
2. Create a external css file and link it to a html document.
11.3.5.5 References
1. Brooks, D. R. (2007). an Introduction to HTML and JavaScript: for Scientists and Engineers.
Springer Science & Business Media.
2. Michaud, T. (2013). Foundations of Web Design: Introduction to HTML & CSS. New Riders.
3. Bassett, L. (2015). Introduction to JavaScript object notation: a to-the-point guide to JSON. "
O'Reilly Media, Inc.".
4. http://www.landofcode.com/html-tutorials/html-stylesheets.php
5. https://teamtreehouse.com/library/inline-and-internal-styles
650
11.3.6 Learning Outcome 5: Understand JavaScript
11.3.6.1 Learning Activities
Introduction
This learning outcome covers the purpose of the JavaScript, outlining JavaScript syntax,
demonstrating access to HTML element using JavaScript Document Object model (DOM) as well
as demonstrating changing HTML elements using DOM.
Purpose of JavaScript
JavaScript was built for an important purpose: computers were once very slow in executing web
developers’ visions . This lead to the idea of a programming language that is executed on users’
computers when they access a webpage.
Anything that has been designed and implemented on web pages running that language would no
longer add to the load on hosting servers; instead, it would be a client-side language. Web pages
would become more responsive and less expensive.
JavaScript syntax
JavaScript syntax is the set of rules, how JavaScript programs are constructed.
var x, y, z; // How to declare variables
x = 5; y = 6; // How to assign values
z = x + y; // How to compute values
JavaScript Values
651
The JavaScript syntax defines two types of values: Fixed values and variable values.
Fixed values are called literals. Variable values are called variables.
JavaScript Literals- The most important rules for writing fixed values are;
1. Numbers are written with or without decimals.
2. Strings are text, written within double or single quotes:
JavaScript Variables -In a programming language, variables are used to store data values.
JavaScript uses the var keyword to declare variables. An equal sign is used to assign values to
variables.
Example
var x;
x = 6;
In this example, x is defined as a variable. Then, x is assigned (given) the value 6:
JavaScript Operators
JavaScript uses arithmetic operators ( + - * / ) to compute values
Example
(5 + 6) * 10
JavaScript Expressions
An expression is a combination of values, variables, and operators, which computes to a value.
JavaScript Keywords
JavaScript keywords are used to identify actions to be performed.The var keyword tells the
browser to create variables:
652
Example:
var x, y;
x = 5 + 6;
y = x * 10;
JavaScript Comments
Not all JavaScript statements are "executed".
Code after double slashes // or between /* and */ is treated as a comment.
Comments are ignored, and will not be executed:
Example
var x = 5; // I will be executed
JavaScript Identifiers
Identifiers are names .In JavaScript, identifiers are used to name variables (and keywords, and
functions, and labels).The rules for legal names are much the same in most programming
languages. In JavaScript, the first character must be a letter, or an underscore (_), or a dollar sign
($). Subsequent characters may be letters, digits, underscores, or dollar signs.
Note: Numbers are not allowed as the first character. This way JavaScript can easily distinguish
identifiers from numbers.
JavaScript is Case Sensitive. All JavaScript identifiers are case sensitive. The
variables lastName and lastname, are two different variables:
Hyphens:
first-name, last-name, master-card, inter-city.
Note: Hyphens are not allowed in JavaScript. They are reserved for subtractions.
Underscore:
first_name, last_name, master_card, inter_city.
653
firstName, lastName, masterCard, interCity.
Accessing HTML element attributes using the JavaScript Document Object Model (DOM)
Among the many talents of the DOM is its ability to retrieve and modify attributes inside HTML
elements. Using just a small set of methods, you can intuitively get the width of a DIV, change the
src of an image, or even remove the background image of the document!
getAttribute()
getAttribute() retrieves the corresponding value of an attribute. If the attribute does not exist, an
empty string is returned. For example:
setAttribute()
As the name implies, setAttribute() dynamically modifies the value of an element's attribute. The
method takes two parameters- the name of the attribute to set, and its new value. Using the same
<IMG> example above:
<script type="text/javascript">
//image src is now "another.gif"
document.getElementById("myimage").setAttribute("src","another.gif")
</script>
removeAttribute()
A whole new concept, removeAttribute() allows you to remove entire HTML attributes from an
element! This is particularly handy when an attribute contains multiple values which you wish to all
erase:
654
<div id="adiv" style="width:200px;height:30px;background-color:yellow">Some Div</div>
<script type="text/javascript">
//adiv now contains no style at all
document.getElementById("adiv").removeAttribute("style")
</script>
Example
var title = document.getElementById(‘header-title’);
Here we get the element with the id of header-title and save it into a variable.
Here we get the element with the id of header-title and save it into a variable.
655
document.replaceChild(new, old)
Replace an HTML element
document.write(text) Write into the HTML output stream
Conclusion
At the end of this learning outcome, the learner should be able to explain the purpose of the
JavaScript, outline JavaScript syntax, demonstrate access to HTML elements using JavaScript
Document Object model (DOM) and demonstrate changing HTML elements using DOM.
Further Reading
1. https://webplatform.github.io/docs/concepts/programming/the_purpose_of_javascript/
2. https://gabrieltanner.org/blog/javascript-dom-introduction
11.3.6.3 Self-Assessment
656
Practical Assessment
1. Create a Java Script code declaring a variable and assigning it a value.
11.3.6.5 References
1. Brooks, D. R. (2007). an Introduction to HTML and JavaScript: for Scientists and Engineers.
Springer Science & Business Media.
2. Michaud, T. (2013). Foundations of Web Design: Introduction to HTML & CSS. New Riders.
3. Bassett, L. (2015). Introduction to JavaScript object notation: a to-the-point guide to JSON. "
O'Reilly Media, Inc.".
4. Gabarró, S. A., & Gabarrâo, S. A. (2007). Web Application Design and Implementation: Apache 2,
PHP5, MySQL, JavaScript, and Linux/UNIX. Wiley-Interscience.
5. Haverbeke, M. (2014). Eloquent javascript: A modern introduction to programming. No Starch Press.
6. Morrison, M. (2007). Head first javascript. " O'Reilly Media, Inc.".
7. https://www.w3schools.com/js/js_syntax.asp
657
11.3.7 Learning Outcome 6: Use JavaScript Data types
11.3.7.1 Learning Activities
6.1 JavaScript data types are explained Activities may be carried out
6.2 Operations on the data types are demonstrated in groups or as individual
6.3 Operations on arrays are demonstrated
Introduction
This learning outcome covers explaining JavaScript data types, demonstrating operations on the
data types and demonstrating arrays.
Numbers
JavaScript has only one type of numbers. Numbers can be written with, or without decimals:
The number type has only one integer with two representations: 0 is represented as both -0 and +0.
(0 is an alias for +0.)
Example:
var x1 = 34.00; // Written with decimals
var x2 = 34; // Written without decimals
Extra large or extra small numbers can be written with scientific (exponential) notation.
Example
var y = 123e5; // 12300000
var z = 123e-5; // 0.00123
Booleans
Boolean represents a logical entity and can have two values: true and false.
Example
658
var x = 5;
var y = 5;
var z = 6;
(x == y) // Returns true
(x == z) // Returns false
JavaScript has function scope: Each function creates a new scope. Scope determines the
accessibility (visibility) of these variables.Variables defined inside a function are not
accessible (visible) from outside the function.
Example
Since local variables are only recognized inside their functions, variables with the same name can
be used in different functions.
Local variables are created when a function starts, and deleted when the function is completed.
Example
659
var carName = "Volvo";
// code here can use carName
function myFunction() {
// code here can also use carName
}
Automatically Global
If you assign a value to a variable that has not been declared, it will automatically become a
GLOBAL variable.
This code example will declare a global variable carName, even if the value is assigned inside a
function.
Example
myFunction();
function myFunction() {
carName = "Volvo";
}
Strict Mode
All modern browsers support running JavaScript in "Strict Mode".
In "Strict Mode", undeclared variables are not automatically global.
2. Variables declarations
There are three keywords available for declaring variables in JavaScript. They are the var, let, and
const keywords. JavaScript, being a dynamic and loosely typed language, also allows you to use
variables without pre-declaring them, but this is not considered good practice and is highly
discouraged.
To declare a variable, we use any of the above listed keywords, followed by the variable name as
follows:
var a;
let b;
const c = 5;
660
When you declare a variable using const, you must initialize it with a value -as we have done
above - which cannot afterwards be changed. When declaring variables with var and let, we can
optionally initialize the variables at the point of declaration:
var a = 2;
var b = 3;
Unlike what you might be used to from other languages, variables declared with the var keyword
have no block scope. In concrete terms, this means that if you declare a variable using var within
a for, or any non-function block, the variable's scope extends beyond the block to the end of the
block's parent scope.
On the other hand, if you declare a variable inside a function with the var keyword, the variable is
only available within the function definition, and cannot be accessed outside of the function. We,
therefore, say that variables declared with var are function-scoped.
Example
Functions forScope() {
For(var i=0; i<5;i++)
Console.log(i);//prints the values 0 through 4;
}
Console.log(i);//prints 5;
}
Inside the for header, we declare and initialize the i variable. Then inside the loop, we iterate from
0 while the value of i is less than 5, bumping i on each iteration. When the value of i equals 5, the
condition i < 5 evaluates to false, terminating our loop.
However, since i is declared using var, its scope extends from its point of declaration to the end
of the function. Hence, even after the loop, we can access the up-to-date value of i, which, in this
case is 5.
661
▪ They cannnot be re-declared within the same scope
Example
function letScope() {
let a = 5;
if (true) {
let a = "Jamie"; // using let creates a new a variable inside the "if" block
console.log(a); // prints "Jamie"
}
Example
const a = 2;
a = 3 // Error, reassignment is not allowed
const a = 2;
const a = 3 // Error, re-declaration is not allowed
Expressions
662
10; // Here 10 is an expression that is evaluated to the numeric value 10 by the JS interpreter10+13;
// This is another expression that is evaluated to produce the numeric value 23
2. Boolean
Boolean represents one of two values: true or false.
In programming, you will need a data type that can only have one of two values, like
• YES / NO
• ON / OFF
• TRUE / FALSE
For this, JavaScript has a Boolean data type. It can only take the values true or false.
Example
Boolean(10 > 9) // returns true
3.String concatenation
String expressions are expressions that evaluate to a string. Examples include the following
Example
'hello';
'hello' + 'world'; // evaluates to the string 'hello world'
✓ push()-The array_push() function inserts one or more elements to the end of an array.
Example:
663
Conclusion
At the end of this learning outcome, the learner should be able to explain JavaScript data types and
demonstrate operations on the data types and demonstrate arrays.
Further Reading
1. Bassett, L. (2015). Introduction to JavaScript object notation: a to-the-point guide to JSON. " O'Reilly
Media, Inc.".
11.3.7.3 Self-Assessment
11.3.7.5 References
1. Brooks, D. R. (2007). an Introduction to HTML and JavaScript: for Scientists and Engineers. Springer
Science & Business Media.
2. Gabarró, S. A., & Gabarrâo, S. A. (2007). Web Application Design and Implementation: Apache 2, PHP5,
MySQL, JavaScript, and Linux/UNIX. Wiley-Interscience.
3. https://medium.com/launch-school/javascript-expressions-and-statements-4d32ac9c0e74
4. https://www.w3schools.com/js/js_scope.asp
665
11.3.8 Learning Outcome 7: Use JavaScript Functions
11.3.8.1 Learning Activities
Introduction
This learning outcome covers explaining the structure of a Javascript function, creation and
invoking JavaScript functions and returning values from JavaScript functions.
In JavaScript, functions are first-class objects, because they can have properties and methods just
like any other object
Functions can be used the same way as you use variables, in all types of formulas, assignments,
and calculations.
Variables declared within a JavaScript function, become LOCAL to the function. Local variables
can only be accessed from within the function. Since local variables are only recognized inside
their functions, variables with the same name can be used in different functions. Local variables
are created when a function starts, and deleted when the function is completed.
Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).
The parentheses may include parameter names separated by commas: (parameter1, parameter2,
...)
The code to be executed, by the function, is placed inside curly brackets: {}
Example:
function name(parameter1, parameter2, parameter3) {
// code to be executed
}
• Function parameters are listed inside the parentheses () in the function definition.
• Function arguments are the values received by the function when it is invoked.
• Inside the function, the arguments (the parameters) behave as local variables.
We can create functions in JavaScript using the keyword function. The basic syntax to create a
function in JavaScript is shown below.
667
• When an event occurs (when a user clicks a button)
• When it is invoked (called) from JavaScript code
• Automatically (self invoked)
Syntax:
Invoking a Function as a Function:
If a function invocation is preceded with the new keyword, it is a constructor invocation.
It looks like you create a new function, but since JavaScript functions are objects you actually
create a new object:
Example
var myObject = {
firstName:"John",
lastName: "Doe",
fullName: function () {
return this.firstName + " " + this.lastName;
}
}
myObject.fullName(); // Will return "John Doe"
The fullName method is a function. The function belongs to the object. myObject is the owner of
the function.
The thing called this, is the object that "owns" the JavaScript code. In this case the value of this
is myObject.
668
When JavaScript reaches a return statement, the function will stop executing. If the function was
invoked from a statement, JavaScript will "return" to execute the code after the invoking statement.
Functions often compute a return value. The return value is "returned" back to the "caller":
Example: Calculate the product of two numbers, and return the result:
vary x = myFunction(4, 3); // Function is called, return value will end up in x
function myFunction(a, b) {
return a * b; // Function returns the product of a and b
}
Conclusion
At the end of this learning outcome, the learner should be able to explain the structure of a
Javascript function, create and invoke Javascript functions and return values from JavaScript
functions.
Further Reading
1. https://www.w3schools.com/js/js_function_invocation.asp
11.3.8.3 Self-Assessment
11.3.8.5 References
670
11.3.9 Learning Outcome 8: Use JavaScript Libraries
11.3.9.1 Learning Activities
Introduction
This learning outcome covers explaining the concept of JavaScript libraries and the JQuery
framework, demonstrating referencing of JQuery and JQuery syntax, explaining JQuery Events
and demonstrating DOM manipulation with JQuery.
Libraries concept
A JavaScript library is a library of pre-written JavaScript which allows for easier development
of JavaScript-based applications, especially for AJAX and other web-centric technologies.
JQuery framework
JQuery is a lightweight, "write less, do more", and JavaScript library. The purpose of JQuery is to
make it much easier to use JavaScript on your website.
JQuery takes a lot of common tasks that require many lines of JavaScript code to accomplish, and
wraps them into methods that you can call with a single line of code.
JQuery also simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM
manipulation.
671
There are lots of other JavaScript libraries out there, but JQuery is probably the most popular, and
also the most extendable.
Many of the biggest companies on the Web use JQuery, such as:
• Google
• Microsoft
• IBM
• Netflix
Referencing JQuery
The JQuery library is a single JavaScript file, and you reference it with the HTML <script> tag
(notice that the <script> tag should be inside the <head> section
Example:
<head>
<script src="jquery-3.4.1.min.js"></script>
</head>
JQuery syntax
The JQuery syntax is tailor-made for selecting HTML elements and performing some action on
the element(s).
Examples:
$(this).hide() - hides the current element.
$("p").hide() - hides all <p> elements.
$(".test").hide() - hides all elements with class="test".
$("#test").hide() - hides the element with id="test".
JQuery events
All the different visitors' actions that a web page can respond to are called events.
An event represents the precise moment when something happens.
Keyboard Events
a. Keypress
b. Keydown
c. Keyup
Mouse Events
a. Click
672
b. Dblclick
c. Mouseenter
d. Mouseleave
Form Events
a. Submit
b. Change
c. Focus
d. blur
Conclusion
At the end of this learning outcome, the learner should be able to explain the concept of JavaScript
libraries and the JQuery framework, demonstrate referencing of JQuery and JQuery syntax, explain
JQuery Events and demonstrate DOM manipulation with JQuery.
673
Further Reading
1. https://www.w3schools.com/js/js_function_invocation.asp
2. https://www.w3schools.com/jquery/jquery_events.asp
11.3.9.3 Self-Assessment
674
Oral Questions
1. What are the JQuery library features?
Practical
1. Demonstrate how to reference a JQuery.
2. Create a code to demonstrate basic Syntax in JQuery.
11.3.9.5 References
675
CHAPTER 12: GRAPHIC DESIGN
12.1 Introduction
This unit covers the competencies required to understand Graphic Design. It involves
understanding fundamentals of graphic design, understanding elements and principles of graphic
design, applying typography techniques, creating and editing of images and printing the design.
676
12.3.2 Learning Outcome 1: Understand Graphic Design Fundamentals
12.3.2.1 Learning Activities
Learning Outcome No.1: Understand Graphic Design Fundamentals
This learning outcome covers explaining graphic design, identifying graphic design equipment
based on the design, explaining application areas of graphic design and specifying requirements as
per a user’s needs.
Graphic Design
Definition
Graphic design is the craft of creating visual content to communicate messages. Applying visual
hierarchy and page layout techniques, graphic designers use typography and pictures to meet users’
specific needs and focus on the logic of displaying elements in interactive designs to optimize the
user experience.
Scanner
As a graphic designer, you may have faced the need to scan some designs either to work with, save
or share. Having a reliable high-resolution scanner can help with this problem.
677
However, picking one may not be that straightforward. There are a lot of things to consider.
This device should be able to cater to most of your needs efficiently and still produce good results.
To do this, it should have a good price and great specs.
Printer
Since printing services are very important for any designer, you need to have a printer.
Camera
For creatives who need to take, edit, and manage hyper-precise photos and videos, high quality
camera is required.
Digital Tablet
When it comes to designing and illustrating, you need a powerful tablet that will keep up with the
demands of your everyday projects.
A good tablet offers an artist a light, handy, responsive and electronic option to get projects done,
even when they aren’t at the office.
Graphic design can serve many functions. Just a few of the uses of graphic design include:
• Signage
• Corporate identity/branding
• Packaging (from water bottles to appliances)
• Printed materials (books, flyers, magazines, newspapers)
• Online art (banners, blogs, websites)
• Album covers
• Film and television titles and graphics
• T-shirt and clothing designs
• Greeting cards
Graphic designers use various methods to create and combine words, symbols, and images to create
a visual representation of ideas and messages. A graphic designer may use a combination of
typography, visual arts and page layout techniques to produce a final result. Graphic design often
refers to both the process (designing) by which the communication is created and the products
(designs) which are generated.
678
Common uses of graphic design include
• Identity (logos and branding)
• Publications (magazines, newspapers and books)
• Print advertisements
• Posters
• Billboards
• Website graphics and elements
• Signs
Product packaging. For example, a product package might include a logo or other artwork,
organized text and pure design elements such as images, shapes and color which unify the piece.
Composition is one of the most important features of graphic design, especially when using pre-
existing materials or diverse elements.
• Attractiveness
A good design is attractive. The user or the viewer is automatically directed towards an
attractive design. Maybe the design consists bright colors or could be of minimal colors in the
pool of bright-colored billboards.
• A Great Experience
A good design should delivers a good experience to the viewer. Sometimes, attractive designs
could be very annoying to view and the viewer ceases to look at it anymore. If it is on his/her
commute, he/she will start to ignore or neglect it. If it’s on webpage the same ignoring will
continue. Also, not only colors but the use of grotesque, unlikable or taboo images could also
bring some sort of disgust in viewer’s mind.
• Comprises Psychological/Scientific advantages
For instance, color red captures the attention most powerfully being a very visible color than
others. Also, it is said to increase enthusiasm, energy and confidence in the viewer. Color red
also has significances in many cultures being an auspicious color. Due to such believed traits
of the color it is mostly used in marketing ideas, companies with similar agendas and 77% of
the world’s flags comprises the color red. It all because of those attributes. Famous examples,
Coca Cola, Disney, KFC, etc.
• Long Lasting Impact/Appeal – There should be a long lasting impact on viewer’s minds.
• Conveys The Message Effortlessly
Graphical designs are used in creating websites, banners, infographics, etc. All of these
various information careers have one thing in common – a message. They are trying to convey
a message through their attractiveness, smartness, great experience or through any other trait.
Even if a design comprises all the other attributes for it to win a designing award, but fails to
convey the message for which it is designed, the whole design is considered failed.
• Achieves the intended aims.
679
Conclusion
At the end of this learning outcome, the learner should be able to explain graphic design, identify
graphic design equipment based on the design, explain application areas of graphic design and specify
requirements as per a user’s needs.
Further Reading
1. https://www.computercareers.org/basic-elements-and-principles-of-graphic-design/
2. https://1stwebdesigner.com/graphic-design-basics-elements/
12.3.2.3 Self-Assessment
Written Assessment
1. What is packaging?
2. What is corporate branding?
3. Define graphic design
Oral Assessment
1. Identify popular graphic design uses today.
Practical Assessment
As an ICT student, you are required to use suitable publication software and design a cover for the
college magazine called ‘Governance for better’as follows:
a) Use appropriate layout, paper balance, font variable and relevant pictures. Save it as your
name and personal number.
b) Insert a clip to represent the writer at the bottom of the cover
c) Use your name as the author of the magazine.
d) Insert automatic current date to appear as the date of publication
e) Apply suitable background for the cover.
f) Insert your name and personal number as a header.
g) Save and print your work.
12.3.2.5 References
1. http://phoenixwebsolutions.net/what-are-the-features-of-a-great-graphic-design
2. https://medium.com/@anahatrawal/10-basic-principles-of-graphic-design-b74be0dbdb58
680
12.3.3 Learning Outcome 2: Understand elements and principles of graphic design
12.3.3.1 Learning Activities
Learning Outcome No.2: Understand elements and principles of graphic design
2.1 Elements of graphic design are explained Activities may be carried out in groups or
2.2 Principles of graphic design are explained as individual
2.3 Elements of graphic design project as per user
requirements are selected
·
12.3.3.2 Information Sheet No 12/LO2: Understand elements and principles of graphic design
Introduction
This learning outcome covers explaining elements and principles of graphic design and selecting
elements of graphic design elements as per a user requirements.
Types of elements
These elements are what makes an effective design for both print and web pages. The main goal of
graphic design is to create an output that would attract attention and motivate the audience to act on
a specific action.
Lines
This is the most basic design element. There are different kinds of lines such as straight, curved,
thick, thin, solid and non-solid. Lines are primarily used to connect two endpoints and separate
sections of a design to make the eyes of the audience focus on the certain element.
The lines can create different effects and visual impact. While a thick, bold line draws attention
because of its visual power, the thin lines tend to go the other way. The color has an impact too,
dark colors are easier to see and draw more attention than light or pale colors.
The style of a line can also influence the way the user sees it. This style can easily be defined
through CSS and can be solid, dotted and dashed among others. The solid lines have a different
impact than the dotted ones, because they are more imposing.
681
Shapes
Shapes are basic geometric symbols such as squares, circles, and triangles. These shapes are often
used by graphic designers are boxes and borders. Moreover, shapes can also be icons, symbols, and
dingbats.
They are actually lines combined in different shapes. The forms are still popular and this is because
if there is something that needs to stand out, forms are one of the ways to do it.
Like lines, shapes are also associated by the human mind with different movements. For example,
circles are associated with movement and nature, while squares are often seen as structured, basic
designs. Just like with the lines, the color, style, background or texture of a shape can totally change
the viewer’s perception.
Fred Maya’s portfolio uses shapes to emphasize the logo and the previous work.
Texture
The texture is used as an addition to words, images or other elements in the graphic. For the non-
creative people, the texture is usually felt by touching. However, texture can also be implemented
visually. Visual Texture is made through the use of certain graphic design techniques. The goal of
682
visual texture is to focus the attention of the audience to the element on the design or it can serve as
a background as well. Furthermore, visual texture improves the appearance of the design as a
whole.
Texture styles include paper, stone, concrete, brick, fabric and natural elements, among flat or
smooth colors. Textures can also be subtle or pronounced and can be used sparingly or liberally.
They work with pretty much everything.
The textures can totally change a website and offer a totally different visual impact.
Color offers the most powerful visual impact at a single glance. Color is obvious and does not need
basic graphic skills to be noticed.
683
Feed Fever uses different colors for text, trying to emphasize the importance of each line with a
different nuance.
Value
The value of design represents how dark or light it looks to the audience. It also creates emphasis
and contrast. This works by placing a light object against a dark background to draw the viewer’s
attention.
If it is closely related to color, because value is more general and represents how dark or light a
design is. Value has a lot to do with mood too, only at a more profound level.
Understanding colors will take you close to perfection, but knowing how value works will take you
beyond this. Lighter designs offer a different impact and feeling than the dark ones and you need an
expert eye to notice differences and decide which one is the best.
Size
The element size represents the importance of a design. The larger the size, the more important the
information is and supposed to draw all the attention.
Space
The space and how it is used is crucially important in design. Lately the “white space” (also called
negative space) became used widely because it allows the human eye to read easier.
“White space”, does not mean precisely space filled with white, but every area of the design which
is only filled with the background color.
If there is a lot of negative space in your web design, it offers light and an open feeling. The lack of
white space will turn your design into an old-fashioned, cluttered one. The space has also a lot to do
with how the design is perceived by the human eye.
Google is the best example on how the negative space can be maximized.
Design Principles
The design principles are necessary to create effective design compositions on print and web.
Balance
Balance is very important in all good graphic designs. In most projects, balance is achieved by
using symmetrical, asymmetrical or radial symmetry. In a symmetrical balance, both sides of a
page layout are the same in weight, shape, lines and other elements. An asymmetrical balance
684
occurs when the two sides of a website aren’t the same, but they have similar elements. On the
other hand, a radial symmetry places elements in a circular pattern.
Balance is how the elements of a design are distributed throughout a layout. If the balance is good,
then stability is assured, although lately many designers go for unbalanced designs because they
are dynamic and offer a totally different perspective.
In other times, a designer puts an unbalanced design intentionally to focus attention on a single
element. However, you need to know the rules for unbalanced designs to work.
Balance is achieved through shapes, colors, textures, lines among other elements
Alignment
This basic principle refers to how the elements of a design line up along the top, bottom, center or
sides of the elements. Moreover, aligned elements do not need those of the same type and same
kind.
Alignment plays a pivotal role in creating a seamless visual connection with the design elements.
It gives an ordered appearance to images, shapes, and blocks of texts by eliminating elements
placed in a disheveled manner.
.
685
The text, shape and image have been lined up in the middle, creating an ‘Alignment.’
Proximity
When it comes to graphic design, proximity does not necessarily mean elements should be
positioned closely together. In graphics, it should be connected visually. Proximity means keeping
items that go together connected.
Proximity helps in creating a relationship between similar or related elements. These elements need
not be grouped, instead, they should be visually connected by way of font, colour, size, etc.
The above is an example of ‘Proximity.’ Here, a consistent shape (circle) and colours create an
organised design.
Repetition
As the name suggests, repetition means repeating the characteristics of similar elements. This is to
contribute the consistency of the outcome of the design. Moreover, repetition could also mean
creating a design rhythm. This said rhythm could be a series of elements with the same color, type,
and size. These similar elements would then appear as a complete unit.
686
In this online portfolio, the green colour is repeated across the page, creating cohesion and a
‘Repetition.’
Contrast
Contrast means the juxtaposition of opposing elements. This could be big versus small or dark
versus light. For graphic designers, using contrast can contribute to highlighting the elements of
design. Contrast is very easy to do. It can be achieved through contrast in colors, texture, type, and
other graphic elements.
Contrast happens when there is a difference between the two opposing design elements. The most
common types of contrast are dark vs. light, contemporary vs. old-fashioned, large vs. small, etc.
Contrast guides a viewer’s attention to the key elements, ensuring each side is legible.
This image has been darkened to allow the text to create a sharp contrast against the background.
687
Emphasis
Say you’re creating a poster for a concert. You should ask yourself: what is the first piece of
information my audience needs to know? Is it the band? Or the concert venue? What about the day
and the cost of attending?
Make a mental outline. Let your brain organize the information and then lay out your design in a
way that communicates that order. If the band’s name is the most essential information, place it in
the center or make it the biggest element on the poster. Or you could put it in the strongest, boldest
type.
Learn about color theory and use strong color combinations to make the band name pop.
Like writing without an outline or building without a blueprint, if you start your composition
without a clear idea of what you’re trying to communicate, your design will not succeed.
Harmony
Harmony in graphic design is the arrangement of elements such as: colors, shapes, and symmetry to
create a pleasing image that works all together.
Pattern
Patterns are nothing more than a repetition of multiple design elements working together.
Wallpaper patterns are the most ubiquitous example of patterns that virtually everyone is familiar
with.
In design, however, patterns can also refer to set standards for how certain elements are designed.
Proportion
Proportion is the visual size and weight of elements in a composition and how they relate to each
other. It often helps to approach your design in sections, instead of as a whole.
688
Grouping related items can give them importance at a smaller size—think of a box at the bottom of
your poster for ticket information or a sidebar on a website for a search bar. Proportion can be
achieved only if all elements of your design are well-sized and thoughtfully placed. Once you
master alignment, balance, and contrast, proportion should emerge organically.
Unity
Everyone has seen a website or other design out there that seemed to just throw elements on a page
with no regard for how they worked together. Newspaper ads that use ten different fonts come to
mind almost immediately.
Unity refers to how well the elements of a design work together. Visual elements should have clear
relationships with each other in a design. Unity also helps ensure concepts are being communicated
in a clear, cohesive fashion. Designs with good unity also appear to be more organized and of
higher quality and authority than designs with poor unity.
Conclusion
At the end of this learning outcome, the learner should be able to explain elements and principles
of graphic design and select elements of graphic design elements as per a user requirements.
Further Reading
https://www.computercareers.org/basic-elements-and-principles-of-graphic-design/
12.3.3.3 Self-Assessment
Written Assessment
1. What is a design element?
2. Which are the key design elements that should be considered for a poster?
3. Why is the balance principle important in graphic design?
4. How would you tell that graphic elements lack unity and harmony?
Oral Assessment
1. What do you understand by warm and cool colour?
2. Which specific graphic decisions should apply in website creation?
689
Practical Assessment
Design a roll-up banner with for “Awareness of Against Use of Drugs” message.
12.3.3.5 References
1. https://1stwebdesigner.com/graphic-design-basics-elements/
2. https://medium.com/@anahatrawal/10-basic-principles-of-graphic-design-b74be0dbdb58
690
12.3.4 Learning Outcome 3: Apply typography techniques
12.3.4.1 Learning Activities
Learning Outcome No.3: Apply typography techniques
Introduction
This learning outcome covers explaining typography and typography guidelines, demonstrating
measurements and standards of typography and selecting typography techniques for a graphic
design project as per user requirements.
Typography techniques
Definition
These are techniques to help you present your ideas to viewers and get the most out of each word.
The principles, that address each of these elements, revolve around one central idea: good
communication.
Good typography is imperative to any situation where you want to transmit an idea to another
person via text — such as a website, blog post, magazine ad, interface, billboard, or newsletter.
Types of techniques:
Typeface
There are three basic kinds of typefaces: serif, sans-serif, and decorative.
691
Typeface categories.
Notice the little embellishments at the end of lines on the serif font, circled in red. Those are
actually called “serifs,” hence the name of the font category. “Sans” means “without,” which is why
all fonts without serifs are called “sans-serif.” Decorative fonts are such that don’t really fit strictly
in either of those categories, and are often elaborate, creative fonts used for titles.
It’s best to use a maximum of three fonts in a given design project, and two is often even better. It
keeps your design uncluttered and simple. Try to pair serif fonts with sans-serif fonts, such as
putting main body text in a serif font and putting your title in a sans-serif font, or vice-versa.
Use decorative fonts minimally, and almost never for main-body text, because they often have low
readability and just won’t look right most of the time.
Hierarchy
One of the main roles of hierarchy is to help keep your ideas organized, so that viewers can always
identify which category of information they are reading. A typical example would be a website,
where the title of the site is at the top of the page in a large header, while main navigation pages
within the website are listed below the header in a smaller font.
This is a visual cue that helps readers identify the context of the text without even having to
consciously think about it. Notice that in the website below all of the text is in the same size, font,
weight, and color, with little distinction. All of the text appears equal and nothing jumps out. This is
bad design
692
Contrast
Contrast makes text interesting and can help you communicate which ideas you want to emphasize.
Varying size, typeface, weight, color, and style can give your designs a big impact as well as make
your ideas organized. Below, you can see how contrast helps you to give your text an interesting,
attention-grabbing, and even more meaningful appearance.
Below, the word “Small” is black, aligned right, lightweight, in an italic serif typeface with
increased space between letters. “Large” is red, heavy weight, in a regular sans-serif typeface, and
is about 10x bigger than the word “Small.”
No contrast = boring!
Clearly, elements of contrast make the first design stand out much more than the second design,
where both words have the same styling.
Consistency
Consistency is a key principle for all typography. Consistent fonts are especially important, as using
too many can lead to a confusing and messy look, so always use the same font styling for the same
information.
Decide on a hierarchy of styles and stick to it. Even though you may have many levels of hierarchy,
you should keep to an overall theme for the design.
The “Chapter One” page below has a pleasing design with only two font faces, two colors, and
three font sizes. Even though only two font faces are used, hierarchy is achieved by using size and
color. All of the text is left-aligned except the page number, providing clean, consistent lines.
However, on the “Chapter Two” page, there are four different font faces, four colors, four font
sizes, and each element has a different alignment — all of this creates a messy, unattractive design.
693
Alignment
Alignment refers to the “line,” that the text orients towards. It can apply to a whole body of text,
individual words, or even images. Alignment should be as consistent as possible and every element
of your design is meant to align to one of the other elements in some way, to create equal sizes and
distances between objects.
For example, you may want the logo to align in size with your header, and you may want your body
text to align with the same margins the header falls in.
Left alignment is usually the best choice, and right alignment can also be interesting. However,
avoid using right alignment for body text.
694
Whitespace
Whitespace refers to the empty space around objects or text, and can take the form of margins,
padding, or just an uncluttered area. It creates a pleasing visual experience and can even draw
attention to text. In the first box below, the text is crammed against the bounding box, making it
hard to read. In the second box, the text has breathing room and the design even looks more stylish.
We often think flashy colors and bold fonts are the only way to draw attention to text, but
amazingly, white space can be the best way of drawing the viewer in, as it indicates that whatever is
within the large field of empty space must be important.
695
Color
Color can really help to set the mood for your design, and getting it right can make your text stand
out. There are three main components of color:
696
3. Value — lightness or darkness of the color
Remember to contrast hue, saturation, and value in a way that makes your text easy to read. A good
way to tell if your colors have enough contrast is to view your design in grayscale and if it doesn’t
look good you may need to tweak values.
Notice how the text on the right become almost invisible in grayscale, while the image on the left
still looks great:
One situation where contrast just isn’t enough is with light text on a dark background even if the
contrast seems high, it just isn’t as easy to read as dark text on a light background, especially with
small text, so use that style sparingly!
697
When making any design, asking yourself these three questions will help you recall the
aforementioned guidelines and principles:
● Is my text readable?
● Is my styling consistent?
● Does my styling use contrast?
Typography guidelines
Try to conceptualise the mindset of your targeted audience and make it rule to ask yourself some
primary questions:
Typography is a union of art and science. You need to get the basics right to move forward with the
typefaces.
As a beginner, many designers choose centre alignment. However, centre alignment and justified
text make the copy hard to read.
Left Alignment
This is the best kind of alignment because the text starting from the left is easily readable.
Right Alignment
• Another type of conventional alignment is when the text is aligned towards the right side.
• This practice is commonly used in case of resumes and CV.
• It covers an exciting space of the page making the text easy on the eyes.
• You can also use right alignment to write paragraphs.
Justified
• Using ‘Justified’ can be a designer’s biggest mistake.
• If used carelessly, setting the text as justified can lead to substantial spaces in between the
letters or words, disrupting the user experience and content engagement.
699
8 — Typography comes with inspiration
• The design is a mere play of inspirations. Having inspiration for your work helps you in
bringing the best in design.
• All this creative inspiration cannot be found online. As a designer, one can get design
inspiration from their surroundings.
• Look at fonts you see on billboards and advertisements.
• Look for graphics around you.
• Pay attention to all the detailing that makes the piece attractive.
• Do you think the typography is compelling enough?
• What impact it had on you as a reader?
• Figuring out the best typefaces in design and working on details to determine what makes
them engaging makes way for discoveries.
Measurements
Typographic Measurement
The measurements you use every day—whether they’re inches and feet or centimeters and meters—
are fixed, or absolute, measurements. That is, an inch is always an inch and a meter is always a
meter. Type has its own equivalents, which are the pica and its subdivision, the point
.
• The height of type is measured in points, and the width of a letter or a line of type is
measured in picas. Point size is the height of the body of a letter in a typeface; originating in
metal type, it was a slug of lead the typeface was set upon.
• The width of a typeface is measured in characters per pica. Most type is available in sizes
ranging from 5 points to 72 points. Type that is 14 points and less is used for setting text and
is called text type or body copy. Sizes above 14 points are used for display type.
• Line length, which is the horizontal length of a line of type, is measured in picas.
• Approximately 6 picas = 1 inch; 12 points = 1 pica; approximately 72 points = 1 inch.
• Determining a suitable line length for readability depends on the design of the
specifictypeface, type size, line spacing, and length of the content.
700
Spatial Measurement
A designer measures type as well as the spatial intervals between typographic elements.
These intervals occur between letters, between words, and between two lines of type.
● The spatial interval between letters is called letter spacing
● Adjusting the letter spacing is called kerning
● The spatial interval between words is word spacing
● The spatial interval between two lines of type is line spacing, traditionally called leading in
metal type, where strips of lead of varying thickness (measured in points) were used to
increase the space between lines of type
Many people still use the term leading to mean line spacing: the distance between two lines of type,
measured vertically from baseline to baseline.
In metal type, letter spacing and word spacing are produced by the insertion of quads—metal blocks
shorter than the type height—between pieces of metal type.
The Em in Typesetting
The fundamental relative unit in typography is the em. An em is the same size as the type currently
being set, so if you’re setting 11-point type, an em equals 11 points. Despite the sound of its name,
an em is not the width of an M; in fact, an M is rarely a full em wide.
One such adjustment is kerning, the adjustment of spacing between particular letter pairs to correct
problems arising from the shapes of those letters. The letters in To, for example, are usually kerned
closer together, because the empty space under the crossbar of the T creates a gap between it and
the o next to it.
Likewise, rn in some typefaces have to be kerned apart to avoid having them look like an m.
Digitally generated typefaces generally have tables of kerning information built into them – which
can be adjusted by the designer.
701
of the text. These factors include character shapes, size of counters, character width, weight,
ascender and descender length and stroke contrast.
Picking a good font is a good starting point for making text legible. However, making this choice
may be difficult because of the sheer number of fonts that are available.
Certain elements of the text will appear highlighted to the visitor if a font is chosen that has
variations in height and weight. Helvetica Neue has other styles than bold and italic such as light or
ultra light. Fonts such as these can be effective if focusing on the typography of the site.
A legible font will usually be one that has conventional letterforms and design characteristics
which are consistent. These types of fonts are likely to be the ones which will deliver legible
results.
The process of adjusting spacing between characters to make the font proportional is known as
kerning. This improves the appearance of the font and quality typefaces will have built in kern
pairs so this effect can be easily achieved. Letter spacing is also an important aspect of choosing a
legible font and fonts that are too open should be avoided.
Titles and subheadings can be used to attract a viewer’s attention and prevent them from leaving the
page. Content can be prioritized through the use of feature such as bold and italic, and the use of
color or the case of the font.
The size of the type is an important consideration to bear in mind when designing a web page. A
larger type will be a better choice because this will be easier to read on lower resolution screens and
smaller devices such as laptops and tablets.
There should be a good amount of contrast between the text and the background. If the
background is dark then the text should be light or vice versa. This will ensure that the text is easy
to read and the full impact of the text that has been chosen can be achieved.
A combination of different typefaces may be effective. It is important that these fonts are different
in order to get the full effect of this. A good solution is to pick one serif font and one sans serif.
This will create contrast and give the text a cohesive look, especially if fonts are chosen from the
same designer.
702
The typeface should not overpower the text as this may distract from the message. The purpose
of the typeface is to make the text easy to read and if this is not the case then there is a risk that the
reader will simply look at the typeface and not actually read the text.
When the font is being printed from a screen the contrast and brightness should be adjusted to
enable the font to look as it will when it is printed. This can assist the designer in deciding whether
the typeface that has been chosen is achieving the desired effect.
Once the font has been printed off it can be shown to friends and family to get their opinion. If
more than one font has been used then they may be able to assist in choosing the final font to be
used.
The ultimate decision about which font is chosen will depend on the personal preferences of the
designer. There is no right and wrong font to use in print, but there are certain fonts that will work
better than others.
Conclusion
At the end of this learning outcome, the learner should be able to explain typography and
typography guidelines, demonstrate measurements and standards of typography and select
typography techniques for a graphic design project as per user requirements.
Further Reading
https://www.computercareers.org/basic-elements-and-principles-of-graphic-design/
12.3.4.3 Self-Assessment
Written Assessment
1. What is typography?
2. What Is Hyphenation?
3. How does typography play an important role in designing?
4. What is spacing around letters?
5. What are the elements of typography?
Oral Assessment
1. Why is kerning adjustment important?
2. Outline the measurement guidelines for typography elements?
Practical Assessment
3. Design a visiting card for a pastry shop.
4. Design a webpage blog for a fiction-writer author
12.3.4.5 References
1. https://1stwebdesigner.com/graphic-design-basics-elements/
2. https://medium.com/@anahatrawal/10-basic-principles-of-graphic-design-b74be0dbdb58
704
12.3.5 Learning Outcome 4: Create and edit images
12.3.5.1 Learning Activities
Learning Outcome No.4: Create and edit images
4.1 Software and tools for graphic design and Activities may be carried out in groups
photography are identified or as individual
4.2 Image file types are explained.
4.3 Letterforms, lines of type and body copy are created
using appropriate software ·
4.4 Images are created and manipulated using appropriate
software.
Introduction
This learning outcome covers identifying software and tools for graphic design and photography,
explaining image file types, creating letterforms, lines of type and body copy and creating and
manipulating images using appropriate software.
Whether you are an amateur graphic designer or an experienced digital artist, using the right tools
can multiply your talent exponentially. A well-built graphic design software provides intuitive
controls and flexibility that can be easily understood by a beginner but also has vastly superior tools
for an experienced user.
Each of the software is characterized by its features, ease of use, performance, cost, and availability.
Many paid graphic design software provide a free trial for users to give them a better understanding
of the product.
Raster
Raster graphics are the most common type of image files. They are comprised of a grid of pixels
where each pixel represents an individual color within the image. Both Web graphics and digital
photos are stored as raster graphics. While some raster image formats are uncompressed, most use
some type of image compression.
Raster images can be low to high quality images containing pixels. The images of raster category
are used for simple to complex purposes. Each image file type has its own details and different
extensions.
Common raster image file extensions include .BMP, .TIF, .JPG, .GIF, and .PNG.
JPEG
JPEG is the most common image format on World Wide Web and most of the digital cameras
produce built-in JPEG image. The compression degree of JPEG image can be adjusted and
typically, it gains 10:1 compression and you can feel the loss of quality in image. This filename
extension is usually .JPEG or .JPG.
A JPEG image is easily editable or compressible, but once you edit a high quality jpeg image, you
cannot regain that quality again by reversing.
The compression benefit has made JPEG image more popular than other image formats. Such a
reduced image data and compressed image format is useful for responsive presentation in web
though it is not usable for drawing and iconic graphics which need to be enlarged.
For medical and scientific imaging data creation, this format is not suitable as JPEG format being a
lossy compression method. It cannot regain its original quality if it undergoes editing several times.
JPEG 2000
This format offers both lossy and lossless storage. It compression methods improve quality and
compression ratios. This file format also includes the features that are missing in JPEG. It is now
not common as general JPEG, but this format is used in professional movie editing especially for
individual movie frames.
GIF
706
GIF is has been quite popular in web for lightweight animations. Currently, they are also used
instead of emoticons in various chat apps. But, for scanned images containing text and for general
images with texts also render clear visibility on web.
GIF, a bitmap image format becomes more popular because of its wide support and portability. GIF
supports up to 8 bits per pixel for each image and animations. It also allows separate palette of 256
color for each frame.
PNG
It is an acronym of Portable Network Graphics. It is a raster image format which supports lossless
data compression and also background transparency. In fact, for having transparent effects, PNG
images are best options for professionals who are related to web.
PNG image format supports palette-based images, grayscale images, and full color RGB images. Its
file extension is .png and if you want to get a transparent background image, you have to get PNG
image format. This image format is mostly used for getting transparent image background for logo,
banner and such.
Bitmap/BMP
It is also known as bitmap image file or raster graphics file which is a dot matrix data structure. It is
used to store bitmap digital images free from display device barrier. This file format is capable to
store two dimensional digital images. It can store data of raw images.
One of the many advantages of Bitmap formats is it can keep its quality while saving in multiple
other raster formats. It is supported by most of the virtual devices. Before JPEG, BMP was quite
popular.
TIFF
It is a short form of Tagged Image File Format for storing raster graphics images. This format is
popular among graphic artists, photographers, and print media. Scanning, word processing, faxing,
optical character recognition, desktop publishing, image manipulation, and page-layout applications.
TIFF is flexible, adaptable, and capable of storing image data in a lossless format.
BPG
It is a new image format created for replacing JPEG format to cope with quality or file size issue. Its
file size is much smaller that JPEG and high compression ratio. It is supported by the most web
browser. It supports all color spaces and lossless compression. It also supports various Meta data.
It is a new image format and is intended to replace the JPEG. It has a lot of advantages. It offers high
compression ratio and files are much smaller. It is supported by the most web browsers. This format
can reduce losses while converting and support all spaces of color. It can also contain metadata and
offers lossless compression.
707
Vector
Mostly used for quality logo, banner, marketing design, and some other corporate identity designs.
For advertising purposes, you should use images of high quality, distortion free, and extended at
any sizes. You should use vector images, because only vector format can serve you the purposes.
Raster images cannot keep their original quality zoom or expand them for larger media, since pixels
are made up of dots. So, when you zoom or expand, all you see is pixilated stuffs or dots. However,
vector image formats contain vector lines, fills, & patterns which can be zoomed at the maximum
sizes without losing image quality and dynamically retain their original look, as they are not limited
to pixels.
It can be used for storing many raster formats (which most often is the case), but you can also use
this format as a very good vector format. It can contain both raster and vector file. But, it depends on
how you have created the file. If its layers can be flattened, it is a raster image in the file. But, you
may find difficulty in flattening a vector file.
The image of this format is quite lightweight, scalable, and OS independent. That’s why this file
format is very popular for web resources. It provides much flexibility while editing. These images
can be scaled up at large sizes without a bit of distortion. And the best thing is, SVGs are supported
by almost all browser now-a-days. However, SVG file size can be higher if it contains many small
size contents. It is not possible to read object partly, but entire object which may slow you down.
DXF
DXF stands for Drawing eXchange Format. It is also known as a ‘tagged data’ which is preceded by
integer- ‘group code’. It is a CAD from Autodesk and used by CAD tools. All programs cannot read
DXF files having splines (curves). Anyway, DFX is not so useful now because AutoCAD has become
more powerful meanwhile with its supporting complex object types.
708
CGM (Computer Graphics Metafile)
It is a free and international standard file format for 2D vector & raster graphics and text. But, it is
not supported for web pages. This file format has been succeeded by other graphic art formats. But,
this format is great for product design.
CDR (CorelDRAW)
CorelDraw is in fact a vector graphic editor and creator. The images created by this software get .cdr
file extension. It can create two dimensional vector graphics which act same as the vector images
created by other tools like Adobe Illustrator. The graphics of this format like logo, banner, poster,
etc. are distortion free high quality vector images and they can be used anywhere for personal or
commercial purposes. The CRD images contain all necessary quality of vector graphics including
zooming capability at any sizes and others.
Letter form
Letterform is a term used in typography to describe shape of letters or in modern language known
as font.
In typography, a typeface (also known as font family) is a set of one or more fonts each composed
of glyphs that share common design features. Each font of a typeface has a specific weight, style,
condensation, width, slant, italicization, ornamentation, and designer or foundry.
1. Baseline
709
Majority of the characters sit on this imaginary horizontal line.
2. Cap height
The capline or cap height is another imaginary line wherein the heights of all the capital letters are
marked in a typeface. However one has to keep in mind that the cap height is below the maximum
height of the typeface.
3. Crossbar
The crossbar is a stroke that connects 2 lines in capital letterforms of “A” and “H”. Again a cross
stroke implies a horizontal stroke that does not connect two lines, for example, the lower case of
“f” or “t”.
4. Serif
It is the name assigned to the finishing strokes at the tops and bottoms of some typefaces.
5. Mean line
The mean line better is known as midline is another imaginary horizontal line that marks the top
edges of the lower case letters. You go wrong if you go by the literal definition of the term “mean
line” because it actually doesn’t imply the central line between the baseline and the cap height.
6. Bowl
It is nothing but the rounded curve that covers the negative space in a letter form. Consider, for
example, it can be easily viewed in the following letters “I”, “e”, “D”, “o” and “g”.
7. Descender
710
Descender happens to be the bottom part of the lowercase letter (like “g”, “j”, “p”, “q”, “y” etc.)
that usually goes below the baseline of a typeface. Some other features that particularly extend
below this baseline comprise of the old style numerals typefaces. These specific numerals were
basically thought to mix appropriately with the lowercase roman
8. Counter
Counter refers to the negative space within a letter, particularly if you consider letters like “A”, “o”
and “P” etc. where the counter is fully enclosed. In letters like “G”, “u” and “c” the non-enclosed
negative space is reflected and they are also called counters.
9. Stem
The main vertical or diagonal stroke depicted in a letterform is known as Stem. They consists of the
vertical parts of the letters like “I” and “H” and also simultaneously all the strokes in the letter
“W”.
10. Tittle
The title is defined as the dot above the lowercase “j” and “i”.
11. Terminal
The terminal is the culmination point of the stroke or stem that has no serif.
12. Ascender
It is an extension that goes above the meanline and is generally found in some lowercase letters.
These letters are, “b”, “d”, “f”, “h”, “k”, “l” and “t”.
13. Leg
Legs are the lower angled strokes which you can see in the letters “K”, “R” and “Q”. They are
also known as tails.
14. Ligature
This addition of two characters to create another character is called ligature. They are commonly
seen in serif faces .It is present to give space between certain characters and give the characters an
aesthetic imprint.
15. X-height
711
The space that exists in the vertical direction for the lowercase “x” in any typeface is known as X-
Height. It is the distance the baseline and mean line of the body of characters in lowercase form.
The X-Height is very important in the context of font shapes as the fonts with greater X-heights are
easier to read.
Horizontal
Horizontal lines are straight lines that extend from side to side, laying down parallel. Although
lines do not actually occur in nature — they're simply tools that allow artists to represent objects,
feelings and ideas — the horizontal line mimics the natural edge of the horizon. In graphic design,
horizontal lines are excellent tools for dividing an image. Horizontal lines typically imply a sense
of stability or stillness.
Vertical
Vertical lines can also be used to divide space, separating images into columns. While the side-to-
side nature of horizontal lines reflects a lying or sleeping figure to imply stillness, up-and-down,
perpendicular vertical lines reflect standing figures. This lends the work a more alert or “awake”
feeling and may imply height or strength.
Diagonal
While standard horizontal and vertical lines do not lean, diagonal lines do. Diagonal lines may
stand in a horizontal or vertical fashion, but they are slanted. Like their straight brethren, they often
serve as dividers, but they also give designs a sense of dynamic energy, a lack of stability or a sense
of kinetic motion or tension. Diagonal lines also represent depth and lend a sense of perspective to
artwork.
Zigzag
A group of connected diagonal lines creates the erratic zigzagging line. Graphic designers use
zigzag lines to create a sense of excitement or heighten the energy of a piece. This type of line may
also convey intensity, confusion or danger.
712
Curved
Also known as a contour line, curved lines are extremely versatile tools for graphic designers. This
type of line essentially serves as the definition of a drawn object's edge. For instance, in a line
drawing of a flower, the curved lines represent the edges of its petals. This type of line allows for
complex artistic representations of real-world objects in a drawn image.
Body Copy
Main text part of an advertisement or any printed matter (as distinct from the logo, headline,
subheadings, and graphics) that provides the 'meat' of the communication.
713
2) Build brand identities: 3D modeling lets you create structures that have not been built yet,
providing customers with a prospective vision of what they can expect once the project is complete.
While this is technically photo creation, the final stages involving taking views that obtain the best
angles of the project. These views are then properly manipulated to appear even more aesthetically
beautiful, creating the stage for a perfect brochure.
3)
3) Bring out the best of a picture: Not all pictures appear beautiful. The circumstances around
which the pictures were clicked become relevant, as weather conditions such as rain or dust can
affect the final product. Photo manipulation lets you remove these problems by using graphic
design tools to remove damaged spots. Even red eyes in people and animals can be removed using
photo manipulation. No picture has to be unusable ever again.
4) Create perfect aesthetics: Successful brands rely on graphic design to make their
advertisements and build their brands. All aspects of corporate branding such as catalogs,
brochures, calendars, annual reports and even visiting cards require graphic design. And it is
through perfect photo manipulation that those beautiful visuals on advertisements are achieved.
Graphic design is a powerful tool, and a very basic aspect of that is achieved through photo
manipulation. With the right skills, the right stock photos and right knowledge of techniques, photo
manipulation can let you create anything you want.
Conclusion
At the end of this learning outcome, the learner should be able to identify software and tools for
graphic design and photography, explain image file types, create letterforms, lines of type and
body copy and create and manipulate images using appropriate software.
Further Reading
https://fileinfo.com/filetypes/raster_image
12.3.5.3 .Self-Assessment
Written Assessment
1. Differentiate raster and vector format?
2. What types of lines are available for image creation?
3. Describe the guidelines for creating and manipulating images.
Oral Assessment
What image types are available for image creation and where is each applicable?
.
Practical Assessment
You have been asked by your high school principal to collate old pictures and prepare a collage for
your school’s annual day. Some of the pictures are old and torn. How will you help your school?
714
12.3.5.4 Tools, Equipment, Supplies and Materials
● Graphic design software
● Computers
● Printers
● Internet
● Instruction materials
● Stationery
12.3.5.5 References
1. https://www.colorexpertsbd.com/blog/different-types-raster-image-file-formats
2. https://www.colorexpertsbd.com/blog/vector-based-image-file-formats-extensions
715
12.3.6 Learning Outcome 5: Perform layout design
12.3.6.1 Learning Activities
Learning Outcome No.5: Perform layout design
5.1 Proportion on layout design is explained Activities may be carried out in groups or
5.2 Creation of unified systems out of dissimilar as individual
elements is done.
5.3 Dynamic layouts are created by using
typographic tools ·
5.4 Type and image project is created.
Introduction
Grids bring organization not only to the design, but to the process of creating design. Say you
want to create a poster for a lecture series. Create a strong grid and if the dates, times, images and
colors all change, your basic designs will feel related. Instant consistency and less time updating
and adjusting.
716
Baseline grids also give you a great roadmap when working in a team. Every designer knows the
feeling of relief that comes with opening someone else’s design and seeing a clear grid to follow!
The eye generally needs a place to rest or something of interest to hold it, otherwise people will
look at your design and quickly move on. Say you take a photograph of your mom at a family
reunion. Your purpose is to bring attention to the moment and the joy of the gathering by making
your mom the subject and focal point of your composition.
To communicate the message to the viewer that your mom is the focal point, you want to use
scale and emphasis. You could place her prominently in the photograph and make sure she is the
largest object in the photo. You could emphasize her by blurring the background to make her
stand out or focusing her brightly colored dress.
Figuring out the focal point of the design will give your eye the guide it requires to structure the
composition, as well as organically build hierarchy. In the design above the focal point is the
ridiculous cake—our eyes go right to it and then read the rest for context.
Balance
717
Graphic designers must constantly juggle different elements to find harmony in their design.
Imagine an invisible set of scales in each design and make sure you don’t tip the scales by
cloistering elements on one side of your grid. The website design above does this cleanly by
marrying large type elements (“What We Do” “Our Works”) with smaller, equal-sized
paragraphs of longer explanatory copy.
Keep in mind that in terms of composition, white space (or negative space) is also an element.
White space gives our eyes paths to follow through the design. Give each element on the page
some space to breathe and balance between positive and negative space will emerge organically.
Rule of Third
The Rule of Thirds is inescapable in design. It’s a fundamental guideline that’s so simple and
effective, it often feels like a cheat: divide your design into three rows and three columns. The
points where the vertical and horizontal lines meet form natural guidelines for where you should
place your subject and supporting elements.
For the most clear examples, look at photographs. In the example below, the focal points (the tree
and horizon) are perfectly aligned with the grid created by the Rule of Thirds.
If the tree was dead center horizontally and the mountains were directly in the vertical center, the
composition would not be so pleasing.
Rule of odds
A logo design that uses the Rule of Odds to draw the eye to focal point.
718
The Rule of Odds says that pleasing compositions seem to often have an odd number of elements
placed in the foreground, most commonly three. The two objects on the outside both balance the
focal point in the center, creating a simple, natural balance. (If you’re a wedding photographer
this is probably the most difficult rule to follow.) This is often true in logo design, where a
centered mark might be offset on either side by the company name.
Alignment
Alignment refers to lining up the top, bottom, sides, or middle of a text, composition, or grouping
of graphic elements on a page. Often a design composition includes a grid where the alignment of
text blocks is dictated by the design of the columns of the grid.
Typographically, horizontal alignment includes flush left (also called left justified or ragged
right), flush right (also called right justified or ragged left), centred, and fully justified. Vertical
alignment in typography is usually linked to baseline alignment. A baseline grid exists in digital
software that is meant for layout of type and is the invisible line where font characters sit.
Contrast
Contrast is a visual device that increases the special character of both elements that have been
paired. Contrast assists composition by creating focal points, and adds energy and visual range to
a composition. Using contrast enables us to distinguish the qualities of one object by comparing
differences with another.
Some ways of creating contrast among elements in the design include the use of contrasting
colours, sizes, and shapes.
Colour Contrast
There are seven kinds of contrast.
719
• Contrast of hue occurs when a hue or colour is separated by being outlined in black or
white lines. White lines weaken the ‘strength’ and appearance of the colour and the
colours around the white lines seem darker. In contrast, a black line around a colour
strengthens the appearance of the colour, while the colours around the black lines appear
to be lighter.
• Light-dark contrast is the contrast between light values and dark values.
• Cold-warm contrast refers to the contrast between cool and warm colours. Warm colours
are the red, orange, and yellow colours of the colour wheel, while cool colours are blue,
green, and purple.
• Complementary contrast is the contrast between colours directly opposite each other on
the colour wheel.
• Simultaneous contrast occurs between two colours that are almost complementary. One
colour is one section to the left or right of the complementary colour of the other.
• Contrast of saturation refers to the contrast between intense colours and tertiary or muted
colors. Muted colours appear duller when placed next to intense colours, and intense
colours appear more vivid when next to a muted colour.
• Contrast of extension refers to the contrast between the area of one colour and another.
Different areas of one colour are needed to balance another.
For text, contrast is achieved by using varied colours, serif and sans serif, type styles that are not
often paired, or type in place of an image. As contrast in elements diminishes, the elements begin
to feel similar, and the level of visual interest decreases.
Emphasis
A focal point in a composition draws the eye to it before the eye engages with the rest of the
visual information. This is called emphasis and is achieved by making a specific element gain the
attention of the eye.
Emphasis is created in graphic design by making only one focal point and clearly emphasizing it
by placing the elements on the page in positions where the eye is naturally drawn to the proper
entry into the work. Designers rely on additional compositional principles to support the
hierarchy of a composition such as contrast, repetition, or movement.
Designers use emphasis to assist viewers in identifying the relative importance of each element in
a composition. Emphasis is strongly linked to visual hierarchy.
Both emphasis and visual hierarchy create order for the viewer, allowing the eye to see the first
element of importance, then the second, then the third, and so on. Graphic elements gain or lose
emphasis by changing in size, visual intensity, colour, complexity, uniqueness, placement on the
page, and relationship to other elements.
720
Movement
Movement is made by creating visual instability — like motion in a photograph that blurs the
image, as shown in the example in Figure above.
Creating the illusion of movement photographically or artistically is not difficult because a blur
translates into movement in the mind of the viewer. However, it is not the only option for a
designer. A composition can also achieve movement if the graphic elements are arranged in a
way that directs the eye to move in a specific direction — usually by creating a diagonal that
takes the eye up to the right corner (forward motion) or down to the left corner (backward
motion).
Movement can also be created using overlapping planes that imply depth and distance by
becoming progressively smaller and lighter in tone (mimicking depth). Using typography as a
visual medium is also an option. Overlapping the text blocks and/or sentences effectively creates
both depth and movement (though it destroys legibility).
Scale
Varying scale (size) is one of the major tools in the designer’s toolbox. Changing scale is
important on two levels. The first is purely compositional — a composition needs variety in the
size of its elements to be dynamic and effective. If all the elements have the same visual weight,
the composition will be flat.
Another aspect to varied scale is conceptual. If a design visually distorts the size relation of one
element to another, the viewer is instantly engaged in discovering why. This is a great method to
engage the viewer and add a twist to the message embedded in the design.
Hierarchy + Balance
In order to create a dynamic layout design, you have to focus on the hierarchy + balance of the
layout. What do you want the viewer to focus on the most? What is secondary information?
721
Designs that aren’t harmonious, or lack a dynamic appeal, typically don’t incorporate a good use of
hierarchy. If your layout lacks this balance, the viewer is left subconsciously confused where they
should focus their attention.
Avoid this dilemma through providing a clear hierarchy to your layout: Title, subhead/secondary
info, and remaining copy. I’m always drawn to a minimal design that has an obvious hierarchy +
structure to the layout.
Sketch
Remove distractions + the temptation to mimic another designer’s work, and take your
concept/layout to paper first.
Sketching allows you to lay out a design, without the distraction of the computer. It is SO easy to
jump to the computer first, and layout your design.
Typography
Typography is at the heart of every design. If you have a weak typographic layout, nothing can
compensate for it. Focus on the typography choices first, before diving into the other design
elements. Select typefaces that are appropriate for the concept + audience, and that pair well
together. Through having a strong typographic emphasis, the rest of the design will fall into place.
Think of this layout as a wireframe of your design. Through minimizing the design + color, you
focus your design on a dynamic layout, rather than relying on color or graphics to compensate.
Remove Distractions
Once you have a wireframe of your design complete, take note of where you can remove any
distractions. Does your design look too cluttered? Is there too much information + content, that can
be reduced? Look for ways to minimize the design, directing the viewer to the information you
want to focus on.
722
Creation of Type and image project
Also, titles ought to look like titles, subtitles ought to look like subtitles, and lists ought to look like
lists—in other words, a reader should be able to deduce the informational structure of the page from
its layout.
What is the most important thing on the page you’re designing? Make that the center of attention.
Can you rank other things in declining order of importance? Arrange them on the page in ways that
draw progressively less attention; make them look less interesting.
Density
A dense, heavy-looking block has stronger contrast with the surrounding page; an open look
has less contrast.
Background color
723
Contrast draws attention. Black on white, or vice versa, is the strongest contrast possible.
Visual Flow
Visual flow deals with the tracks that readers’ eyes tend to follow as they scan the page. It’s
intimately related to visual hierarchy, of course—a well-designed visual hierarchy sets up focal
points on the page wherever you need to draw attention to the most important elements, and visual
flow leads the eyes from those into the less important information.
Several forces can work against each other when you try to set up a visual flow. One is our
tendency to read top to bottom and left to right. When faced with a monotonous page of text, that’s
what you’ll do naturally; but if there are strong focal points on the page, they can distract you from
the usual progression, for better or for worse.
Focal points are the spots your eyes can’t resist going to. You tend to follow them from strongest to
weakest, and skillfully designed pages have only a few—too many focal points dilute the
importance of each one. A good visual hierarchy uses focal points to pull eyes to the right places in
the right order.
One simple way to create a good visual flow is to use implied lines, either curved or straight, to
connect elements on the page (see figure below). This creates a visual narrative for the viewer to
follow.
Conclusion
At the end of this learning outcome, the learner should be able to explain proportion on layout
design, create unified systems out of dissimilar elements, create dynamic layouts by using
typographic tools and create a type and image project.
Further Reading
1. https://www.oreilly.com/library/view/designing-interfaces-2nd/9781449379711/ch04.html
2. https://webflow.com/blog/9-of-the-best-typography-tools-fordesigners
3. https://alexanderwwhite.wordpress.com/designer/typedesign/“
putting-it-together-achieving-a-unified-design”/
12.3.6.3 .Self-Assessment
Written Assessment
1. What is proportionality in graphic design?
2. Why is visual flow important?
3. How do focal points improve graphic understanding?
4. Which rules are important for design composition and layout?
Oral Assessment
Outline the guidelines for creating types and images.
.
Practical Assessment
Open an entertainment website and critique the layout design.
12.3.6.4 Tools, Equipment, Supplies and Materials
● Graphic design software
● Computers
● Printers
● Internet
● Instruction materials
● Stationery
12.3.6.5 References
1. https://www.oreilly.com/library/view/designing-interfaces-2nd/9781449379711/ch04.html
2. https://webflow.com/blog/9-of-the-best-typography-tools-for-designers
3. https://alexanderwwhite.wordpress.com/designer/type-design/“putting-it-togetherachieving-
a-unified-design”/
725
12.3.7 Learning Outcome 6: Print Design
12.3.7.1 Learning Activities
Learning Outcome No.6: Print Design
6.1 Tools and Equipment for printing are Activities may be carried out in groups or as
identified. individual
6.2 Types of printing are identified based on the
design.
6.3 Paper is classified according to types, size and ·
weight.
6.4 Chemicals used in Printing are selected.
6.5 Printing of the actual design is demonstrated
Introduction
This learning outcome covers identifying tools and equipment for printing, identifying types of
printing based on the design, classifying paper according to types, size and weight, selecting
chemicals used for printing and printing the actual design.
Photoshop
This incredible tool also offers basic features like channel mixing, perspective correction, and even
clone stamp tool. Photoshop is considered one of the best graphic design tools running on both Mac
and Windows.
With Photoshop, you get other useful add-ons like one touch adjustment, cropping, panoramic
image option, and so much more.
Photoshop makes photo editing an interesting endeavor. Whether you are a seasoned graphic
designer or not, Photoshop has automatic photo editing options that infuse life to your images.
Pixlr
A Pixlr editor is a very useful tool for graphic designers who use Photoshop. This amazing tool not
only opens .PSD files but also keeps hold of all the artistic layers.
726
Pixlr is a great alternative to Photoshop for clients who have straightforward image editing
prerequisites, including such things as crop and resize. This fine tool provides all the functionalities
you need without having to bother about an extra graphic design software license to uphold.
GIMP
Also known as GNU Image Manipulation Program, GIMP graphic design tool is a perfect
alternative to Adobe Photoshop. It incorporates the photo manipulation feature for creating crystal-
clear graphics.
The GIMP has a totally customizable interface along with the full-screen mode that enables you to
view and edit the image simultaneously.
This graphic design software has extensive features that provide a unique experience. It can run on
OS X, GNU/Linux, Windows, and other Operating Systems. It is hands down one of the most
excellent graphic design software whose cross-compatible platform provides a strong support.
ProofHub eliminates the need for using emails, approval or feedback while also reducing the time
the entire process consumes. This online proofing tool allows you to effect instant changes to your
file, add comments, and even highlight some flaws you might have noticed in the design.
DesignBold
DesignBold is another user-friendly graphic design tool for creating stunning images within a
specified number of drags-and-drops. It has plenty of design resources including an enormous
library of 12,080++ customizable layouts that will enable you to craft the design elements on your
own.
727
As an example, DesignBold allows you to create several types of visuals like a logo or a header to
your website content. It is a fast and cost-effective tool suitable for beginners and professional
designers.
Illustrator
Illustrator is a fantastic graphic design tool for creating topography, sketches, icons, and other
complex illustrations for videos or mobile. You can use it to create artwork with immaculate
configuration by sketching pixel-perfect shapes. The Illustrator makes designing faster than ever
before.
The Illustrator features numerous plugins for turning a blank page into a seamless looking one. It
has plugins designed for Ai versions as well as a host of features designed for new versions like
Creative Cloud.
Marvel
Every experienced graphic designer will tell you that prototyping is a fundamental part of design
these days. Marvel is the best prototyping tool that allows you to create anything from scratch as
well as sync all designs directly from your cloud storage.
Marvel Canvas is a great tool for sketching the prototype and adding gestures and conversions to
your design.
Inkscape
Inkscape is a specialized tool for vector art enthusiasts as well as graphic designers who utilize
SVG format. It is compatible with Mac, OS, Linux, and Windows.
It is capable of directly editing the source code for a blog, whether or not you are a professional
graphic designer. Inkscape is also simple to use when it comes to making illustrations, coloring or
sketching.
Pixelmator
From time to time, graphic designers have to showcase their innovation as far as image editing is
concerned. Pixelmator Pro is an excellent graphic design software featuring simplified editing tools
along with intelligent image editing features. It has an elegant single window interface that allows
you to build up multiple projects using intuitive tools like resizing, moving, and arranging layers.
CorelDraw
Corel graphic design software is great for aspiring designers searching for a graphics editor with
the ability to generate infinite designs with no restrictions. CorelDraw can hone your design skills
because it has some cool productive functions, unlike many other vector editors available out there.
728
Palleton
Every designer needs a superior color scheme to be able to create amazing color combinations that
match their unique designs.
Palleton is a fantastic color scheme tool that helps you come up with perfect color combinations
for your artwork.
With Palleton, you will be able to create amazing combinations by choosing your desired colors on
a color wheel as well as selecting from some tried and tested color combinations. These include
Adjacent Colors, Monochromatic, Tetrad, Triad, and Freestyle.
Cheetah 3D
The 3D art is gaining immense traction and popularity in the world of design. With the Cheetah 3D
hack design toolkit, you will be able to craft unique 3D artwork for your first animated character
or next iPhone game.
This impeccable design toolkit is packed with a breath of extraordinary features for carrying out a
myriad of graphic design tasks.
Types of printing:
Digital Printing
Digital Printing is when you reproduce a digital based image to print format, using a physical
surface like paper, film, plastic, photographic paper or cloth. When dealing with high volume or
larger format document, an inkjet printer could be used.
The impressions made into the paper might differ all the time, not like where you have thousands
of ideas of the same image. The ink or toner will not absorb into the paper, and it forms a layer on
the surface.
Offset Printing
729
Offset printing is a type of print that makes use of plates. These plates usually made from
aluminium. In this technique the inked image is transferred from the plate to a rubber blanket, then
rolled unto the sheet of paper.
The word offset refers to the image not directly transferred to the medium from the start. The
advantages of offset printing include: production of sharper pictures and type as the blanket
conforms to the texture of the printing surface and consistently high image quality. It can also be
known as Lithographic or Planographic depending on the method used.
Flexography
This type of printing has been commonly called the modern version of the letterpress. It is also
referred to as Flexobecause it was initially used to print onto corrugated cardboard. Flexography
printing is mostly used for packaging. A master copy of the required image as a 3D relief is created
out of polymer material and using this you can do a flexo print. An anilox roll or printing cylinder
is then used to do the printing. Firstly the ink must be placed onto the surface of the printing plate.
Letterpress Printing
The term letterpress refers to the direct imprint of ink media such as plates onto an open surface. It
is printing text with movable type. The raised surface of the type is inked and then pressed against
a receptive surface to obtain an image in reverse.
Screen Printing
Screen printing creates sharp-edged images by making use of stencils. The screen consists of a
finely woven fabric which stretches over an aluminium frame. A stencil is then used to block the
images that need printing.
People typically associate screen printing with creating garments. Thousands of items, including
clocks and birthday cake designs and many other products, are printed using this print technique.
Graphic screen printing is used to create large batches of graphics as posters or display stands. You
can also create full-colour prints.
Paper classification
730
Bond paper
This type of paper is stronger and more durable than the average sheet of paper. Instead of being
made from low grade wood pulp, it is mostly made up of rag pulp. It’s perfect for letterheads, typed
reports and envelopes.
Recycled paper
Made from re-used paper products, recycled paper is perfect for those who are trying to reduce
their environmental impact. It can be used for most documents including reports, memo paper and
forms.
Uncoated paper
Typically found in most office printers, uncoated paper has no coating, making it excellent for ink
receptivity and absorbency. As it is uncoated it has the advantage of being used by both printer and
pen, ideal for forms, letterheads and memo paper.
Watermarked paper
Used in high quality paper watermarked paper give a feel of luxury and high quality. To create its
desired effect an impression is pressed into the paper by attaching a wire pattern. This type of paper
is commonly used as a security feature for important documents, including exam certificates.
Paper Size
The table below provides the dimensions of each paper size.
731
A3 297 x 420 mm 11.7 x 16.5 in
A4 210 x 297 mm 8.3 x 11.7 in
A5 148 x 210 mm 5.8 x 8.3 in
A6 105 x 148 mm 4.1 5.8 in
A7 74 x 105 mm 2.9 x 4.1 in
A8 52 x 74 mm 2.0 x 2.9 in
A9 37 x 52 mm 1.5 x 2.0 in
A10 26 x 37 mm 1.0 x 1.5 in
Paper Weight
Chemicals in printing
Chemicals used in Printing (inks, lacquers, adhesives, cleaning solvents and many others) are
substances that can cause ill health if there is exposure. For example, you can breathe in vapours
and mists: contact with chemicals can cause skin problems and chemicals may be absorbed through
the skin and cause damage in other parts of the body.
732
Printing is the mechanical process of applying ink to paper using an offset or digital press. The
offset press is the most cost effective way of producing large volumes of printed materials, while
the digital press is more commonly used for smaller volume and lower production cost.
It is important to understand that the final product will look slightly different when printed digitally
vs. offset, as well as from printer to printer. Proper and consistent paper selection is also a critical
component of the process because color appears distinctively on different paper stocks and with or
without finishes (varnish, aqueous coating, etc.).
So when you need to reprint, it is best to use the same methodology, on the same paper, with the
same finishes, at the same printer to match the original run as closely as possible.
Conclusion
At the end of this learning outcome, the learner should be able to identify tools and equipment for
printing, identify types of printing based on the design, classify paper according to types, size and
weight nd select chemicals used for printing and printing the actual design.
Further Reading
1. https://fileinfo.com/filetypes/raster_image
2. https://www.colorexpertsbd.com/blog/different-types-raster-image-file-formats
3. https://www.colorexpertsbd.com/blog/vector-based-image-file-formats-extensions
4. https://www.printerland.co.uk/blog/printer-buying-guide/indepth-guide-to-printer-paper/
12.3.7.3. Self-Assessment
Written Assessment
1. What are the different types of printing?
2. What are the different types of printing paper?
3. What type of paper will you use for printing visiting cards for a top executive?
1. What are the key factors for selecting paper quality?
2. Explain the harmful effects of printing chemicals.
Oral Assessment
You are working in a photocopy shop. You have noticed that there are a lot of query related to
architecture drawing printing since the time a college nearby has opened interior designing course.
What kind of printer and paper will you suggest to your manager?
.
Practical Assessment
Design a logo for an advertising company and print it using the correct paper while setting
appropriate print dimensions.
733
● Computers
● Printers
● Internet
● Instruction materials
● Stationery
12.3.7.5 References
1. https://www.fellesforbundet.no/globalassets/dokumenter/grafisk/publikasjoner/ngu-
digitalprint-report-2016.pdf
2. https://www.printerland.co.uk/blog/printer-buying-guide/in-depth-guide-to-printer-paper/
3. http://imprimerie-sanjose.com/what-are-the-different-types-of-printing/
4. https://www.fellesforbundet.no/globalassets/dokumenter/grafisk/publikasjoner/ngudigital-
print-report-2016.pdf
734