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

Computer Science Level 6 Learning Guide

The document is a Learning Guide for Computer Science Level 6 developed by the TVET Curriculum Development, Assessment and Certification Council (CDACC) in Kenya. It emphasizes the importance of competency-based education and training (CBET) to address the skill gap in the workforce and align with Kenya's Vision 2030 and Sustainable Development Goals. The guide includes structured learning outcomes and activities across various computer science topics to enhance the delivery of the curriculum and support the development of skilled professionals in the sector.

Uploaded by

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

Computer Science Level 6 Learning Guide

The document is a Learning Guide for Computer Science Level 6 developed by the TVET Curriculum Development, Assessment and Certification Council (CDACC) in Kenya. It emphasizes the importance of competency-based education and training (CBET) to address the skill gap in the workforce and align with Kenya's Vision 2030 and Sustainable Development Goals. The guide includes structured learning outcomes and activities across various computer science topics to enhance the delivery of the curriculum and support the development of skilled professionals in the sector.

Uploaded by

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

REPUBLIC OF KENYA

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.

PRINCIPAL SECRETARY, VOCATIONAL AND TECHNICAL TRAINING


MINISTRY OF EDUCATION

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.

Prof. CHARLES M. M. ONDIEKI, PhD, FIET (K), Con. EngTech. CHAIRMAN,


TVET CDACC

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

DR. LAWRENCE GUANTAI M’ITONGA, PhD


COUNCIL SECRETARY/CEO
TVET CDACC

iv
ACRONYMS

BC: Basic competency


CBET: Competency Based Education and Training
CC: Common competency
CR: Core Competency
CU: Curriculum
CS: Computer Science
KCSE: Kenya Certificate of Secondary Education
KNQA: Kenya National Qualifications Authority
SSAC: Sector Skills Advisory Committee
TVET: Technical and Vocational Education and Training
TVET CDACC: TVET Curriculum Development, Assessment and Certification Council
AI – Artificial Intelligence
ROM – Read Only Memory
RAM – Random Access Memory
LAN – Local Area Network
WAN – Wide Area Network
ASCII – American Standard Code for Information Interchange
BIOS – Basic Input Output System
CASE – Computer Aided Software Engineering
SDLC – Software Development Life Cycle
DDL – Data Definition Language
GB – Gigabytes
HTML- Hyper Text Mark-up Language

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

Figure 1:Motherboard ..................................................................................................................... 6


Figure 2: Power supply ................................................................................................................... 7
Figure 3:Central Processing Unit (CPU) ........................................................................................ 7
Figure 4: RAM ................................................................................................................................ 8
Figure 5: Hard disk ....................................................................................................................... 8
Figure 6:Video Card........................................................................................................................ 9
Figure 7: Optical device drive ....................................................................................................... 10
Figure 8: Computer Internal components ..................................................................................... 10
Figure 9:CPU Registers ................................................................................................................ 15
Figure 10: Buses............................................................................................................................ 16
Figure 11:Fetch Execute Cycle ..................................................................................................... 17
Figure 12:Memory Organization in Computer Architecture ........................................................ 22
Figure 13:Cache Memory ............................................................................................................. 23
Figure 14:Secondary Memory ...................................................................................................... 26
Figure 15:Connection of I/O bus to I/O device ............................................................................. 37
Figure 16:PCI Slots ....................................................................................................................... 38
Figure 17:AGP Slot ....................................................................................................................... 39
Figure 18:Video/Graphics Card .................................................................................................... 39
Figure 19:Network Card ............................................................................................................... 40
Figure 20:USB Connectors ........................................................................................................... 40
Figure 21:Firewire Cable .............................................................................................................. 41
Figure 22:PS/2 Ports ..................................................................................................................... 41
Figure 23:Programmed I/O Mode Input Data Transfer ................................................................ 42
Figure 24:Interrupt- initiated I/O .................................................................................................. 43
Figure 25:Interrupt Processing ...................................................................................................... 45
Figure 26:DMA and Interrupt Breakpoints during an Instruction Cycle ...................................... 46
Figure 27:Typical DMA Block Diagram ...................................................................................... 47
Figure 28:Monolithic System Architecture................................................................................... 74
Figure 29:Layered architecture ..................................................................................................... 75
Figure 30:Virtual Architecture ...................................................................................................... 76
Figure 31:Layout of a process inside main memory ..................................................................... 90
Figure 32:Process States and Transition ....................................................................................... 92
Figure 33:Process Control Block (PCB) ....................................................................................... 93
Figure 34:Process Scheduling Queues .......................................................................................... 94
Figure 35:Context Switching ........................................................................................................ 97
Figure 36: Task Manager (Start window) ................................................................................... 102
Figure 37:Task Manager Details window ................................................................................... 103
Figure 38:Performance Monitor.................................................................................................. 107
Figure 39: Process Swapping in memory ................................................................................... 112
Figure 40: Memory fragmentation .............................................................................................. 114
Figure 41: Memory paging ......................................................................................................... 115

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

Graph 1: Demonstrating y = mx+c ............................................................................................. 200


Graph 2: f(x) = |x| ........................................................................................................................ 201
Graph 3: y = x3 ............................................................................................................................ 201
Graph 4: Indefinite integral ......................................................................................................... 208
Graph 5: Definite integral ........................................................................................................... 208

xiv
CHAPTER 1: INTRODUCTION

1.1 Background Information


This learning guide has been developed in line with the functions of TVET CDACC as stipulated in
Article 45 (1a) of the Technical and Vocational Education and Training (TVET) Act No. 29 of 2013,
the Sessional Paper No. 2 of 2015 that embraces Competency Based Education and Training
(CBET) system. It is therefore, the sole intent of this document to provide guidelines for a
Competency-Based Computer Science Level 6.

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.

1.2 The Purpose of Developing the Trainee Guide


Computer Science level 6curriculum development process was initiated using the DACUM
methodology where jobs/occupations were identified. Further, job analysis charts and occupational
standards were generated in collaboration with the industry players under the guidance of TVET
CDACC (Curriculum Development Assessment and Certification Council). The result of the
process was a Computer Science level 6 curriculum. The curriculum was further broken down to
end up with units of learning. To effectively implement Computer Science level 6curriculum,
learning guides are required to provide training content and guide the learners and trainers on the
learning process aimed at imparting the relevant knowledge, requisite skills and the right attitude to
the industry. Learning guides are part of the training materials.

1.3 Layout of the Learning Guide


The learning guide is organized as per chapters. Chapter one presents the background information,
and purpose of developing the trainee guide. Each of the units of learning/unit of competency is
presented as a chapter on its own. Each chapter presents the introduction of the unit of learning/unit
of competency, performance standard and list of the learning outcome/elements in the occupational
standards.

• 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:

Common Units of Learning


Table 1: Basic Units of Learning

Unit of Learning Unit of Learning Title Duration in Credit


Code Hours Factor
IT/CU/CS/BC/01/6/A Communication skills 40 4
IT/CU/CS/BC/01/6/A Numeracy skills 60 6
IT/CU/CS/BC/01/6/A Digital literacy 60 6
IT/CU/CS/BC/01/6/A Entrepreneurship education 100 10
IT/CU/CS/BC/01/6/A Employability skills 80 8
IT/CU/CS/BC/01/6/A Environmental literacy 40 4
IT/CU/CS/BC/01/6/A Occupational safety and health 40 4
practices
Total 420 42
Common Units of Learning

Table 2: Common Units of Learning

Unit of Learning Unit of Learning Title Duration in Credit


Code Hours Factor
IT/CU/CS/CC/01/6/A Demonstrate Basic Electronic 170 17
Skills
Total 170 17

Core Units of Learning


Table 3: Core Units 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.

2.2 Performance Standard


1. Identified hardware components of a computer
2. Prescribed CPU specifications according to a user’s needs
3. Verified CPU specifications for a given computer
4. Prescribed memory specifications according to a user’s needs

2.3 Learning Outcomes


2.3.1 List of Learning Outcomes
1. Understand principles of Computer Organization and Design
2. Understand Central Processing Unit functions
3. Understand computer memory organization
4. Understand Input-Output functions
5. Understand computer arithmetic and logic

4
2.3.2 Learning Outcome 1: Understand Principles of Computer Organization and Design
2.3.2.1 Learning Activities

Learning Outcome 1: Understand Principles of Computer Organisation and Design


Learning Activities Special Instructions

1.1. Computer organisation is defined Activities may be carried out in


1.2. Computer architecture is explained groups or as individual
1.3. Structure and function of computer components is
explained
1.4. Hardware components of a computer are identified

2.3.2.2 Information Sheet No 2/LO1: Understand Principles of Computer Organisation and


Design

Introduction
This learning outcome covers defining computer organisation, explaining and structure and
function of computer components and identifying hardware components.

Definition of key terms


Computer Organisation: refers to the level of abstraction above the digital logic level, but
below the operating system level.
Computer architecture: is a set of rules and methods that describe the functionality,
organization, and implementation of computer systems
Computer memory: is any physical device capable of storing information temporarily, like
RAM (random access memory), or permanently, like ROM (read-only memory).
Peripherals: Input or output devices that are connected to a computer. E.g. keyboard
Input peripherals: Allows user input, from the outside world to the computer. Example:
Keyboard, Mouse etc.
Output peripherals: Allows information output, from the computer to the outside world e.g.:
Printer, Monitor etc.
Input-Output peripherals: Allows both input (from outside world to computer) as well as,
output (from computer to the outside world). Example: Touch screen etc.
Computer Architecture: refers to those attributes of a system that have a direct impact on the
logical execution of a program.
Computer Organization: refers to the operational units and their interconnections that realize
the architectural specifications.
Structure: The way in which components relate to each other.
Function: the operation of individual components as part of the structure

Computer organization and architecture


Computer Organization is the realization of what is specified by the computer architecture. It
deals with how operational attributes are linked together to meet the requirements specified by
5
computer architecture. Some organizational attributes are hardware details, control signals,
peripherals.

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

Structure and function of computer components


Motherboard
As the given name, we can say this is either the start or endpoint of all components.
It is either the origin point of other parts of the computer or where every other component
connects to. In a way, it is a lot like what you would refer to your home country as: the
motherland.

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.

Figure 2: Power supply

Central Processing Unit (CPU)


Sometimes it's referred to as the computer’s brain. It is the workhorse of the machine. It performs
the calculations needed by a system, and can vary in speed. The work that a CPU does generates
heat, which is why your computer has a fan inside. A more powerful CPU is necessary for intense
computer work like editing high-definition video or programming complex software.

Figure 3:Central Processing Unit (CPU)

Random Access Memory (RAM)


RAM is a temporary memory. When you open an application in our computer, the computer will
place that application and all its data in the RAM. When you close the application, then space in
the RAM is freed. That is why your computer gets so slow when you have too many applications
open; your RAM is probably being used at capacity.

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

Hard disk /Solid State Disk


Remember that we said RAM is volatile due to its temporary nature, which means the computer
still needs a more permanent form of data storage. That’s why the hard drive or solid state drive
exists. Traditionally, the hard drive is a drum with several platters piled on it and spinning, and
the physical arm then writes data onto these platters. These disks are very slow because of the
mechanics through which data is stored, although latest hard drives, solid state drives, are much
faster.

Figure 5: Hard disk

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.

Figure 6:Video Card

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:

Figure 8: Computer Internal components

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.4 Tools, Equipment, Supplies and Materials


● Computer
● Internet connectivity
● Stationery
● Instruction material

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

Learning Outcome 2: Understand Central Processing Unit functions


Learning Activities Special Instructions

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

2.3.3.2 Information Sheet No 2/LO2: Understand Central Processing Unit functions

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.

Standard CPU specification factors


There are four key factors about CPU architecture that affect its performance:
● Cores
○ A CPU can contain one or more processing units. Each unit is called a core. A core
contains an ALU, control unit and registers. It is common for computers to have
two (dual), four (quad) or even more cores. CPUs with multiple cores have more
power to run multiple programs at the same time.
● Clock speed
○ The clock speed - also known as clock rate - indicates how fast the CPU can run.
This is measured in megahertz (MHz) or gigahertz (GHz) and corresponds with
how many instruction cycles the CPU can deal with in a second.
● Cache size
○ Cache is a small amount of memory which is a part of the CPU - closer to the CPU
than RAM. It is used to temporarily hold instructions and data that the CPU is
likely to reuse.
● Processor type
○ Processor type can be either RISC or CISK. CPU ARCHITECTURE

CPU itself has the following three components.


● ALU(Arithmetic Logic Unit)
● Control Unit
● Memory Unit (Registers)

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.

ALU (Arithmetic Logic Unit)


This unit consists of two subsections namely,
● Arithmetic Section
● Logic Section

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.

Figure 9:CPU Registers

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.

Figure 10: Buses

We have three different types of buses. These are:


● DATA BUS
○ The control bus controls the traffic of data. It helps to send data, according to
the request of the user and PC.
● ADDRESS BUS
○ Data bus helps to connect the Microprocessor (CPU) and Memory (RAM).
● Control bus
○ The address bus carries the address of the location of memory.

Instruction representation and execution

Fetch Execute Cycle


This is the basic operation (instruction) cycle of a computer (also known as the fetch decode
execute cycle).

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.

Figure 11:Fetch Execute Cycle

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.

Examples of instruction set


• ADD - Add two numbers together.
• COMPARE - Compare numbers.
• IN - Input information from a device, e.g., keyboard.
• JUMP - Jump to designated RAM address.
• JUMP IF - Conditional statement that jumps to a designated RAM address.
• LOAD - Load information from RAM to the CPU.
• OUT - Output information to device, e.g., monitor.
• STORE - Store information to RAM.

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.4 Tools, Equipment, Supplies and Materials


● Computer
● Internet connectivity
● Stationery
● Instruction material

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

Learning Outcome 3: Understand Computer Memory Organization


Learning Activities Special Instructions

3.1 Memory organization is explained. Activities may be carried out in


3.2 Various storage technologies are explained. groups or as individual
3.3 Cache and Virtual memory are explained
3.4 Memory specifications are prescribed for a user
3.5 Memory specifications are verified for a given computer

2.3.4.2 Information Sheet 2/LO3: Understand Computer Memory Organization

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.

Definition of key terms


• Memory
○ It is any physical device capable of storing information temporarily, or
permanently. Memory devices utilize integrated circuits and are used by operating
systems, software, and hardware.
○ is the storage space in the computer, where data is to be processed and instructions
required for processing are stored
• Memory unit
○ It is the collection of storage units or devices together.
• Memory hierarchy
○ It is an organizational structure in which memory units are ranked according to
levels of importance.
○ The computer memory hierarchy ranks components in terms of response times, with
processor registers at the top of the pyramid structure and tape backup at the
bottom.
• Virtual memory
○ Is a memory management capability of an operating system (OS) that uses
hardware and software to allow a computer to compensate for physical memory
shortages by temporarily transferring data from random access memory (RAM) to
disk storage

• 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.

Memory Organization in Computer Architecture


Generally, memory/storage is classified into 2 categories:
● 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.

Figure 12:Memory Organization in Computer Architecture

Memory is primarily of three types −


● Cache Memory
● Primary Memory/Main Memory
● Secondary 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

Operations of the cache memory


■ Requests regarding the contents of memory location are done by CPU.
■ Check cache for this data
■ If present, get from cache (fast)
■ If not present, read required block from main memory to cache
■ Then deliver from cache to CPU

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.

Primary Memory (Main Memory)


Primary memory holds only those data and instructions on which the computer is currently
working. It has a limited capacity and data is lost when power is switched off. (Volatile)
It is generally made up of semiconductor devices. These memories are not as fast as registers. The
data and instruction required to be processed resides in the main memory. It is divided into two
subcategories RAM and ROM.

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)

Static RAM (SRAM)


❏ Stores data using the flip-flop state
❏ Retains value indefinitely, as long as it is kept powered.
❏ Mostly used to create cache memory of CPU.
❏ Faster and more expensive than DRAM.

Dynamic RAM (DRAM)


❏ Each cell stores a bit with a capacitor and transistor.
❏ Large storage capacity
❏ Needs to be refreshed frequently.
❏ Used to create main memory.
❏ Slower and cheaper than SRAM.

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.

The information is stored permanently in such memories during manufacture.


ROM stores such instructions that are required to start a computer. This operation is referred to as
bootstrap.

ROM chips are not only used in the computer but also in other electronic items like washing
machine and microwave oven.

There are five basic ROM types:


➢ ROM - Read Only Memory
➢ PROM - Programmable Read Only Memory
➢ EPROM - Erasable Programmable Read Only Memory
➢ EEPROM - Electrically Erasable Programmable Read Only Memory
➢ Flash EEPROM memory

Characteristics of Main Memory


● These are semiconductor memories.
● It is known as the main memory.
● Usually volatile memory.
● Data is lost in case power is switched off.
● It is the working memory of the computer.
● Faster than secondary memories.
● A computer cannot run without the primary memory.

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

Characteristics of Secondary Memory


● These are magnetic and optical memories.
● It is known as the backup memory.
● It is a non-volatile memory.
● Data is permanently stored even if power is switched off.
● It is used for storage of data in a computer.
● Computers may run without the secondary memory.
● Slower than primary memories.
Depending on whether secondary memory device is part of CPU or not, there are two types of
secondary memory – fixed and removable.

Table 4: Primary and secondary memory

Parameter Primary memory 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

Accesses Primary memory can be accessed by Secondary memory is accessed by I/O


the data bus. channels.

Expense Primary memory is costlier than Secondary memory is cheaper than primary
secondary memory. memory.

Storage Devices

SSD Solid State Drive


It is a storage device that uses integrated circuit assemblies as memory to store data.
SSD are also known as solid-state disks although SSDs do not have physical disks.

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.

Benefits of having Virtual Memory


1. Large programs can be written, as virtual space available is huge compared to physical
memory.
2. Less I/O required, leads to faster and easy swapping of processes.
3. More physical memory available, as programs are stored on virtual memory, so they occupy
very less space on actual physical memory.

Following are the important differences between Cache Memory and Virtual Memory.

Table 5: Differences between Cache Memory and Virtual Memory

Key Cache Memory Virtual Memory

1 Objective Cache memory increases Virtual memory increases the main


CPU access speed. memory capacity.

2 Memory Cache memory is a Virtual memory is a technique and


Unit memory unit and is very involves hard disk and is slower to
fast to access. access.

3 Management CPU and related Operating System manages virtual


hardware manages cache memory.
memory.

4 Size Cache memory is small Size of virtual memory is much larger


in size. than cache memory.

5 Operation Cache memory keeps Virtual memory keeps the programs


recently used data. which are not getting accommodated in
main 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.4 Tools, Equipment, Supplies and Materials


● Computer
● Internet connectivity
● Stationery
● Instruction material

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

Learning Outcome 4: Understand Input-Output functions


Learning Activities Special Instructions

4.1 Peripherals devices are explained Activities may be carried out in


4.2 Input-output processing is explained groups or as individual
4.3 Bus interface is explained
4.4 Modes of data transfer are explained
4.5 Input-output device specifications are prescribed
for a user
4.6 Input-output device specifications are verified
for a given computer

2.3.5.2 Information Sheet 2/LO4: Understand Input-Output functions

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.

Definition of key terms


• Peripheral: A peripheral device is an internal or external device that connects to a computer
but does not contribute to the computer's primary function, such as computing. It helps end
users access and use the functionalities of a computer.

• Bus: A bus is a subsystem that transfers data between computer components inside a
computer or between computers

Overview of peripheral devices


A peripheral is a device that can be attached to the computer processor. Peripheral devices can be
external, such as a mouse, keyboard, printer, monitor or scanner. Peripheral devices can also be
internal, such as a CD-ROM drive, DVD-R drive or modem.

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.

Examples of input devices


Table 6: Examples of input devices

Device Description Image

Keyboard A keyboard resembles a


typewriter which contains a
set of keys used to input data
and control commands to the
computer. The most
common keyboard has 101
keys with 12 functions keys.

Mouse A mouse is a drawing and


pointing device. A mouse
has one or more buttons on
the top. When a user rolls a
mouse across the flat
surface, the cursor moves on
the screen in the direction of
mouse movement.

Touch screen This is the easiest way to


enter data using the finger
touch. A touch screen allows
the users to select an option
by pressing a specific part of
the screen.

Touchpad Many laptop computers use a


touchpad in front of the
keyboard. We move our
finger on the pad to move
the cursor on the screen.

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.

Joystick It is a pointing device which


is used to move the cursor
position on the screen. A
joystick is a stick which has
a spherical ball at its lower
ends as well as its upper
ends. Joysticks are
commonly used in playing
the game.

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.

Examples of common output devices


Table 7: Examples of common output devices

Device Description Image

Monitor The most common output device


used with computers is the
monitor, which displays video
images and text.

Projectors Projectors are output


devices used mainly by
companies, schools, and
churches to show
information to a large body
of people at the same time

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

speakers/headphones These are hardware devices that


transform the signal from the
computer's sound card into audio

Backing Storage Devices


Backing storage is a device which holds and retains data.

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 Interface unit (BIU)


BIU takes care of all data and addresses transfers on the buses for the EU (Execution Unit) like
sending addresses, fetching instructions from the memory, reading data from the ports and the
memory as well as writing data to the ports and the memory. EU has no direct connection with
System Buses so this is possible with the BIU. EU and BIU are connected with the Internal Bus.

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.

Figure 15:Connection of I/O bus to I/O device

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.

Figure 16:PCI Slots

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.

Figure 18:Video/Graphics Card

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.

Figure 20:USB Connectors

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.

Figure 22:PS/2 Ports

Modes of data transfer:


There are different modes of data transfer. We are going to have a look at the following:
➔ Programmed I/O
➔ Interrupt initiated I/O
➔ Direct memory access(DMA)

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.

The overall operation of the programmed I/O can be summarized as follows:


• The processor is executing a program and encounters an instruction relating to I/O
operation.
• The processor then executes that instruction by issuing a command to the appropriate I/O
module.
41
• The I/O module will perform the requested action based on the I/O command issued by
the processor (READ/WRITE) and set the appropriate bits in the I/O status register.
• The processor will periodically check the status of the I/O module until it finds that the
operation is complete.

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.

Advantages and disadvantages of programmed I/O


42

Advantages - simple to implement

- very little hardware support

Disadvantages - busy waiting

- ties up CPU for long period with no useful work

Interrupt- initiated I/O


Interrupt I/O is a way of controlling input/output activity whereby a peripheral or terminal that
needs to make or receive a data transfer sends a signal. This will cause a program interrupt to be
set at a time appropriate to the priority level of the I/O interrupt.

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.

Figure 24:Interrupt- initiated I/O

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.

Basic Operations of Interrupt

1. CPU issues read command.


2. I/O module gets data from peripheral whilst CPU does other work.
3. I/O module interrupts CPU.
4. CPU requests data.
5. I/O module transfers data.

Interrupt Processing

44
Figure 25:Interrupt Processing

1. A device driver initiates an I/O request on behalf of a process.


2. The device driver signals the I/O controller for the proper device, which initiates the requested
I/O.
3. The device signals the I/O controller that is ready to retrieve input, the output is complete or that
an error has been generated.
4. The CPU receives the interrupt signal on the interrupt-request line and transfer control over the
interrupt handler routine.
5. The interrupt handler determines the cause of the interrupt, performs the necessary processing
and executes a “return from” interrupt instruction.
6. The CPU returns to the execution state prior to the interrupt being signaled.
7. The CPU continues processing until the cycle begins again.

Direct Memory Access (DMA)


Different from Programmed I/O and Interrupt-Driven I/O, Direct Memory Access is a technique
for transferring data within main memory and external device without passing it through the
CPU.

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.

Figure 26:DMA and Interrupt Breakpoints during an Instruction Cycle

Basic Operation of DMA


When the processor wishes to read or send a block of data, it issues a command to the DMA
module by sending some information to the module. The information includes:
● Read or write command, sending through read and write control lines.
● Number of words to be read or written, communicated on the data lines and stored in the
data count register.
● Starting location in memory to read from or write to, communicated on data lines and stored
in the address register.
● Address of the I/O device involved, communicated on the data lines.

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.

Advantages & Disadvantages of DMA

Advantages Allows a peripheral device to read from/write to memory


without going through the CPU

Allows for faster processing since the processor can be working


on something else while the peripheral can be populating
memory

Disadvantages Requires a DMA controller to carry out the operation, which


increases the cost of the system

Cache coherence problems

Key I/O Specifications for a computer


• Keyboard – Layout, Language and ease of use.
• Mouse – Type (Wireless, wired)
• Monitor – Resolution, Size
• Printer – Speed (Pages per minutes), Colour or non-colour, resolution (dpi), type (impact
vs. non impact)
47
Further Reading
1. https://www.tutorialspoint.com/computer_fundamentals/computer_input_devices.htm
2. https://www.tutorialspoint.com/computer_fundamentals/computer_hardware.htm

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.

6.3.5.4 Tools, Equipment, Supplies and Materials


● Computer
● Internet connectivity
● Stationery
● Instruction material
6.3.5.5 References

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

5.1 Number systems are explained Activities may be carried out in


5.2 Integer and Floating point representations are groups or as individual
demonstrated according to IEEE standard
5.3 Integer and Floating point arithmetic is explained
5.4 Logic operators are explained
5.5 Logic operations are explained
5.6 Methods of representing logic operations are
demonstrated

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.

The Number System


The technique to represent and work with numbers is called the number system.
We have different types of numbering systems. They include:
● Decimal number system
● The binary number system
● octal number system
● hexadecimal number system

Decimal Number System


Decimal number system is a base 10 number system having 10 digits from 0 to 9. This means that
any numerical quantity can be represented using these 10 digits. Decimal number system is also a
positional value system. This means that the value of digits will depend on its position. Let us
take an example to understand this.

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

The weightage of each position can be represented as follows –


49
Decimal Number System

Binary Number System


The easiest way to vary instructions through electric signals is the two-state system – on and off.
On is represented as 1 and off as 0, though 0 is not actually a no signal but signal at a lower
voltage.
The number system having just these two digits – 0 and 1 – is called binary number system.
Each binary digit is also called a bit. Binary number system is also a positional value system,
where each digit has a value expressed in powers of 2, as displayed here.

Binary Number System

In any binary number, the rightmost digit is called least significant bit (LSB) and leftmost digit is
called most significant bit (MSB).

Least significant bit (LSB) and 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 –

Octal Number System

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

Hexadecimal Number System


Octal number system has 16 symbols – 0 to 9 and A to F where A is equal to 10, B is equal to 11
and so on till F. Hexadecimal number system is also a positional value system with where each
digit has its value expressed in powers of 16, as shown here –

Hexadecimal Number System

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

Number System Relationship


The following table depicts the relationship between decimal, binary, octal and hexadecimal
number systems.

Table 8: Number System Relationship

HEXADECIMAL DECIMAL OCTAL BINARY

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 –

● 26 upper case letters


● 26 lower case letters
● 10 digits
● 7 punctuation marks
● 20 to 40 special characters

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.

Number Systems Conversions

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:

Reading the remainders from bottom to top,


47310 = 7318

Decimal to Hexadecimal
Decimal numbers can be converted to octal by repeated division of the number by 16 while
recording the remainder.

Example:

Reading the remainders from bottom to top we get,


42310 = 1A716

Binary to Octal and Vice Versa


To convert a binary number to octal number, these steps are followed −
● Starting from the least significant bit, make groups of three bits.

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.

IEEE-based Integer and Floating point representations

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.

Floating Point numbers


As the name implies, floating point numbers are numbers that contain floating decimal points.
For example, the numbers 5.5, 0.001, and -2,345.6789 are floating point numbers.

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.

Floating point arithmetic


Arithmetic operations on floating point numbers consist of addition, subtraction, multiplication
and division the operations are done with algorithms similar to those used on sign magnitude
integers (because of the similarity of representation) -- example, only add numbers of the same
sign. If the numbers are of the opposite sign, you must do subtraction.

Addition
Example on decimal value given in scientific notation:
3.25 x 10 ** 3
+ 2.63 x 10 ** -1
-----------------
First step: Align decimal points

Second step: add

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)

Third step: normalize the result

Example on fl pt. value given in binary:


.25 = 0 01111101 00000000000000000000000
100 = 0 10000101 10010000000000000000000

To add these fl. pt. representations,


Step 1: Align radix points
Shifting the mantissa LEFT by 1 bit DECREASES THE EXPONENT by 1
Shifting the mantissa RIGHT by 1 bit INCREASES THE EXPONENT by 1

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.

0 01111101 00000000000000000000000 (original value)


0 01111110 10000000000000000000000 (shifted 1 place)
(note that hidden bit is shifted into msb of mantissa)
0 01111111 01000000000000000000000 (shifted 2 places)
0 10000000 00100000000000000000000 (shifted 3 places)
0 10000001 00010000000000000000000 (shifted 4 places)
0 10000010 00001000000000000000000 (shifted 5 places)
0 10000011 00000100000000000000000 (shifted 6 places)
0 10000100 00000010000000000000000 (shifted 7 places)
0 10000101 00000001000000000000000 (shifted 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.

Before subtracting, compare magnitudes (don't forget the hidden bit!)


Change sign bit if order of operands is changed. Don't forget to normalize numbers afterward.

Multiplication
Example on decimal values given in scientific notation:
3.0 x 10 ** 1
+ 0.5 x 10 ** 2
-----------------

Algorithm: multiply mantissa, add exponents


3.0 x 10 ** 1
+ 0.5 x 10 ** 2
-----------------
1.50 x 10 ** 3

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.

Unsigned representation for 65 is 01000001.

Put the result back together (and add sign bit).


1 01000001 10.00110000

Normalize the result:


(Moving the radix point one place to the left increases the exponent by 1.)

1 01000001 10.00110000
becomes
1 01000010 1.000110000

This is the value stored (not the hidden bit!):


1 01000010 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.

Some comparisons of approximate times:


2's complement integer add 1 time unit
fl. pt add 4 time units
fl. pt multiply 6 time units
fl. pt. divide 13 time units

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.

Division by reciprocal approximation:


Instead of doing a / b, they do a x 1/b.
Figure out a reciprocal for b, and then use the fl. pt.

Example of a result that isn't the same as with true division.


True division: 3/3 = 1 (exactly)
Reciprocal approx: 1/3 = .33333333

3 x .33333333 = .99999999, not 1

It is not always possible to get a perfectly accurate reciprocal.

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

Round toward + infinity -- regardless of the value, round towards +infinity.

Example:
1.23 If 2 decimal places, 1.3
-2.86 if 2 decimal places, -2.8

Round toward - infinity -- regardless of the value, round towards -infinity.

Example:
1.23 If 2 decimal places, 1.2

60
-2.86 if 2 decimal places, -2.9

In binary -- rounding to 2 digits after radix point


Round toward + infinity --
1.1101
|
1.11 | 10.00
------
1.001
|
1.00 | 1.01
-----

Round toward - infinity --

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

Conversion of Byte Integer to Word


● Sign Extension

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

Conversion of Word Integer to Byte


● Remove the upper byte of the word. Retain only the lower byte.
● Meaningful only if the original number can be represented by a byte.

Integer Arithmetic (1's Comp and 2's Comp)


● Addition: Simply add the two binary representations.
● Subtraction: Find negative of one number, add to the second.

Addition in 1's Comp


● Add binary representations of the two numbers.
● If there is a carry, add it back in on the right side.
51 00110011
+ (-37) + 11011010
----------
1 00001101
+1
----------
14 00001110

Addition in 2's Comp


● Add binary representations of the two numbers.
● Disregard the carry.
51 00110011
+ (-37) + 11011011
----------
14 1 00001110

Subtraction in 2's Comp


Overflow
● If two numbers have different signs, their sum will never overflow.
● If they have the same sign, they might overflow.
● Overflow has occurred if sign of result is different than sign of addends.

Logic operators and Logic Operations


A logical operator is a special symbol or word that connects two or more phrases of information.

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.

Below is the circuit diagram of an OR logic gate.

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.

Below is the circuit diagram of an AND logic gate.

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).

Below is the circuit diagram of a NOT logic gate.

NOT logic gate

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.)

Below is the circuit diagram of a NOR logic gate.

NOR logic gate

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).

Below is the XOR operation circuit diagram.

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).

Below is the XNOR operation circuit diagram.

Exclusive NOT OR gate

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.6.4 Tools, Equipment, Supplies and Materials


● Computer
● Internet connectivity
● Calculator
● Stationery
● Instruction material

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.

3.2 Performance Standard


1. Installed Windows Operating system
2. Demonstrated process management using the task manager
3. Demonstrated resource allocation using the performance monitor tool
4. Demonstrated disk storage management operations
5. Demonstrated device management using the Device Manager
6. Demonstrated file and directory operations
7. Configured local policy security settings.

3.3. Learning Outcomes


3.3.1. List of learning outcomes
1. Understand fundamentals of operating systems
2. Understand Process Management
3. Understand Memory Management
4. Understand Input and Output Management
5. Understand File Management and local policy settings

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

1.1 Computer Software is explained ● Activities may be carried out in


1.2 Operating system is explained groups or as individual
1.3 Structures of operating systems are described.
1.4 Types of operating systems are explained.
1.5 Installation requirements for Windows are outlined
1.6 Installation of Windows is demonstrated

3.3.2.2 Information sheet No 3/LO1: Understand fundamentals of operating systems

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.

Definition of key terms


Software: A set of programs, which is designed to perform a well-defined function. There are two
types of software; System Software and Application Software.

Computer program: A sequence of instructions written to solve a particular problem.

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.

Application Software: This is software designed to satisfy a particular need of a particular


environment. Application software may consist of a single program, such as Adobe Reader or
consist of a collection of programs, often called a software package, which work together to
accomplish a task, such as a Microsoft Office.

Operating system concepts

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.

An operating system has two parts


(i) The Kernel: This is the active part of an operating system which is running at all times.
It consist of programs which can interact with the hardware. Examples are device drivers
and system files.
(ii) The Shell - It is also called the command interpreter. It is a set of programs used to
interact with the application programs. It is responsible for execution of instructions
given to the operating system.

The goals of an operating system in a computer system include:


• Executing user programs and make solving user problems easier.
• Making the computer system convenient to use.
• Using the computer hardware in an efficient manner.

Functions of Operating Systems


i) Process Management
• A process is a program in execution. A process needs certain resources, including CPU
time, memory, files, and I/O devices, to accomplish its task.
• The operating system is responsible for the following activities in connection with process
management.
o Process creation and deletion.
o Process suspension and resumption.
o Provision of mechanisms for process synchronization and process
communication

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.

iii) File Management


• A file is a collection of related information defined by its creator. Commonly, files
represent programs (both source and object forms) and data.
• The operating system is responsible for the following activities in connections with file
management:
o File creation and deletion.
72
o Directory creation and deletion.
o Support of mechanisms for manipulating files and directories.
o Mapping files onto secondary storage.
o File backup on stable (non-volatile) storage media.

iv) The Input/Output (I/O) System Management


The I/O system consists of:
• A buffer-caching system
• A general device-driver interface
• Drivers for specific hardware devices

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

vi) Networking (Distributed Systems)


• A distributed system is a collection of processors that do not share memory or a clock.
Each processor has its own local memory.
• The processors in the system are connected through a communication network.
• Communication takes place using a protocol.
• A distributed system provides user access to various system resources.
• Access to a shared resource allows:
o Computation speed-up
o Increased data availability
o Enhanced reliability

vii) Protection System


• Protection refers to a mechanism for controlling access by programs, processes, or users
to both system and user resources.
• The protection mechanism must:
o Distinguish between authorized and unauthorized usage.
o Specify the controls to be imposed.
o Provide a means of enforcement.
73
viii) Command-Interpreter System
• Many commands are given to the operating system by control statements which deal with
all the above functions.
• The program that reads and interprets control statements is called variously; command-
line interpreter and shell (in UNIX)
• The function of the command-interpreter system is to get and execute the next command
statement.

Structures of operating systems


Operating systems services are built using various architectures, including:
• Monolithic system architecture
• Layered architecture
• Virtual Structure
• Client Server model

Monolithic System Architecture


In this architecture, the entire operating system works in the kernel space. This increases the size
of the kernel as well as the operating system. The kernel provides various services such as memory
management, file management and process scheduling.

The diagram below demonstrates the architecture of a monolithic system

Figure 28:Monolithic System Architecture

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.

Figure 29:Layered architecture

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.

Layering has several advantages:


• All the layers can be defined separately and interact with each other as required.
• It is easier to create, maintain and update the system if it is done in the form of layers.
Change in one layer specification does not affect the rest of the layers.

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.

Figure 30:Virtual Architecture

Client Server Architecture


Client Server communication involves two components, namely a client and a server. They are
usually multiple clients in communication with a single server. The clients send requests to the
server and the server responds to the client requests.

Types of Operating Systems

Batch Processing Operating Systems


This type of operating systems accepts more than one job and these jobs are batched/ grouped
together according to their similar requirements. This is done by computer operator. Whenever
the computer becomes available, the batched jobs are sent for execution and gradually the output
is sent back to the user.
76
Multiprogramming Operating Systems
This type of operating system is used to execute more than one job simultaneously by a single
processor. It increases CPU utilisation by organizing jobs so that the CPU always has one job to
execute.

The concept of multiprogramming works as follows:


• All the jobs that enter the system are stored in the job pool (in disc). The operating system
loads a set of jobs from the job pool into main memory and begins to execute.
• During execution, the job may have to wait for some task, such as an I/O operation, to
complete. In a multiprogramming system, the operating system simply switches to
another job and executes.
• When that job needs to wait, the CPU is switched to another job, and so on.
• When the first job finishes waiting and it gets the CPU back.
• As long as at least one job needs to execute, the CPU is never idle.

Time-Sharing/multitasking Operating Systems


A time sharing (or multitasking) operating system is a logical extension of multiprogramming. It
provides extra facilities such as:
• Faster switching between multiple jobs to make processing faster.
• Allows multiple users to share computer system simultaneously.
• The users can interact with each job while it is running.
• These systems use a concept of virtual memory for effective utilisation of memory space.
Hence, in this operating system, no jobs are discarded. Each one is executed using the
virtual memory concept.
• Examples of timesharing systems: MULTICS and UNIX

Multiprocessor Operating Systems


Such operating systems have more than one processor in close communication that sharing the
computer bus, the clock and sometimes memory and peripheral devices. It executes multiple jobs
at same time and makes the processing faster.

Multiprocessor systems have three main advantages:


• Increased throughput: By increasing the number of processors, the system performs more
work in less time.
• Economy of scale: Multiprocessor systems can save more money than multiple single-
processor systems, because they can share peripherals, mass storage, and power supplies.
• Increased reliability: If one processor fails to done its task, then each of the remaining
processors must pick up a share of the work of the failed processor. The failure of one
processor will not halt the system, only slow it down.

Distributed Operating Systems

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.

The advantages of distributed systems include:


• Resources sharing
• Computation speed up – load sharing
• Reliability – Each machine has processing capability and can take over the work of
another machine that fails.

Desktop Systems/Personal Computer Systems


The PC operating system is designed for maximizing user convenience and responsiveness. This
system is neither multi-user nor multitasking. These systems include PCs running Microsoft
Windows and the Apple Macintosh.

Real-Time Operating Systems (RTOS)


A real-time operating system (RTOS) is a multitasking operating system intended for applications
with fixed deadlines (real-time computing). Such applications include some small embedded
systems, industrial robots, spacecraft, industrial control and some large-scale computing systems.

Installing Windows Operating System


Different versions of Windows operating system have different installation requirements.

Definition of key terms

BIOS - (basic input/output system) is the program (firmware) a personal computer's


microprocessor uses to get the computer system started after you turn it on. It also manages data
flow between the computer's operating system and attached devices such as the hard disk, video
adapter, keyboard, mouse and printer.

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.

Original equipment manufacturer (OEM) is an original equipment manufacturer (OEM) is a


company whose goods are used as components in the products of another company, which then
sells the finished item to users.

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.

PrebooteXecution Environment (PXE) is an industry standard client/server interface that allows


networked computers that are not yet loaded with an operating system to be configured and
booted remotely by an administrator.

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.

Scheduled or automated installation


An installation process that runs on a preset time or when a predefined condition transpires, as
opposed to an installation process that starts explicitly on a user's command. For instance, a
system administrator willing to install a later version of a computer program that is being used
can schedule that installation to occur when that program is not running.

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.

Methods of windows desktop operating system installation

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 a clean installation


• A clean installation is an opportunity to start fresh from scratch without any unwanted
software and trial software that might have come pre-installed with your system.
• You will also regain control over your applications, as you can now install only the
applications you need, and you'll also start with a brand new and clean Windows Registry.
• Chances of running into errors and other issues will significantly be reduced. If your PC had
any software or hardware issues, doing a clean installation likely resolves any problems.

Disadvantages of clean installation


• Starting from scratch also takes longer than doing a plain in-place upgrade because you will
need to reinstall and reconfigure any software you previously had.
• It also requires that you have the applications installation files and products keys.
80
• If the Windows setup cannot recognize different hardware in your computer, you will have
to manually find and install all the necessary drivers, which is not sometimes an easy task
• Besides deleting all your applications and settings, performing a clean installation of
Windows will delete all your files. Therefore make sure you backup all your data before
using the upgrade path.

ii) Upgrade Installation


Sometimes, it is also possible to perform an upgrade. When you perform an upgrade, OS
configuration settings, installed programs and data are preserved. With this installation you have
nothing to worry about, because you will not lose any personal data. You will just replace the old
operating system files with the new, upgraded files.

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.

iii) Multi-boot Installation


Another option is to install multiple operating systems on a single computer. You can install each
OS inside a different disk partition and this way every OS will have its own files and
configuration settings. On multi-boot installations, the users see a menu when they open their
computers and they have to select the desired OS. Of course, only one operating system can run
at a time.

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.

Table 10: System requirements for installing Windows 10

Processor 1 gigahertz (GHz) or faster compatible processor or


System on a Chip (SoC)
RAM 1 gigabyte (GB) for 32-bit or 2 GB for 64-bit
Hard drive size 32GB or larger hard disk
Graphics card Compatible with DirectX 9 or later with WDDM 1.0
driver
Display 800x600
Internet Connection Internet connectivity is necessary to perform updates and
to download and take advantage of some features.

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.

4. Decide the type of file system to use.


The file system controls how the OS stores and tracks the files. There are several different file
systems available. The most well-known are: FAT 32, NTFS, HPFS, ext2 and ext3. Every
operating system is designed to use one or more of these file systems. There are advantages and
disadvantages on every file system. Careful consideration should be made to the type of file
systems supported by the selected OS and the benefits of each.
You can find several programs to modify the partitioning structure and file system of a hard drive
after installation, but it is better to avoid them if possible. When modifying either the file system
or partition structure on a hard drive, data loss may result. Careful planning can help preserve the
integrity of the data.

Windows desktop operating system installation procedure

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.

3. Save the settings change and exit BIOS.


Once you have updated the boot order, you can begin the Windows installation process.

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.

How to install and update a computer driver.


It is strongly recommended that you install the latest drivers for each piece of hardware.

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.

Windows desktop operating system customization

Setting the date and time in Windows 10


Note: Windows 10 automatically adjusts your date and time for you and only allows you to adjust
the time if you disable this feature. If the wrong date and time are set, you need to change the
time zone, or increase or decrease the time for other reasons, follow the steps below.

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.

How to configure remote desktop


To open Remote Desktop in Windows Professional, follow these steps.
• Click the Start button, type remote desktop, and click on Remote Desktop connection.
• Or, in the Start menu, click Windows Accessories, then click Remote Desktop Connection.

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.

Change Computer name


Step 1
Click the Start Button and right-click Computer and select Properties.
Note: Like all things Windows, there are several ways to do the same thing. With Windows 7 and
Vista, you can just type System and click System as shown to the right.

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.

Customization of Licence settings


1. Use the Windows key + R keyboard shortcut to open the Run command.
2. Type slui.exe 3 and click OK to open the Windows activation client.
3. Type the 25-digit product key for the version of Windows 10 you want.
4. Click Next to complete the task.
If the activation process completes successfully, you'll get the "Windows is activated" message.

How to change Windows 10's product key using CHANGEPK


1. Use the Windows key + R keyboard shortcut to open the Run command.
2. Type changepk.exe and click OK to open the Windows activation client.
3. Enter the 25-digit product key for the version of Windows 10 you want.
4. Click Next to complete the task.

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>

To Configure Network settings


1. Select Start, then select Settings > Network & Internet .
2. Do one of the following:
• For a Wi-Fi network, select Wi-Fi > Manage known networks. Choose the network you
want to change the settings for, then select Properties.
• For an Ethernet network, select Ethernet, then select the Ethernet network you’re connected
to.
3. Under IP assignment, select Edit.
4. Under Edit IP settings, select Automatic (DHCP) or Manual.

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

3.3.2.3 Self Assessment

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.4 Tools, equipment, supplies and materials


• Computer
• Internet connectivity
• Windows Set Up file
• Stationery
• Instruction material

3.3.2.5 References

1. Computer - Software. Retrieved from


https://www.tutorialspoint.com/computer_fundamentals/computer_software.htm
2. Layered Operating Systems. Retrieved from https://www.tutorialspoint.com/layered-
operating-system
3. Windows 10 specifications. Retrieved from https://www.microsoft.com/en-
us/windows/windows-10-specifications
4. https://pcdreams.com.sg/operating-system-options-and-installation-methods/
5. https://www.windowscentral.com/how-change-product-key-windows-10

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

2.1 Process management is explained ● Activities may be carried out in


2.2 Manage computer resources groups or as individual
2.3 Process states and transitions are explained
2.4 Process scheduling is explained
2.5 Use of the Task Manager is demonstrated
2.6 Use of performance monitor tool is demonstrated

3.3.2.2 Information sheet No 3/LO2: Understand Process Management

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.

Introduction to Process Management

The Process Concept


A process is basically a program in execution. The execution of a process must progress in a
sequential fashion.

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

Component & Description

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.

A part of a computer program that performs a well-defined task is known as an algorithm. A


collection of computer programs, libraries and related data are referred to as a software.

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

Process Control Block (PCB)


A Process Control Block is a data structure maintained by the Operating System for every process.
The PCB is identified by an integer process ID (PID). A PCB keeps all the information needed to
keep track of a process as listed below in the table −
Information & Description

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.

7 CPU Scheduling Information


Process priority and other scheduling information which is required to schedule
the process.

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 −

Figure 33:Process Control Block (PCB)

The PCB is maintained for a process throughout its lifetime, and is deleted once the process
terminates.

Managing Computer Resources


Processes need two key resources such as the processor or CPU and storage space (main memory
and disk). In a multiprogramming environment, several processes constantly request to use these
resources and therefore a sharing mechanism for the CPU and other resources needs to be in
place to meet the needs the needs of each process so that it can be scheduled and be completed on
time.

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.

Process scheduling is an essential part of multiprogramming operating systems. Such operating


systems allow more than one process to be loaded into the executable memory at a time and the
loaded process shares the CPU using time multiplexing.

Process Scheduling Queues


The OS maintains all PCBs in Process Scheduling Queues. The OS maintains a separate queue for
each of the process states and PCBs of all processes in the same execution state are placed in the
same queue. When the state of a process is changed, its PCB is unlinked from its current queue and
moved to its new state queue.

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.

Figure 34:Process Scheduling Queues

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.

Use of dispatcher is as follows. When a process is interrupted, that process is


transferred in the waiting queue. If the process has completed or aborted, the
process is discarded. In either case, the dispatcher then selects a process from the
queue to execute.

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

Long Term Scheduler


It is also called a job scheduler. A long-term scheduler determines which programs are admitted
to the system for processing. It selects processes from the queue and loads them into memory for
execution. Process loads into the memory for CPU scheduling.

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.

Short Term Scheduler


It is also called as CPU scheduler. Its main objective is to increase system performance in
accordance with the chosen set of criteria. It is the change of ready state to running state of the

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.

Medium Term Scheduler


Medium-term scheduling is a part of swapping. It removes the processes from the memory. It
reduces the degree of multiprogramming. The medium-term scheduler is in-charge of handling the
swapped out-processes.

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.

Table 11: Comparison among Schedulers

Long-Term Scheduler Short-Term Scheduler Medium-Term Scheduler

1 It is a job scheduler It is a CPU scheduler It is a process swapping


scheduler.

2 Speed is lesser than Speed is fastest among Speed is in between both


short term scheduler other two short and long term
scheduler.

3 It controls the degree of It provides lesser control It reduces the degree of


multiprogramming over degree of multiprogramming.
multiprogramming

4 It is almost absent or It is also minimal in time It is a part of Time sharing


minimal in time sharing sharing system systems.
system

5 It selects processes from It selects those processes It can re-introduce the


pool and loads them which are ready to execute process into memory and
into memory for execution can be continued.
execution
Context Switching
A context switch is the mechanism to store and restore the state or context of a CPU in Process
Control block so that a process execution can be resumed from the same point at a later time.

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.

Figure 35:Context Switching

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.

There are six popular process scheduling algorithms


• First-Come, First-Served (FCFS) Scheduling
• Shortest-Job-Next (SJN) Scheduling
• Priority Scheduling
• Shortest Remaining Time
• Round Robin(RR) Scheduling
• Multiple-Level Queues Scheduling

These algorithms are either non-preemptive or preemptive. Non-preemptive algorithms are


designed so that once a process enters the running state, it cannot be preempted until it completes
its allotted time, whereas the preemptive scheduling is based on priority where a scheduler may
preempt a low priority running process anytime when a high priority process enters into a ready
state.

First Come First Serve (FCFS)


• Jobs are executed on first come, first serve basis.
• It is a non-preemptive, pre-emptive scheduling algorithm.
• Easy to understand and implement.
• Its implementation is based on FIFO queue.
• Poor in performance as average wait time is high.

Wait time of each process is as follows −


Process Wait Time : Service Time - Arrival Time

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

Shortest Job Next (SJN)


• This is also known as shortest job first, or SJF
• This is a non-preemptive, pre-emptive scheduling algorithm.
• Best approach to minimize waiting time.
• Easy to implement in Batch systems where required CPU time is known in advance.
• Impossible to implement in interactive systems where required CPU time is not known.
• The processer should know in advance how much time process will take.

Given: Table of processes, and their Arrival time, Execution time


Process Arrival Time Execution Time Service Time

P0 0 5 0

P1 1 3 5

P2 2 8 14

P3 3 6 8

Waiting time of each process is as follows −


Process Waiting Time

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

Priority Based Scheduling

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

Waiting time of each process is as follows −


Process Waiting Time

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

Shortest Remaining Time


• Shortest remaining time (SRT) is the preemptive version of the SJN algorithm.
• The processor is allocated to the job closest to completion but it can be preempted by a
newer ready job with shorter time to completion.
• Impossible to implement in interactive systems where required CPU time is not known.
• It is often used in batch environments where short jobs need to give preference.

Round Robin Scheduling


• Round Robin is the preemptive process scheduling algorithm.
• Each process is provided a fix time to execute, it is called a quantum.

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.

Wait time of each process is as follows −


Process Wait Time : Service Time - Arrival Time

P0 (0 - 0) + (12 - 3) = 9

P1 (3 - 1) = 2

P2 (6 - 2) + (14 - 9) + (20 - 17) = 12

P3 (9 - 3) + (17 - 12) = 11
Average Wait Time: (9+2+12+11) / 4 = 8.5

Multiple-Level Queues Scheduling


Multiple-level queues are not an independent scheduling algorithm. They make use of other
existing algorithms to group and schedule jobs with common characteristics.
• Multiple queues are maintained for processes with common characteristics.
• Each queue can have its own scheduling algorithms.
• Priorities are assigned to each queue.
For example, CPU-bound jobs can be scheduled in one queue and all I/O-bound jobs in another
queue. The Process Scheduler then alternately selects jobs from each queue and assigns them to
the CPU based on the algorithm assigned to the queue.

Using the Windows 10 Task Manager: An overview


The Windows Task Manager is a powerful tool packed with useful information, from your
system’s overall resource usage to detailed statistics about each process

How to Launch the Task Manager


The simplest one is pressing Ctrl+Alt+Delete and then click “Task Manager” on the screen that
appears or find the Task Manager shortcut in your Start menu.

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.

The Task Manager’s Tabs

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.

Task Manager Menu Options

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.

Using the Windows 10 Performance Monitor


When your computer suddenly isn't fast as usual, or keeps hanging, you're likely dealing with
performance issues that could be caused by a number of reasons.

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.

How to open Performance Monitor


Here are three ways to open Performance Monitor:
• Open Start, do a search for Performance Monitor, and click the result.
• Use the Windows key + R keyboard shortcut to open the Run command, type perfmon,
and click OK to open.
• Use the Windows key + X keyboard shortcut to open the Power User menu,
select Computer Management, and click on Performance

How to use Performance Monitor


When you first open the tool, it'll open in the main page with a brief overview, as well as a system
summary with real-time data about memory, network adapter, physical disk, and processor usage.

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.

Adding new counters

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.

7. Click OK to confirm and add the new counters.

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.

To customize the Performance Monitor view, do the following:


1. Double-click one of the counters to open the Performance Monitor Properties window.
2. On the "Data" tab, select the counter you want to customize.
3. At the bottom, choose the color, scale, width, and style you want to use.
4. Repeat steps 2 and 3 for each item you want to customize.

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

• Remzi H. Arpaci-Dusseau and Andrea C. Arpaci-Dusseau (2014). "Operating


Systems: Three Easy Pieces". Arpaci-Dusseau Books. Relevant chapters: Abstraction: The
Process The Process API

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

3.3.2.3 Self assessment

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.4 Tools, Equipment, Supplies and Materials


• Computer
• Internet Connectivity
• Stationery
• Instruction material

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

3.1 Memory management is explained. ● Activities may be carried out in


3.2 Memory management techniques are explained. groups or as individual
3.3 Virtual memory management settings are demonstrated

3.3.4.2 Information sheet No 3/LO3: Understand Memory Management

Introduction
This learning outcome covers memory management. It entails explaining management, explaining
memory management techniques and demonstrating virtual memory settings.

Introduction to memory management


Together with the CPU, the physical memory is the most important resource a computer has. The
CPU chip has instructions to manipulate data only directly in memory, so all arithmetic and logic
operations must take place in RAM.

Memory management is the functionality of an operating system which handles or manages


primary memory and moves processes back and forth between main memory and disk during
execution.

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.

Process Address Space


The process address space is the set of logical addresses that a process references in its code. For
example, when 32-bit addressing is in use, addresses can range from 0 to 0x7fffffff; that is, 2^31
possible numbers, for a total theoretical size of 2 gigabytes.

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.

Figure 39: Process Swapping in memory

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

2048KB / 1024KB per second = 2 seconds = 2000 milliseconds

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.

Fragmentation is of two types −


Fragmentation & Description

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.

Memory Management Techniques


The following are the three key memory management techniques used by an operating system:
• Paging
• Segmentation
Paging
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 that's set up to emulate
the computer's RAM. Paging technique plays an important role in implementing virtual memory.

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.

Figure 41: Memory paging

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.

Figure 42: Memory Address Translation


115
When the system allocates a frame to any page, it translates this logical address into a physical
address and create entry into the page table to be used throughout execution of the program.

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 −

Figure 44:Virtual Memory

Virtual memory is commonly implemented by demand paging. It can also be implemented in a


segmentation system. Demand segmentation can also be used to provide virtual memory.

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.

Advantages of Demand Paging


• Large virtual memory.
• More efficient use of memory.
• There is no limit on degree of multiprogramming.

Disadvantages of Demand Paging


• Number of tables and the amount of processor overhead for handling page interrupts are
greater than in the case of the simple paged management techniques.

Virtual Memory Configuration in Windows 10


On Windows 10, virtual memory (or paging file) is an essential component (hidden file) designed to
remove and temporarily store less frequently use modified pages allocated in RAM (random-access
memory) to the hard drive.

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.

How to increase virtual memory using Settings

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.

6. Click the Advanced tab.


7. Under the "Performance" section, click the Settings button

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.

How to increase virtual memory using Command Prompt

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:

wmic pagefileset where name="C:\\pagefile.sys" set


InitialSize=YOUR-INIT-SIZE, MaximumSize=YOUR-MAX-SIZE

This example sets the paging file to "9216" and "12288" megabytes for the initial and maxium size:

wmic pagefileset where name="C:\\pagefile.sys" set


InitialSize=9216, MaximumSize=12288

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.4 Tools, equipment, supplies, and material


• Computer
• Internet connectivity
• Stationery
• Instruction material

3.3.4.5 References

1. Memory Management Techniques in Operating Systems. Retrieved from


https://www.includehelp.com/operating-systems/memory-management-techniques-in-
operating-system.aspx
2. How to change virtual memory size on Windows 10. Retrieved from
https://www.windowscentral.com/how-change-virtual-memory-size-windows-10

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

4.1 Input - output management is explained ● Activities may be carried out in


4.2 Disk operations are explained groups or as individual
4.3 Computer clock system is explained
4.4 Virtual Input Output is explained
4.5 Disk selection criteria are outlined
4.6 Verification of disk properties is demonstrated
4.7 Disk storage management operations are demonstrated
4.8 Device management operations are demonstrated

3.3.5.2 Information sheet No 3/LO4: Understand Input and output management

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 Management Service


• The controlling of various devices that are connected to the computer is a key concern of
operating-system designers. This is because I/O devices vary so widely in their functionality
and speed (for example a mouse, a hard disk and a CD-ROM), varied methods are required
for controlling them.
• These methods form the I/O sub-system of the kernel of OS that separates the rest of the
kernel from the complications of managing I/O devices.

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.

Figure 46:Device Controllers

Synchronous vs. asynchronous I/O


• Synchronous I/O − In this scheme CPU execution waits while I/O proceeds
• Asynchronous I/O − I/O proceeds concurrently with CPU execution

Communication to I/O Devices


The CPU must have a way to pass information to and from an I/O device. There are three
approaches available to communicate with the CPU and Device.
• Special Instruction I/O
• Memory-mapped I/O
• Direct memory access (DMA)

Special Instruction I/O


This uses CPU instructions that are specifically made for controlling I/O devices. These
instructions typically allow data to be sent to an I/O device or read from an I/O device.

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.

Figure 47:Memory-mapped I/O

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.

Direct Memory Access (DMA)


• Slow devices like keyboards will generate an interrupt to the main CPU after each byte is
transferred.
• If a fast device such as a disk generated an interrupt for each byte, the operating system
would spend most of its time handling these interrupts. So a typical computer uses direct
memory access (DMA) hardware to reduce this overhead.
• Direct Memory Access (DMA) means CPU grants I/O module authority to read from or
write to memory without involvement.
• DMA module itself controls exchange of data between main memory and the I/O device.
CPU is only involved at the beginning and end of the transfer and interrupted only after
entire block has been transferred.
• Direct Memory Access needs a special hardware called DMA controller (DMAC) that
manages the data transfers and arbitrates access to the system bus.

Polling vs. Interrupts I/O


• A computer must have a way of detecting the arrival of any type of input.

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.

Device-Independent I/O Software


• The basic function of the device-independent software is to perform the I/O functions that
are common to all devices and to provide a uniform interface to the user-level software.

Following is a list of functions of device-independent I/O Software −


• Uniform interfacing for device drivers
• Device naming - Mnemonic names mapped to Major and Minor device numbers
• Device protection
• Providing a device-independent block size
• Buffering because data coming off a device cannot be stored in final destination.
• Storage allocation on block devices
• Allocation and releasing dedicated devices
• Error Reporting

User-Space I/O Software


• These are the libraries which provide richer and simplified interface to access the
functionality of the kernel or ultimately interactive with the device drivers.
• I/O Libraries (e.g., stdio) are in user-space to provide an interface to the OS resident
device-independent I/O SW. For example putchar(), getchar(), printf() and scanf() are
example of user level I/O library stdio available in C programming.

Kernel I/O Subsystem


130
Kernel I/O Subsystem is responsible to provide many services related to I/O. Following are some
of the services provided.
• Scheduling − Kernel schedules a set of I/O requests to determine a good order in which to
execute them.
• Buffering − Kernel I/O Subsystem maintains a memory area known as buffer that stores
data while they are transferred between two devices or between a device with an
application operation. Buffering is done to cope with a speed mismatch between the
producer and consumer of a data stream or to adapt between devices that have different
data transfer sizes.
• Caching − Kernel maintains cache memory which is region of fast memory that holds
copies of data. Access to the cached copy is more efficient than access to the original.
• Spooling and Device Reservation − A spool is a buffer that holds output for a device, such
as a printer, that cannot accept interleaved data streams. The spooling system copies the
queued spool files to the printer one at a time. In some operating systems, spooling is
managed by a system daemon process. In other operating systems, it is handled by an in
kernel thread.
• Error Handling − an operating system that uses protected memory can guard against many
kinds of hardware and application errors.

Disk I/O Operations


• As we know, a process needs two type of time, CPU time and IO time. For I/O, it requests
the Operating system to access the disk.
• However, the operating system must be fair enough to satisfy each request and at the same
time, operating system must maintain the efficiency and speed of process execution.

• 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.

Purpose of Disk Scheduling


The main purpose of disk scheduling algorithm is to select a disk request from the queue of IO
requests and decide the schedule when this request will be processed.
131
Goal of Disk Scheduling Algorithm
o Fairness
o High throughout
o Minimal traveling head time

Disk Scheduling Algorithms


o FCFS scheduling algorithm
o SSTF (shortest seek time first) algorithm
o SCAN scheduling
o C-SCAN scheduling
o LOOK Scheduling
o C-LOOK scheduling

Computer clock system in I/O


Three types of time services are commonly needed in modern systems:
• Get the current time of day.
• Get the elapsed time (system or wall clock) since a previous event.
• Set a timer to trigger event X at time T.

Unfortunately time operations are not standard across all systems.

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.

Virtual Input Output


I/O virtualization (IOV) is technology that uses software to abstract upper-layer protocols from
physical connections

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.

Key Disk selection criteria

Choose the correct interface.

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.

Buy the right capacity drive.


Very large drives often cost more per gigabyte than midsize drives, and the largest drives may have
slower mechanisms than midsize drives. In general, decide what performance level you need and
are willing to pay for, and then buy a drive that meets those performance requirements, choosing
the model based on its cost per gigabyte

Get a model with large cache if it doesn't cost much more.


Disk drives use cache (or buffer) memory to increase performance. Generally, the larger the cache,
the faster the performance.

Pay attention to power consumption and noise level.


Similar drives can differ significantly in power consumption and noise level. A drive that
consumes more power also produces more heat, which contributes indirectly to overall system
noise level because the system exhaust fans must work harder.

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.

Verifying Disk properties in Windows


If you'd like to view detailed information about your hard disk drives, solid-state drives, or external
storage devices attached to your computer, you can access System Information utility.

To open the System Information utility in Windows 10:


1. Press the Windows key, type System Information, and press Enter.

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 Storage Management in Windows


Disk Management is an extension of the Microsoft Management Console that allows full
management of the disk-based hardware recognized by Windows.

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.

Disk Management Availability

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.

How to Open Disk Management


The most common way to access Disk Management is via the Computer Management utility.

How to Open Disk Management

Figure 48: Windows Disk Manager

Disk Management can also be started by executing diskmgmt.msc via the Command Prompt or
another command-line interface in Windows.

How to Use Disk Management


Disk Management has two main sections—a top and a bottom:

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.

How to Partition a Hard Drive in Windows


N/B: Manually partitioning (as well as formatting) a hard drive is not necessary if your end goal is
to install Windows onto the drive. Both of those processes are included as part of the installation
procedure, meaning you don't need to prepare the drive yourself.

1. Open Disk Management, the tool included in all versions of Windows that lets you partition
drives, among a number of other things.

How to Open Disk Management

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.

New Simple Volume Wizard window

7. Choose Next > on the Specify Volume Size step to confirm the size of the drive you're creating.

Specify Volume Size

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?"

12. Tap or click Cancel for now.

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.

How to Format a Hard Drive in Windows


Step 1. Open Disk Management, the hard drive manager included with all versions of Windows.

Open Disk Management

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.

As a reminder, here's what you should see:

• Volume label: [label of your choosing]


• File system: NTFS
• Allocation unit size: Default
• Perform a quick format: unchecked
• Enable file and folder compression: unchecked

8. Windows is usually pretty good about warning you before you might do something damaging,
and a hard drive format is no exception.

Click OK to the warning message about formatting the drive.

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.

9. The hard drive format has begun!


You can check the progress by watching the Formatting: xx% indicator under the Status column in
the top part of Disk Management or in the graphical representation of your hard drive in the bottom
section.

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.

Note: Formatting Deletes Data — but Doesn't Always Erase It


When you format a drive in Windows, data may or may not truly be erased. Depending on your
version of Windows, and the type of format, it's possible the data is still there, hidden from
Windows and other operating systems but still accessible in certain situations.

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.

Why shrink a volume?


Changing partition size is a useful practice if you want to make best of disk space on your
computer. For instance, there is a 2TB hard drive on your computer and the disk is divided into two
partitions, a 500GB system partition where Windows is installed and a 1.4TB partition for your
music, photos, games, working documents, learning material, etc.

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.

Tools to shrink partition


Changing partition size is one the basic operations that should be mastered by computer users for
the sake of taking full advantage of disk space and rationally managing data.

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.

Shrink a basic volume in Disk Management


1. Open Disk Management.
2. Right-click on the partition you want to reduce its size and choose Shrink Volume, as below.

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.

Shrink a basic volume

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.

Shrink limitations on Disk Management:


Disk Management cannot deal with all issues about partition shrink, and here are some limitations.

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.

Disk Optimization and Defragmentation


There are two types of optimization; hardware and software optimization

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.

Figure 49:Disk Fragmentation

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.

Scan For Errors


Another thing we can do to optimize storage devices is to scan disks for errors. We can use the error
checking utility in Windows to check for file systems errors and bad sectors on our hard drive. We
can choose to automatically try to fix errors.

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.

Device Management in Windows

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).

How to identify (some) problem drivers using Windows Device Manager


Windows Device Manager shows you which devices have corrupt drivers. It may also show you
which devices have outdated drivers.

IMPORTANT: Windows Device Manager doesn’t always detect outdated drivers. So you
can’t assume all your drivers are up to date

To identify corrupt drivers and maybe some outdated drivers:


1. On your keyboard, press the Windows logo key and R at the same time to invoke the run box.
2. Type devmgmt.msc and click OK.

(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.

How to update or reinstall drivers using Windows Device Manager


To update a device’s driver in Windows Device Manager:
1. On your keyboard, press the Windows logo key and R at the same time to invoke the run box.
2. Type devmgmt.msc and click OK.

3. Select a category and expand it to see the devices in that category.


4. Right-click the device whose driver you’d like to update.
5. Select Update Driver.

153
6. Select Search automatically for updated driver software.

To reinstall a device’s driver in Windows Device Manager:


1. On your keyboard, press the Windows logo key and R at the same time to invoke the run box.
2. Type devmgmt.msc and click OK.

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.

5. Restart your PC.


6. Windows will attempt to reinstall the driver.

What Windows Device Manager DOESN’T do


Windows Device Manager doesn’t always detect outdated drivers. That’s because it categorizes
driver updates as either ‘critical’, ‘automatic’ or ‘optional’, and it doesn’t usually concern itself
with the ‘optional’ ones.
So long as you have the necessary ‘critical’ and ‘automatic’ updates, Windows is ok. It won’t, for
example, install a new ‘optional’ update, if it already has an old ‘critical’ update installed.

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.

What to do when Windows Device Manager won’t update a device driver


If you’re unable to update a device driver in Windows Device Manager, Microsoft says:
“If Windows doesn’t find a new driver, you can try looking for one on the device manufacturer’s
website and follow their instructions.”

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

1. What is the role of device drivers in I/O?


2. How do block I/O devices work?
3. Why is it necessary to partition a volume?
4. Which I/O software libraries does an operating system use?
5. How does disk defragmentation improve disk performance?
6. How is disk access time determined?

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.4 Tools, Equipment, Supplies and Materials


• Computer
• Internet
• Stationery
• Stationery
• Instruction material

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

5.1 File management is explained. Activities may be carried out in groups


5.2 File access methods are explained. or as individual
5.3 File allocation techniques are explained.
5.4 File protection and security are explained.
5.5 File and directory operations are demonstrated
5.6 Local policy settings are demonstrated

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.

Responsibilities of File Management System


The responsibilities of File Management System are as follows −
Operation
This provides user to work with or manipulate the files. Manipulation includes open, close, save,
copy, delete, move, rename, share, etc.

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.

Indexed sequential access


• This mechanism is built up on base of sequential access.
• An index is created for each file which contains pointers to various blocks.
• Index is searched sequentially and its pointer is used to access the file directly.

File/Space Allocation Techniques


Files are allocated disk spaces by operating system. Operating systems deploy following three
main ways to allocate disk space to files.
• Contiguous Allocation
• Linked Allocation
• Indexed Allocation

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.

File Protection and Security


In computer systems, a lot of user’s information is stored, the objective of the operating
system is to keep safe the data of the user from the improper access to the system.
Protection can be provided in number of ways.

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.

Controlling File Access:


The files which have direct access of the any user have the need of protection. The files
which are not accessible to other users doesn’t require any kind of 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.

Several different types of operations can be controlled:


• Read –Reading from a file.
• Write – Writing or rewriting the file.
• Execute – Loading the file and after loading the execution process starts.
• Append – Writing the new information to the already existing file, editing must be end
at the end of the existing file.
• Delete –Deleting the file which is of no use and using its space for other data.
• List – List the name and attributes of the file.

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:

i) Constructing such a list may be tedious and unrewarding task, especially if we


do not know in advance the list of the users in the system.
ii) Previously, the entry of the any directory is of the fixed size but now it changes
to the variable size which results in the complicates space management.
These problems can be resolved by use of a condensed version of the access list.
To condense the length of the access-control list, many systems recognize three
classification of users in connection with each file:
• Owner –
Owner is the user who has created the file.
• Group –
A group is a set of members who has similar needs and they are sharing the same
file.
• Universe –
In the system, all other users are under the category called universe.

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.

Other Protection Approaches:


The access to any system is also controlled by the password. If the use of password are is
random and it is changed often, this may be result in limit the effective access to a file.

The use of passwords has a few disadvantages:


• The number of passwords are very large so it is difficult to remember the large
passwords.
• If one password is used for all the files, then once it is discovered, all files are
accessible; protection is on all-or-none basis.

File and Directory Operations in Windows

How to Change File Attributes in Windows 10


File attributes are special metadata or properties of files stored in the file system which instruct
computer software to change its behavior.
162
Some of them may be enforced by operating system. For example, the read-only attribute prevents
apps from writing to such files and tells File Explorer to warn the user that the file or folder can be
important.

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.

Using the File explorer to change file attributes


1. Open File Explorer and go to the folder that contains your files.
2. Select the file whose attributes you want to change.
3. On the Home tab of the Ribbon, click on the Properties button.

Figure 51:Windows File explorer

Sharing through File Explorer in Windows 10


Use File Explorer to share files and folders with specific people, or anyone on the network. You
always have control over what you've shared, and whether other users can look at or edit your files.

Share an item on your network


1. Open File Explorer and find the item you'd like to share.
2. Right-click on the item, then click Give access to > Choose a name or click Specific people.

163
Figure 52: Windows file sharing

3. Click the drop-down to choose someone to share the item with:


• Named user: Choose another user account on this computer.
• Everyone: Share the item with any user on the network
• Create a new user: Set up a new user account on the computer to share the item with.

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.

Stop sharing an item


Go to the file or folder, right-click and choose Give access to > Remove access.

Customising Files and directories using the File Explorer


You can reconfigure certain ways that File Explorer works. All the configuration settings in
Windows 10 are in a window named Folder Options.

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:

1. Open File Explorer.


2. Click View.
The View menu appears.
3. Click Options.

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.

Configuring Local security policy settings


You must have Administrators rights on the local device, or you must have the appropriate
permissions to update a Group Policy Object (GPO) on the domain controller to perform these
procedures.

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.4. Tools, Equipment, Supplies and Materials


• Computer
• Internet
• Stationery
• Stationery
• Instruction material

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.

4.2 Performance Standard


1. Solved Linear equations
2. Performed vector operations
3. Performed matrix operations
4. Performed Boolean algebra operations
5. Performed set operations
6. Explained samples spaces, events and sets
7. Solved problems using Probability axioms
8. Solved permutations and combinations
9. Solved problems using conditional probability
10. Represented data using statistical technique
11. Illustrated measures of central tendency
12. Illustrated measures of spread
13. Illustrated measures of location

4.3 Learning Outcomes


4.3.1 List of Learning Outcomes
1. Understand Linear Algebra
2. Understand Boolean Algebra
3. Understand Set Theory

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

1.1 Linear Equations are explained Activities may be carried out in


1.2 Linear equations are solved groups or as individual
1.3 Vectors are explained
1.4 Vector operations are illustrated
1.5 Matrices are explained
1.6 Matrix operations are illustrated
1.7 Inverse of a square matrix is illustrated

4.3.2.2 Information Sheet No 4/LO1: Understand Linear Algebra

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

A linear equation is any equation that can be written in the form

where a and b are real numbers and x is a variable.

Solving linear equations


Example: y = 2x + 1 is a linear equation:

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:

Add 6 to both sides of the equation:

Divide both sides by 2:

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:

Add 30 to both sides of the equation

Divide both sides by 8:

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.

Vector Algebra Operations


Just like in usual Algebra, we also perform arithmetic operations such as addition, subtraction,
multiplication, in vectors. However, in the case of multiplication only, vectors have two
terminologies, such as dot product and cross product, which we are going to learn here.

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|

If P and Q are both orthogonal, i.e. θ = 90°, then;


• P.Q = 0 [since cos 90° = 0]

In vector algebra, if two vectors are given as;


P = [P1,P2,P3,P4,….,Pn] and Q = [Q1,Q2,Q3,Q4,….,Qn]

Then their dot product is given by;


• P.Q = P1Q1+P2Q2+P3Q3+……….PnQn

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 θ

Vector Algebra Example


Question: Find the dot product of vectors P(1, 3, -4) and Q(3,−5, 2).
Ans: As per the vector algebra definition of the dot product, we know;
P.Q = P1Q1+P2Q2+P3Q3+……….PnQn

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 a 4 × 4 identity matrix. Often a subscript is added to indicate the dimension, as

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

Matrix addition is commutative; that is, C = A + B = B + A .

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

Matrix multiplication is not commutative; that is, C = AB ≠ BA . A matrix multiplying or


multiplied by the identity I is unchanged; that is, AI = IA = A.

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

called the minor of ij , is the matrix formed


by deleting the i row and j column of matrix A .

For 2 × 2 matrix

the cofactors are

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 ,

the cofactors are

so using the first column

178
Transposition

The transpose of a matrix, denoted with superscript T , is formed by interchanging row and
column elements:

is the transpose of A where

For example,

If the matrix is complex, the complex conjugate transpose is denoted as

The matrix is Hermitian if

Inverse of square matrix

A square matrix that multiplies another square matrix to produce the identity matrix is called
the inverse, and is denoted by a superscript − 1

if A is square, and (square) matrix F satisfies F A = I, then

i) F is called the inverse of A, and is denoted


ii) The matrix A is called invertible or nonsingular

If A doesn’t have an inverse, it’s called singular or noninvertible

Example 1

Example 2 - does not have an inverse

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.

3. Solve the given system – or show that no solution exists:

4. What is transposition in linear algebra?


5. Contrast a vector and a matrix.
6. Rank of the matrix A =
0 0 0 0
4 2 3 0
1 0 0 0
4 0 3 0

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.4 Tools, Equipment, Supplies and Materials


● Calculator
● Computer
● Instruction material
● Stationery

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

2.1 Boolean algebra is explained Activities may be carried out


2.2 Basic Boolean operations are explained in groups or as individual
2.3 Secondary operations are explained
2.4 Writing of Boolean Expressions is illustrated
2.5 Methods of simplifying Boolean expressions are
illustrated
2.6 Boolean Laws and Theorems are illustrated
2.7 Simplification rules for Boolean expressions are
illustrated

Information Sheet No. 4/LO 2: Understand Boolean Algebra

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.

Basic Boolean operations


AND, OR, NOT and Secondary operations NAND, NOR, EX-OR, EX-NOR; their algebraic
functions and truth tables

Boolean operations are well expressed as logic gates.

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.

Using Karnaugh Maps


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 Karnaugh map

Boolean Laws, Theorems and Expressions


Table 12: Boolean Laws, Theorems and Expressions
Laws and Theorems Statements Expressions

AND law These laws use the AND


operation. Therefore they
are called AND laws

OR law These laws use the OR


operation. Therefore they
are called OR laws

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

Commutative law Any binary operation (a) A + B = B + A


which satisfies the (b) A B = B A
following expression is
referred to as commutative
operation

Associative law This law states that the (a) (A + B) + C = A + (B + C)


order in which the logic (b) (A B) C = A (B C)
operations are performed is
irrelevant as their effect is
the same

Distributive law This law permits the (a) A (B + C) = A B + A C


multiplying or factoring (b) A + (B C) = (A + B) (A + C)
out of an expression

De-Morgan’s Theorems There are two “de (a)


Morgan´s” rules or
theorems, (b)

(1) Two separate terms


NOR´ed together is the
same as the two terms
inverted (Complement)
and AND´ed for example:

(2) Two separate terms


NAND´ed together is the
same as the two terms
inverted (Complement)
and OR´ed for example:

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}

Hence, the simplified Boolean function will be B + AC.

The logic diagram for Boolean function B + AC can be represented as:


Sample logic diagram 2

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

1. Name and explain 5 Boolean laws


2. Explain the De-Morgan’s Theorem

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

3.1 Sets Theory is explained Activities may be carried out


3.2 Methods of Set representation are illustrated in groups or as individual
3.3 Cardinality of a set explained
3.4 Types of sets are illustrated
3.5 Venn Diagrams are illustrated
3.6 Set Operations are illustrated

4.3.4.2 Information Sheet No. 4/LO3: Understand Set Theory

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

Methods of Set representation


A set can be represented by various methods. 3 common methods used for representing set:
1. Statement form.
2. Roaster form or tabular form method.
3. Set Builder method.

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 }.

Set builder form


In Set-builder set is described by a property that its member must satisfy.
1. {x : x is even number divisible by 6 and less than 100}.
2. {x : x is natural number less than 10}.

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)

For example; Let A = {1, 2, 3, 4, 5, 6} and B = {2, 4, 6, 8}.


What is the cardinality of B? A ⋃ B, A ⋂ B?

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.

Null set/ empty set


A null set or an empty set is a valid set with no member.
A = { } / phie cardinality of A is 0.
Popular representation either empty curly braces { } or a special symbol phie. This A is a set which
has null set inside it.

Venn Diagrams and Set Operations


To visualize the interaction of sets, John Venn in 1880 thought to use overlapping circles, building
on a similar idea used by Leonhard Euler in the eighteenth century. These illustrations are called
Venn Diagrams.

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

Figure 55: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.

Intersection of two sets

Figure 56:Intersection of two sets

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

Figure 57:Complement of a set

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}.

For example; the Cartesian product of A = {1,2} and B = {p, q, r} is


A × B ={(1, p), (1, q), (1, r), (2, p), (2, q), (2, r) };

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.4 Tools, Equipment, Supplies and Materials


● Internet
● Calculator
● Computer
● Instruction material
● Stationery

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

4.3.5.2 Information Sheet No. 4/LO4: Understand Calculus

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

This is a line in the slope intercept form y=mx+b

Graph 1: Demonstrating y = mx+c

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,

Graph 2: f(x) = |x|


Example 3

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:

As a graph it looks like this:

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)

y intercept: set x=0; y = 02 − 4; y = −4


The point is (0,-4)

And here is the graph of x2 - 4 to confirm what we found:


202
Differential calculus

Derivatives (Differential Calculus): The Derivative is the "rate of change" or slope of a function.

Slope = Change in Y / Change in X

To find the derivative of a function y = f(x) we use the slope formula


Slope = Change in Y / Change in X = Δy / Δx

And (from the diagram above) we see that:


x changes from x to x+Δx
y changes from f(x) to f(x+Δx)

Now follow these steps:


Fill in this slope formula: ΔyΔx = f(x+Δx) − f(x)Δx

203
Simplify it as best we can, then make Δx shrink towards zero. Like this:

We write dx instead of "Δx heads towards 0".

And "the derivative of" is commonly written :

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

Common functions and rules of Derivatives


Table 13: Commo derivative functions

Table 14: Common Derivative Rules

205
First and second order differential equations

A first order differential equation is of the form:

Second order differential equations are in the form, ay″+by′+cy=0


(Homogeneous Linear Equations with constant coefficients)

The characteristic equation is:

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)

Example: What is an integral of 2x?


We know that the derivative of x2 is 2x
... so an integral of 2x is x2

Notation

where C is the constant of integration.

Definite and Indefinite


A Definite Integral has actual values to calculate between (they are put at the bottom and top of the
"S"):

207
Graph 4: Indefinite integral

Graph 5: Definite integral


Techniques of integration
The techniques/rules of integration are as summarized on the table below:

Table 15: The techniques/rules of integration

Rules Function Integral

Multiplication by constant ∫cf(x) dx c∫f(x) dx

Power Rule (n≠-1) ∫xn dx (xn+1 /n+1) + C

Sum Rule ∫(f + g) dx ∫f dx + ∫g dx

Difference Rule ∫(f - g) dx ∫f dx - ∫g dx

Integration by Parts Integration by Parts is a special method of integration that is


often useful when two functions are multiplied together, but is
also helpful in other ways;
∫u v dx = u∫v dx −∫u' (∫v dx) dx
where u is the function u(x); v is the function v(x) and u' is the
derivative of the function u(x)

Substitution Rule "Integration by Substitution" (also called "u-Substitution" or


"The Reverse Chain Rule") is a method to find an integral, but
only when it can be set up in a special way

Note that we have g(x) and its derivative g'(x)


Conclusion:
208
At the end of this learning outcome, the learner should be able to explain functions and graphis and
illustrate differential and integral calculus.

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

2. What is the derivative of sin(x)?

4.3.5.4 Tools, Equipment, Supplies and Materials


● Internet
● Calculator
● Computer
● Instruction material
● Stationery
4.3.5.5 References
1. https://www.mathsisfun.com/calculus/derivatives-introduction.html
2. http://www.sosmath.com/tables/diffeq/diffeq.html

210
4.3.6 Learning outcome 5: Understand Probability and Statistics
4.3.6.1 Learning Activities

Learning Outcome 5: Understand Probability and Statistics


Learning Activities Special Instructions

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

4.3.6.2 Information Sheet No.4/LO5: Understand Probability and Statistics


Introduction:
This learning outcome covers explaining key terminologies in probability and statistics, illustrating
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.

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

In summary, if A1 and A2 are disjoint events,


then

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 and B)=P(A,B),

• 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

You roll a fair die. What is the probability of E={1,5}?

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.

Permutations and combinations

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

A permutation is an ordered Combination, classified into Permutations with Repetition and


Permutations without Repetition

Conditional probability and multiplication rule

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)

The Multiplication Rule


In probability theory, the Multiplication Rule states that the probability that A and B occur is equal
to the probability that A occurs times the conditional probability that B occurs, given that we know
A has already occurred.

This rule can be written:


P(A∩B)=P(B)⋅P(A|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.

Data representation techniques (Data graphs)


A Bar Graph (also called Bar Chart) is a graphical display of data using bars of different
heights.

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

A Dot Plot is a graphical display of data using dots

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:

Histogram: a graphical display of data using bars of different heights

Measures of central tendency

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

Percentile: the value below which a percentage of data falls.


Example: You are the fourth tallest person in a group of 20
80% of people are shorter than you:

That means you are at the 80th percentile.


If your height is 1.85m then "1.85m" is the 80th percentile height in that group

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.4 Tools, Equipment, Supplies and Materials


● Calculator
● Computer
● Instruction material
● Stationery
● Internet

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.

5.2 Performance Standard


1. Installed Java
2. Demonstrated understanding of Java environment
3. Created a program to perform data operations
4. Created a program using control statements
5. Created a program using methods
6. Demonstrated classes and objects
7. Demonstrated inheritance

5.3 Learning Outcomes


5.3.1 List of Learning Outcomes
1. Understand Programming Concepts
2. Understand the Java environment
3. Perform Data Operations
4. Use Control Structures
5. Use Methods
6. Understand 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

Learning Activities Activities may be carried out in


groups or as individual
1.1 Programming is defined
1.2 Phases of program development are explained
1.3 Key terms used in programming are explained
1.4 The types of code are explained
1.5 Different translators are used in programming
are explained
1.6 OOP fundamental concepts are explained

5.3.2.2 Information Sheet No 5/LO1: Understand 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++.

Phases of program development


1. Establish program requirements
All possible requirements of the system to be developed are captured in this phase and
documented in a requirement specification document.

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.

4. Code test and debug


223
All the units developed in the implementation phase are integrated into a system after testing of
each unit. Post integration the entire system is tested for any faults and failures. 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.

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.

Key terms used in programming


Algorithm
An algorithm is a procedure or step-by-step instruction for solving a problem. They form the
foundation of writing a program.

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.

Translators used in programming


Compiler
A compiler is a special program that processes statements written in a particular programming
language and turns them into machine language or “code” that a computer’s processor uses

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.

OOP fundamental concepts


It is a programming concept that works on the principle that objects are the most important part of
your program. It allows users to create the objects that they want and then create methods to
handle those objects. Manipulating these objects to get results is the goal of Object Oriented
Programming.

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

What is Computer Programming? Basics to Learn Coding. Retrieved from


https://www.guru99.com/computer-programming-tutorial.html

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

Learning Outcome No. 2: Understand The Special Instructions


Java Environment

Learning Activities Activities may be carried out in groups or as


individual
2.1 Java is installed
2.2 Java programming environment is
demonstrated
2.3 Features of Java are explained
2.4 Java syntax is demonstrated

5.3.3.2 Information Sheet No 5/LO2: Understand the Java Environment

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.

Following are steps to install Java in Windows


Step 1) Download Java for Windows and Install JDK, Go to link. Click on Download JDK.
Select the java 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

Set the Environment variables


2. The PATH variable gives the location of executables like javac, java etc. It is possible to run a
program without specifying the PATH but you will need to give full path of executable like
C:\Program Files\Java\jdk-13.0.1\bin\javac A.java instead of simple javac A.java
3. The CLASSPATH variable gives location of the Library Files.

Let's look into the steps to set the PATH and CLASSPATH
Step 1) Right Click on the My Computer and Select the properties

Step 2) Click on advanced system settings

229
Step 3) Click on Environment Variables

Step 4) Click on new Button of User variables

Step 5) Type PATH in the Variable name.

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

Step 8) You can follow a similar process to set CLASSPATH.

Step 9) Click on OK button


Step 10) Go to command prompt and type javac commands.
If you see a screen like below, Java is installed.
231
Java Programming environment
1. Download the Eclipse Installer
Download Eclipse Installer from http://www.eclipse.org/downloads. Eclipse is hosted on many
mirrors around the world. Please select the one closest to you and start to download the Installer

2. Start the Eclipse Installer executable


For Windows users, after the Eclipse Installer executable has finished downloading it should be
available in your download directory.

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.

3. Select the package to install


• The new Eclipse Installer shows the packages available to Eclipse users. You can search for
the package you want to install or scroll through the list.

232
• Select and click on the package you want to install.

4. Select your installation folder


• Specify the folder where you want Eclipse to be installed. The default folder will be in your
User directory.
• Select the ‘Install’ button to begin the installation.

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: public void myMethodName()


• Program file name
Name of the program file should exactly match the class name.
When saving the file, you should save it using the class name (Remember Java is case
sensitive) and append '.java' to the end of the name (if the file name and the class name do
not match, your program will not compile).
Note that in case you do not have a public class present in the file then file name can be different
than class name. It is also not mandatory to have a public class in the file.

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.

Most common syntax of main() method:


class GeeksforGeeks {
public static void main(String[]
args)
{
System.out.println("I am a
Geek");
}
}
I am a Geek
Explanation:
Every word in the public static void main statement has got a meaning to the JVM.
· Public: It is an Access modifier, which specifies from where and who can access the method.

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;
}
}

In the above java code, we have 5 identifiers namely :


● Test : class name.
237
● main : method name.
● String : predefined class name.
● args : variable name.
● a : variable name.

Rules for defining Java Identifiers


There are certain rules for defining a valid java identifier. These rules must be followed, otherwise
we get compile-time error. These rules are also valid for other languages like C,C++.
● The only allowed characters for identifiers are all alphanumeric characters([A-Z],[a-z],[0-
9]), ‘$‘(dollar sign) and ‘_‘ (underscore).For example “geek@” is not a valid java identifier
as it contain ‘@’ special character.
● Identifiers should not start with digits([0-9]). For example “123geeks” is a not a valid java
identifier.
● Java identifiers are case-sensitive.
● There is no limit on the length of the identifier but it is advisable to use an optimum length
of 4 – 15 letters only.
● Reserved words can’t be used as an identifier. For example “int while = 20;” is an invalid
statement as while is a reserved word. There are 53 reserved words in Java.

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 {
// ...
}

private boolean myFlag;


static final double weeks = 9.5;
protected static final int BOXWIDTH = 42;
public static void main(String[] arguments) {
// body of method
}
Access Control Modifiers
Java provides a number of access modifiers to set access levels for classes, variables, methods and
constructors. The four access levels are −
● Visible to the package, the default. No modifiers are needed.
● Visible to the class only (private).
● Visible to the world (public).
● Visible to the package and all subclasses (protected).

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

1. Learn Programming – Java Basics. Retrieved from


https://www.tutorialspoint.com/java/index.htm

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

5. What is the extension of java code files?


a) .class
b) .java
c) .txt
d) .js

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.4 Tools, Equipment, Supplies and Materials


• Computer
• JDK
• Stationery
• Instruction material
• Internet

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

Learning Activities Activities may be carried out in groups


or as individual

3.1 Java data types are explained


3.2 Types of statements are explained
3.3 Variables and constants are explained
3.4 Data operations are demonstrated
3.5 Program to perform specified operations is created

5.3.4.2 Information Sheet No 5/LO3: Perform Data Operations

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.

Java Data Types


Variables are nothing but reserved memory locations to store values. This means that when you
create a variable you reserve some space in the memory.

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.

There are two data types available in Java


● Primitive Data Types
● Reference/Object Data Types

Primitive Data Types


Integer
• int data type is a 32-bit signed two's complement integer.
• Minimum value is - 2,147,483,648 (-2^31)
• Maximum value is 2,147,483,647(inclusive) (2^31 -1)
• Integer is generally used as the default data type for integral values unless there is a concern
about memory.

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

Reference Data types


• Reference variables are created using defined constructors of the classes. They are used to
access objects. These variables are declared to be of a specific type that cannot be changed.
For example, Employee, Puppy, etc.
• Class objects and various type of array variables come under reference datatype.
• Default value of any reference variable is null.
• A reference variable can be used to refer any object of the declared type or any compatible
type.
• Example: Animal animal = new Animal("giraffe");

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;

The statement above declares a variable tax which is initialized to 9.5.


Also, there are control flow statements that are used in decision making and looping in Java. You
will learn about control flow statements in later chapters.

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.

Variables and Constants


• A variable provides us with named storage that our programs can manipulate.
• Each variable in Java has a specific type, which determines the size and layout of the
variable's memory; the range of values that can be stored within that memory; and the
set of operations that can be applied to the variable.

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
}

public static void main(String args[]) {


Test test = new Test();
test.pupAge();
}
}
This will produce the following result −

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;
}

// The salary variable is assigned a value.


public void setSalary(double empSal) {
salary = empSal;
245
}
// This method prints the employee details.
public void printEmp() {
System.out.println("name : " + name );
System.out.println("salary :" + salary);
}
public static void main(String args[]) {
Employee empOne = new Employee("Ransika");
empOne.setSalary(1000);
empOne.printEmp();
}
}
This will produce the following result −

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

Single Character Constants


● A Character is Single Alphabet a single digit or a Single Symbol that is enclosed within
Single inverted commas.
● ‘S’ ,’1’ etc are Single Character Constant.

246
String Constants
● String is a Sequence of Characters Enclosed between double Quotes These Characters may
be digits , Alphabets Like “Hello” , “1234” etc.

Java Data operations


Variable Assignment
Assigning a value to a variable in Java follows this pattern:
variableName = value ;

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.

Table 16: Java Arithmetic Operators

Operator Use Description Example


+ x+y Adds x and y float num = 23.4 + 1.6; //
num=25
- x–y Subtracts y from x long n = 12.456 – 2.456; //n=10
-x Arithmetically negates x int i = 10; -i; // i = -10
* x*y Multiplies x by y int m = 10*2; // m=20
/ x/y Divides x by y float div = 20/100 ; // div = 0.2
% x%y Computes the remainder of dividing x int rm = 20/3; // rm = 2
by y
Object Instantiation
In object-oriented programming, an object is an instance of a class. Think of the common
example that is the Employee class; any new employee object used in the program is considered
an instance of that class. Therefore, the fancy term for creating a new instance of that class is
instantiation

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[])
{

Scanner s= new Scanner(System.in);

System.out.println("Enter the radius:");


double r= s.nextDouble();
double area=(22*r*r)/7 ;
System.out.println("Area of Circle is: " + area);
}
}

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…..)

Some of those method are:


● nextDouble() ,
● nextFloat(),
● nextInt(),
● nextLong()
Step – 6:
double area=(22*r*r)/7 ;
Step – 7: System.out.println(“Area of Circle is: ” + area); ( Once, you entered the radius , the
value stored in a particular function ( nextDouble(); ) and read those values with the help of a
scanner and display the output for a given value.

Example 2: Calculate compound interest


Compound Interest Formula is P (1 + R/n) (nt) - P

● Here P is principal amount.


● R is the annual interest rate.
249
● t is the time the money is invested or borrowed for.
● n is the number of times that interest is compounded per unit t, for example if interest is
compounded monthly and t is in years then the value of n would be 12. If interest is
compounded quarterly and t is in years then the value of n would be 4.

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.

Let’s put these values in the formula.


● Compound Interest = 2000 (1 + 0.08 / 12) (12 * 5) – 2000 = $979.69
● So, the compound interest after 5 years is $979.69
.
Java Program to calculate Compound Interest
In this java program we are calculating the compound interest, we are taking the same example that
we have seen above for the calculation.

public class JavaExample {


public void calculate(int p, int t, double r, int n) {
double amount = p * Math.pow(1 + (r / n), n * t);
double cinterest = amount - p;
System.out.println("Compound Interest after " + t + " years: "+cinterest);
System.out.println("Amount after " + t + " years: "+amount);
}
public static void main(String args[]) {
JavaExample obj = new JavaExample();
obj.calculate(2000, 5, .08, 12);
}
}
Output:
Compound Interest after 5 years: 979.6914166032102
Amount after 5 years: 2979.69141660321

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

3. Which of the following is the smallest integer data type?


a) bytecode
b) int
c) short
d) long
4. Integer data type does not include following primitive data type.
e) byte
f) short
g) double
h) long
5. What is the size of integer in java programming?
i) 2 byte
j) 3 byte
k) 8 byte
l) 4 byte
Oral Assessment
1. What is an expression statement?
2. What is the difference between class variables and local variables?
3. What are the common java data types?

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

1. Java Training. Retrieved from https://www.javatpoint.com/java-tutorial

252
5.3.5 Learning outcome 4: Use Control Statements
5.3.5.1 Learning Activities

Learning Outcome No. 4: Use Control Special Instructions


Statements

Learning Activities Activities may be carried out in groups or as


individual

4.1 Control Structures are explained


4.2 Uses of different control statements are
demonstrated
4.3 Programs using control statements are
created

5.3.5.2 Information Sheet No 5/LO4: Use Control Statements

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.

Java Control Statements


The JAVA control statements inside a program are usually executed sequentially. Sometimes a
programmer wants to break the normal flow and jump to another statement or execute a set of
statements repeatedly.

The statements which breaks the normal sequential flow of the program are called control
statements.

Control statements enable decision making, looping and branching.

Decision making statements


These statements decides the flow of the execution based on some conditions.
● If then
● If then else
● switch
Looping statements
Statements inside a loop are executed repeatedly provided with some condition which terminates
the loop.
● for
253
● while
● do while

Branching statements
Branching statements are used to jump from the current executing loop.
● break
● continue

Uses of different control statements in Java


Decision making statements
2. If then
The statements under the ‘if’ block are executed only when the condition evaluates to true.
if (condition)
{
//statements
}
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”);
}

}
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.

The default case is considered when no case value is matched.

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.

There are two types of break statements


● Labelled break
● Unlabeled break
Unlabeled break is the one explained above.

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

Schildt, H(2019 ) . Java A Beginner’s Guide (8th ed.). McGrawHill


Education

5.3.5.3 Self Assessment

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

Learning Activities Activities may be carried out in groups or as


individual
1.1 Procedures/Functions/Methods are explained
1.2 Methods are demonstrated
1.3 Programs using methods are created

5.3.6.2 Information Sheet No 5/LO5: Use Methods

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 Definition Example:


Below is a method called minFunction(). This method takes two parameters num1 and num2 and
returns the maximum between the two –

public static int minFunction(int n1, int n2) {


int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}

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.

Methods returning void is considered as a call to a statement. For example:


System.out.println("This is Me!");

The method returning value can be understood by the example:


int result = sum(6, 9);

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);
}

/* returns the minimum of two numbers */


public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
}

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.

Call to a void method must be a statement i.e. methodRankPoints(255.7);. It is a Java statement


which ends with a semicolon as shown in the following example.

Program Example:
public class ExampleVoid {
public static void main(String[] args) {
methodRankPoints(255.7);
}

public static void methodRankPoints(double points) {


if (points >= 202.5) {
System.out.println("Rank:A1");
}else if (points >= 122.4) {
System.out.println("Rank:A2");
}else {
System.out.println("Rank:A3");
}
}
}
Output:
Rank:A1

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.

public class swappingExample {

public static void main(String[] args) {


int a = 30;
int b = 45;
System.out.println("Before swapping, a = " + a + " and b = " + b);

// Invoke the swap method


swapFunction(a, b);
System.out.println("\n**Now, Before and After swapping values will be same here**:");
System.out.println("After swapping, a = " + a + " and b is " + b);
}
public static void swapFunction(int a, int b) {
System.out.println("Before swapping(Inside), a = " + a + " b = " + b);
// Swap n1 with n2
int c = a;
a = b;
b = c;
System.out.println("After swapping(Inside), a = " + a + " b = " + b);
}
}
Output:
Before swapping, a = 30 and b = 45
Before swapping(Inside), a = 30 b = 45
After swapping(Inside), a = 45 b = 30
**Now, Before and After swapping values will be same here**:
After swapping, a = 30 and b is 45

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.

The following example explains the same:


Example:
public class ExampleOverloading {
public static void main(String[] args) {
int a = 11;
int b = 6;
double c = 7.3;
double d = 9.4;
int result1 = minFunction(a, b);

// same function name with different parameters


double result2 = minFunction(c, d);
System.out.println("Minimum Value = " + result1);
System.out.println("Minimum Value = " + result2);
}

// 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

public class This_Example {


// Instance variable num
int num = 10;
This_Example() {
System.out.println("This is an example program on keyword this");
}
This_Example(int num) {
// Invoking the default constructor
this();
// Assigning the local variable num to the instance variable num
this.num = num;
}
public void greet() {
System.out.println("Hi Welcome to Java tutorial");
}
public void print() {
// Local variable num
int num = 20;
// Printing the local variable
System.out.println("value of local variable num is : "+num);
// Printing the instance variable
System.out.println("value of instance variable num is : "+this.num);
// Invoking the greet method of a class
this.greet();

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

Schildt, H(2019 ) . Java A Beginner’s Guide (8th ed.). McGrawHill Education

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

1. Java – Methods. Retrieved from https://www.tutorialspoint.com/java


2. Methods in Java. Retrieved from https://www.javatpoint.com

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

Learning Activities Activities may be carried out in groups or as


individual
6.1 Object oriented programming is explained
6.2 Classes and objects are explained
6.3 Classes and objects are demonstrated.
6.4 Inheritance is demonstrated
6.5 Inheritance programs are developed

5.3.7.2 Information Sheet No 5/LO6: Understand Object 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.

What is Object Oriented Programming (OOP)?


• Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-
Oriented Programming is a methodology or paradigm to design a program using classes and
objects.
• The popular object-oriented languages are Java, C#, PHP, Python, C++, etc.
• OOP simplifies software development and maintenance by providing some concepts:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation

Object oriented programming concepts


Class
Collection of objects is called class. It is a logical entity.
A class can also be defined as a blueprint from which you can create an individual object. Class
doesn't consume any space

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.

Class attributes are variables within a class.

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.

There are three steps when creating an object from a class −


• Declaration − A variable declaration with a variable name with an object type.
• Instantiation − The 'new' keyword is used to create the object.
• Initialization − The 'new' keyword is followed by a call to a constructor. This call initializes
the new object.

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.

//First define the class


class Box{
double width;
double height;
double depth;
274
public void Findvolume(){
System.out.println("Volume is " + width*height*depth);
}
}

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);
}

public void Subtraction(int x, int y) {


z = x - y;
System.out.println("The difference between the given numbers:"+z);
}
}

public class My_Calculation extends Calculation {


public void multiplication(int x, int y) {
z = x * y;
System.out.println("The product of the given numbers:"+z);
}

public static void main(String args[]) {


int a = 20, b = 10;
My_Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);
demo.multiplication(a, b);
}
}
Compile and execute the above code as shown below.
javac My_Calculation.java
java My_Calculation

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!");
}
}

class Car extends Vehicle {


private String modelName = "Mustang"; // Car attribute
public static void main(String[] args) {
// Create a myCar object
Car myCar = new Car();
// Call the honk() method (from the Vehicle class) on the myCar object
myCar.honk();
// Display the value of the brand attribute (from the Vehicle class) and the value of the
modelName from the Car class
System.out.println(myCar.brand + " " + myCar.modelName);
}
}
Conclusion
At the end of this learning outcome, the trainee should be able to explain object oriented
programming, classes and objects, demonstrate classes, objects and inheritance and develop
inheritance programs.

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.

5.3.7.4 Tools, Equipment, Supplies and Materials


• Computer
• JDK
• Stationery
• Instruction material
• Internet
5.3.7.5 References

1. Java – Object Oriented – Retrieved from https://www.tutorialspoint.com/java


2. Objects and class. Retrieved from https://www.javatpoint.com/object-and-class-in-java

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.

6.2 Performance Standard


1. Installed MS SQL server
2. Created an entity relationship model
3. Normalized database tables
4. Validated an ER model
5. Created and queried a database from a validated ER model.
6. Retrieved data from several tables using joins
7. Prescribed a database type based on user requirements.
8. Demonstrated Object Oriented Concepts
9. Demonstrated designing of views and triggers in object oriented databases.
10. Implemented Indexing and hashing

6.3 Learning Outcomes


6.3.1 List of Learning Outcomes
1. Understand database fundamentals
2. Design a data base
3. Use Structured Query Language
4. Design of object oriented database
5. Understand indexing and hashing
6. Understand 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

1.1 A database is defined Activities may be carried out in


1.2 Terminologies used with databases are explained groups or as individual
1.3 Reasons of using databases are explained
1.4 Relational Model is defined
1.5 Key concepts in relational modelling are explained
1.6 Properties of a table/relation are explained
1.7 Relational Database Management Systems (RDBMSs)
products are compared
1.8 Installation of MS SQL server is demonstrated
1.9 MS SQL server interface is explained
1.10 Properties of MS SQL server database are explained

6.3.2.2 Information Sheet No 6:LO1: Understand database fundaments


Introduction

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

Figure 59: MSAccess Database Sample

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.

Figure 60:: MSAccess Table Sample

✓ 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.

Figure 61: : MSAccess Table Records Sample

✓ 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.

Figure 62:: MSAccess Table Fields Sample.

Reasons of using databases


The various reasons a database is important are:
Manages large amounts of data
A database stores and manages a large amount of data on a daily basis. This would not be
possible using any other tool such as a spreadsheet as they would simply not work.

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.

Easy to update data


In a database, it is easy to update data using various Data Manipulation languages (DML)
available. One of these languages is SQL.

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.

Easy to research data


It is very easy to access and research data in a database. This is done using Data Query
Languages (DQL) which allow searching of any data in the database and performing
computations on it.

Control of data redundancy


In the database approach, ideally, each data item is stored in only one place in the database.
In some cases, data redundancy still exists to improve system performance, but such

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.

Backup and recovery facilities


Backup and recovery are methods that allow you to protect your data from loss. The
database system provides a separate process, from that of a network backup, for backing up
and recovering data. If a hard drive fails and the database stored on the hard drive is not
accessible, the only way to recover the database is from a backup.

Support for multiple views of data


A database supports multiple views of data. A view is a subset of the database, which is
defined and dedicated for particular users of the system. Multiple users in the system might
have different views of the system. Each view might contain only the data of interest to a
user or group of users.

Insulation between program and data


In the file-based system, the structure of the data files is defined in the application programs
so if a user wants to change the structure of a file, all the programs that access that file might
need to be changed as well. On the other hand, in the database approach, the data structure is
stored in the system catalogue and not in the programs. Therefore, one change is all that is
needed to change the structure of a file. This insulation between the programs and data is
also called program-data independence.

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.
.

Relational Modeling Concepts

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

In the above-given example, employee ID is a primary key because it uniquely identifies an


employee record. In this table, no other employee can have the same employee ID.
✓ Foreign Key
A FOREIGN KEY is a key used to link two tables together.
A FOREIGN KEY is a field (or collection of fields) in one table that refers to the PRIMARY KEY
in another table. The table containing the foreign key is called the child table, and the table
containing the candidate key is called the referenced or parent table.
Look at the following two tables:

"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

Relational tables have six properties:


Values Are Atomic
This property implies that columns in a relational table are not repeating group or arrays. Such
tables are referred to as being in the "first normal form" (1NF). The atomic value property of
relational tables is important because it is one of the cornerstones of the relational model.
The key benefit of the one value property is that it simplifies data manipulation logic.

Column Values Are of the Same Kind


In relational terms this means that all values in a column come from the same domain. A domain
is a set of values which a column may have. For example, a Monthly_Salary column contains only
specific monthly salaries. It never contains other information such as comments, status flags, or
even weekly salary.
This property simplifies data access because developers and users can be certain of the type of data
contained in a given column. It also simplifies data validation. Because all values are from the same
domain, the domain can be defined and enforced with the Data Definition Language (DDL) of the
database software.

Each Row is Unique


This property ensures that no two rows in a relational table are identical; there is at least one
column, or set of columns, the values of which uniquely identify each row in the table. Such
columns are called primary keys.
This property guarantees that every row in a relational table is meaningful and that a specific row
can be identified by specifying the primary key value.

e Sequence of Columns is Insignificant


This property states that the ordering of the columns in the relational table has no meaning.
Columns can be retrieved in any order and in various sequences. The benefit of this property is that
it enables many users to share the same table without concern of how the table is organized. It also
permits the physical structure of the database to change without affecting the relational tables.

The Sequence of Rows is Insignificant


This property is analogous the one above but applies to rows instead of columns. The main benefit
is that the rows of a relational table can be retrieved in different order and sequences. Adding
information to a relational table is simplified and does not affect existing queries.

Each Column Has a Unique Name


Because the sequence of columns is insignificant, columns must be referenced by name and not by
position. In general, a column name need not be unique within an entire database but only within
the table to which it belongs.

Comparison of RDBMS products

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)

Installation of MS SQL server


Beginning with SQL Server 2016 (13.x), SQL Server is only available as a 64-bit application. Here
are important details about how to get SQL Server and how to install it.

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

Install SQL Server 2017 Developer Edition


To install SQL Server, you need to download it from the Microsoft.com website via the following
link: https://www.microsoft.com/en-us/sql-server/sql-server-2017
Once the download completes, you double-click the file SQLServer2017-SSEI-Dev.exe to launch
the installer.

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.

15. Verify the SQL Server 2017 features to be installed:

294
16. The installer starts the installation process

295
17. Once it completes, the following window displays. Click the OK button.

18. Click the Close button to complete the installation

Congratulation! you have successfully installed SQL Server Developer Edition.

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

Second, double-click the installation file SSMS-Setup-ENU.exe to starting installing. The


installation process of SMSS is straightforward which you just need to follow the screen sequence.

1. Click the Install button

2. Wait for few minutes while the installer sets up the software.

3. Once setup is completed, click the Close button

297
Now, you should have a SQL Server 2017 and SQL Server Management Studio installed on your
computer.

MS SQL server interface


Normally, when you install Microsoft SQL Server, you also install the SQL Server Management
Studio (SSMS), which is the primary tool for managing the server and its databases using a graphical
interface.

Figure 63:: MSSQL Server Interface

• 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:

o Here's a Horizontal Tab Group:

o Here's a Vertical Tab Group:

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.

Change basic settings


This section describes how to modify some basic settings in SSMS from the Tools menu.

• To modify the highlighted toolbar, select Tools > Customize:

304
Change the font
• To change the font, select Tools > Options > Fonts and Colors:

Change startup options


• Startup options determine what your workspace looks like when you first open SSMS. To
change startup options, select Tools > Options > Startup:

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

Properties of MS SQL server Database


The following a properties apply to a SQL server database. From the object explorer, right click on
an existing database to see the properties as follows:
✓ Deleting a database
✓ Deleting data or log files
306
✓ Increasing database size
✓ Shrinking database
✓ Renaming database
✓ Importing a database
✓ Exporting a database

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

1 A relational database consists of a collection of


a) Tables
b) Fields
c) Records
d) Keys
2 A ________ in a table represents a relationship among a set of values.
a) Column
b) Key
c) Row
d) Entry
3 The term _______ is used to refer to a row.
a) Attribute
b) Tuple
c) Field
d) Instance

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

1. Explain 5 applications of databases in your real life


2. Explain 5 properties of a relational database

Practical Assesssment

1. In groups of two install MS SQL server on your personal Laptop


2. Document the steps of installing MS SQL Server as you install.

6.3.2.4 Tools, Equipment, Supplies and Materials


• Microsoft Office with MS Visio Modelling tool
• MS SQL server software
• Computers
• Instruction material
• Stationery
• Internet

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

Learning Activities Special Instructions

Activities may be carried out in groups


2.1 Phases of database design are explained or as individual
2.2 Entity modelling is illustrated
2.3 Entity model is designed using UML notation
2.4 Validation of the ERM model is done according to the ·
requirements

·
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.

Phases of database Design


There are three phases of database design, namely conceptual, logical, and physical database design.

Figure 64: Database Data Modelling

a) Conceptual database design (ERM Modeling)

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

Figure 65: Demonstrating Conceptual Data Model

Characteristics of a conceptual data model


• Offers Organisation-wide coverage of the business concepts.
• This type of Data Models are designed and developed for a business audience.
• The conceptual model is developed independently of hardware specifications like data
storage capacity, location or software specifications like DBMS vendor and technology. The
focus is to represent data as a user will see it in the "real world."
Conceptual data models known as Domain models create a common vocabulary for all stakeholders
by establishing basic concepts and scope.

Steps of Conceptual database Design


Conceptual database design steps are:
• Build a conceptual data model
• Recognize entity types
• Recognize the relationship types
• Identify and connect attributes with entity or relationship types
• Determine attribute domains
• Determine candidate, primary, and alternate key attributes

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

Building a Conceptual Database Model


The first step in conceptual database design is to build one (or more) conceptual data replica of the
data requirements of the enterprise. A conceptual data model comprises these following elements:
• entity types
• types of relationship
• attributes and the various attribute domains
• primary keys and alternate keys
• integrity constraints
The conceptual data model is maintained by documentation, including ER diagrams and a data
dictionary, which is produced throughout the development of the model.

b) Logical database design


Logical database design is the process of constructing a model of the data used in an enterprise based
on a specific data model, but independent of a particular DBMS and other physical considerations.

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.

Figure 66:Logical data Modelling

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.

Characteristics of a Logical data model


• Describes data needs for a single project but could integrate with other logical data models
based on the scope of the project.
• Designed and developed independently from the DBMS.
• Data attributes will have data types with exact precisions and length.
• Normalization processes to the model is applied typically till 3NF

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.

c) Physical database design

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.

Figure 67:Physical Data Modelling

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.

Steps of the physical database design


The steps of the physical database design methodology are as follows:
• Transform the logical data model for target DBMS
o Design base relations
o Design representation of derived data
o Design general constraints
313
• Design file organizations and indexes
o Analyze transactions
o Choose file organizations
o Choose indexes
o Estimate disk space requirements
o Design user views
o Design security mechanisms
o Consider the introduction of controlled redundancy
o Monitor and tune the operational system
Entity Modelling Concepts

ER modeling helps you to analyze data requirements systematically to produce a well-designed


database. So, it is considered a best practice to complete ER modeling before implementing your
database.
a) Entities
A real-world thing either living or non-living that is easily recognizable and non-recognizable. It is
anything in the enterprise that is to be represented in our database. It may be a physical thing or
simply a fact about the enterprise or an event that happens in the real world.
An entity can be place, person, object, event or a concept, which stores data in the database. The
characteristics of entities are must have an attribute, and a unique key. Every entity is made up of
some 'attributes' which represent that entity.
Examples of entities:
• Person: Employee, Student, Patient
• Place: Store, Building
• Object: Machine, product, and Car
• Event: Sale, Registration, Renewal
• Concept: Account, Course
Entity set:
An entity set is a group of similar kind of entities. It may contain entities with attribute sharing
similar values. Entities are represented by their properties, which also called attributes. All
attributes have their separate values. For example, a student entity may have a name, age, class, as
attributes.

Figure 68:Demonstrating an Entity

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

It is a single-valued property of either an entity-type or a relationship-type.


For example, a lecture might have attributes: time, date, duration, place, etc.

An attribute is represented by an Ellipse

Attributes

Types of Attributes Description


Simple attribute Simple attributes can't be divided any further.
For example, a student's contact number. It is
also called an atomic value.
Composite attribute It is possible to break down composite
attribute. For example, a student's full name
may be further divided into first name, second
name, and last name.
Derived attribute This type of attribute does not include in the
physical database. However, their values are
derived from other attributes present in the
database. For example, age should not be
stored directly. Instead, it should be derived
from the DOB of that employee.
315
Multivalued attribute Multivalued attributes can have more than one
values. For example, a student can have more
than one mobile number, email address, etc.

c) Relationships
Relationship is nothing but an association among two or more entities. E.g., Tom works in the
Chemistry department.

Figure 69:Entity Relationships

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)

An Entity Relationship Diagram (ERD) is a visual representation of different entities within a


system and how they relate to each other. For example, the elements writer, novel, and a
consumer may be described using ER diagrams the following way:

Figure 70:ER diagram with basic objects

ER Diagram Symbols and Notations


A number of symbols and notations are used for ER Modelling as shown below

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

Figure 72:Binary relationship

Ternary relationship called Registers

Figure 73:Ternary relationship

Quaternary relationship called Arranges


318
Figure 74:Quaternary relationship

Recursive relationship called Supervises with role names

Figure 75:Recursive relationship

Entities associated through two distinct relationships with role names

319
Figure 76:Entities associated through two distinct relationships with role names

ER diagram of Staff and Branch entities and their attributes

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.

Reasons for Database Normalization


There are three main reasons to normalize a database. The first is to minimize duplicate data, the
second is to minimize or avoid data modification issues, and the third is to simplify queries.
Normalization fixes anomalies and Data redundancy especially those occasioned by data updates.
There are three modification anomalies that can occur:
a) Insert Anomaly
There are facts we cannot record until we know information for the entire row. In our example we
cannot record a new sales office until we also know the sales person.
Why? Because in order to create the record, we need provide a primary key. In our case this is the
EmployeeID. Table Update Anomaly

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.

Database Normalization Example


We will study normalization with the help of a case study. Assume, a video library maintains a
database of movies rented out. Without any normalization, all information is stored in one table as
shown below.

Here you see Movies Rented column has multiple values. Now let's move into 1st Normal Forms:

1NF (First Normal Form) Rules

321
• Each table cell should contain a single value.
• Each record needs to be unique.
The above table in 1NF-
1NF Example

Table A: In 1NF Form

Before we proceed let's understand a few things --


What is a KEY?
A KEY is a value used to identify a record in a table uniquely. A KEY could be a single column or
combination of multiple columns
Note: Columns in a table that are NOT used to identify a record uniquely are called non-key
columns.
What is a Primary Key?

A primary is a single column value used to identify a database record


uniquely.
It has following attributes
• A primary key cannot be NULL
• A primary key value must be unique
• The primary key values should rarely be changed
• The primary key must be given a value when a new record is
inserted.

What is Composite Key?


A composite key is a primary key composed of multiple columns used to identify a record uniquely
In our database, we have two people with the same name Robert Phil, but they live in different
places.

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.

Decomposition of out 1NF table to table 1

Normalized table members -Table 2

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

Introducing foreign Key in members table

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

Why do you need a foreign key?


Suppose, a novice inserts a record in Table B such as
You will only be able to insert values into your foreign key that exist in the unique key in the parent
table. This helps in referential integrity.

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.

Let's move into 3NF


3NF (Third Normal Form) Rules
• Rule 1- Be in 2NF
• Rule 2- Has no transitive functional dependencies
To move our 2NF table into 3NF, we again need to again divide our table.
3NF Example
Table staff in 3 NF-Table 1

Table Members Normalized-Table 2

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.

Crud Matrix alternative way

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

1. _____________ can help us detect poor E-R design.


a) Database Design Process
b) E-R Design Process
327
c) Relational scheme
d) Functional dependencies

2. In the __________ normal form, a composite attribute is converted to individual attributes.


a) First
b) Second
c) Third
d) Fourth

3. Tables in second normal form (2NF):


a) Eliminate all hidden dependencies
b) Eliminate the possibility of a insertion anomalies
c) Have a composite key
d) Have all non-key fields depend on the whole primary key
4. Which is a bottom-up approach to database design that design by examining the relationship
between attributes:
a) Functional dependency
b) Database modeling
c) Normalization
d) Decomposition
5. An ________ is a set of entities of the same type that share the same properties, or
attributes.
a) Entity set
b) Attribute set
c) Relation set
d) Entity model

6. Entity is a _________
a) Object of relation
b) Present working model
c) Thing in real world
d) Model of relation

7. Which of the following can be a multivalued attribute?


a) Phone_number
b) Name
c) Date_of_birth
d) All of the mentioned

8. The Rectangles divided into two parts represents


a) Entity set
b) Relationship set
c) Attributes of a relationship set

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

Learning Activities Special Instructions

Activities may be carried out in groups


3.1 Structured Query Language (SQL) is explained or as individual
3.2 Data definition queries are explained
3.3 Creation of tables using the SQL CREATE TABLE
statement is demonstrated ·
3.4 CREATE TABLE statement constraints are
demonstrated
3.5 The table schema is edited using the SQL ALTER
statement
3.6 A table is dropped using the SQL DROP TABLE
statement
3.7 Data manipulation query statements are
demonstrated.
3.8 SQL joins are explained
3.9 Database is created and queried from validated ER
model
3.10 Types of joins are demonstrated

6.3.4.2 Information Sheet No 6/LO3: Use Structured Query Language (SQL)

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.

Structured Query Language (SQL)


Structured query language is a standard language in programming specifically for relational
databases. It is designed mainly for management of data i.e. insertion, update and retrieval into and
from relational databases. It can also be seen as a standard interface through which access and
manipulation of data in relational databases is done.

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.

SQL code is generally divided into the following categories:


• Data Querying – done using the common and familiar statement SELECT. The SELECT
statement has additional helpful clauses to aid further its operation – FROM, WHERE,
ORDER BY, GROUP BY, LIMIT.
• Data Manipulation – this consist of at least three statements INSERT, UPDATE AND
DELETE used to add, edit/update and delete data respectively.
• Data Definition – used for table management and table structures including indexing.
This includes such statements as CREATE, ALTER, DROP.
• Data Control – majorly for database control and management, i.e. assign and revoke
database rights and permissions to respective users. Its statements include GRANT,
REVOKE.

Data definition queries


Data Definition Queries as stated above are mainly for management of relations/tables – creation,
update and deletion. The statements here as explained below:
CREATE – this query is for creating tables and table structure.
ALTER – used to update/alter/change a table and/or table structure.
DROP – this is for total removal of a table and its structure inclusive of existing data.

Creation of tables using the SQL CREATE TABLE statement


Using CREATE statement is a basic way of naming a table and defining its structure. The create
statement has a table name and its columns with respective data types. The below is a sample
statement.

CREATE TABLE table_name(


column1 datatype,
column2 datatype,
column3 datatype,
column4 datatype,

PRIMARY KEY( column1,.. )
);

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.

CREATE TABLE statement constraints

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
);

The common constraints used as below:

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.

Examples: Tables with constraints


CREATE TABLE department
(
dept_code integer PRIMARY KEY,
dept_name varchar(10) not null,
);

CREATE TABLE employee


( id integer PRIMARY KEY,
name varchar(20) NOT NULL,
nationality varchar(30) DEFAULT "KENYA”,
age integer NOT NULL,
gender char(1) CHECK (gender in ('M','F')),
salary float,
location char(10) UNIQUE,
dept_code integer FOREIGN KEY REFERENCES department(dept_code)
);

Data Querying USING the SELECT statement

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.

Syntax of SQL SELECT Statement:


SELECT column_list FROM table-name
[WHERE Clause]
[GROUP BY clause]
[HAVING clause]
[ORDER BY clause];
• table-name is the name of the table from which the information is retrieved.
• column_list includes one or more columns from which data is retrieved.
• The code within the brackets is optional.
database table student_details;
id first_name last_name age subject games
100 Rahul Sharma 10 Science Cricket
101 Anjali Bhagwat 12 Maths Football
102 Stephen Fleming 09 Science Cricket
103 Shekar Gowda 18 Maths Badminton
104 Priya Chandra 15 Economics Chess
NOTE: These database tables are used here for better explanation of SQL commands. In reality, the
tables can have different columns and different data.

For example, consider the table student_details. To select the first name of all the students the query
would be like:

SELECT first_name FROM student_details;


NOTE: The commands are not case sensitive. The above SELECT statement can also be written as
"select first_name from students_details;"

• You can also retrieve data from more than one column. For example, to select first name
and last name of all the students.

SELECT first_name, last_name FROM student_details;


You can also use clauses like WHERE, GROUP BY, HAVING, ORDER BY with SELECT
statement. (Discussed later)

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.

How to use expressions in SQL SELECT Statement


• Expressions combine many arithmetic operators, they can be used in SELECT, WHERE and
ORDER BY Clauses of the SQL SELECT Statement.
• The operators are evaluated in a specific order of precedence, when more than one
arithmetic operator is used in an expression. The order of evaluation is: parentheses,
division, multiplication, addition, and subtraction. The evaluation is performed from the left
to the right of the expression.

For example: If we want to display the first and last name of an employee combined
together, the SQL Select Statement would be like

SELECT first_name || ' ' || last_name FROM employee;


Output:
Rahul Sharma
Anjali Bhagwat
Stephen Fleming
Shekar Gowda
Priya Chandra

You can also provide aliases as below.


SELECT first_name || ' ' || last_name AS emp_name FROM employee;

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.

Aliases for columns:

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

SELECT first_name Name FROM student_details;


In the above query, the column first_name is given a alias as 'name'. So when the result is displayed
the column name appears as 'Name' instead of 'first_name'.

Output:
Name
Rahul Sharma
Anjali
Bhagwat
Stephen
Fleming
Shekar Gowda
Priya Chandra

Aliases for tables:


SELECT s.first_name FROM student_details s;

In the above query, alias 's' is defined for the table student_details and the column first_name is
selected from the table.

Aliases is more useful when


• There are more than one tables involved in a query,
• Functions are used in the query,
• The column names are big or not readable,
• More than one columns are combined together

SQL WHERE Clause


The WHERE Clause is used when you want to retrieve specific information from a table excluding
other irrelevant data.

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.

Syntax of SQL WHERE Clause:


WHERE {column or expression} comparison-operator value

335
Syntax for a WHERE clause with Select statement is:

SELECT column_list FROM table-name


WHERE condition;
• column or expression - Is the column of a table or a expression
• comparison-operator - operators like = < > etc.
• value - Any user value or a column name for comparison

For Example: To find the name of a student with id 100, the query would be like:

SELECT first_name, last_name FROM student_details


WHERE id = 100;

• Comparison Operators and Logical Operators are used in WHERE Clause (Discussed later)

How to use expressions in the WHERE Clause


• Expressions can also be used in the WHERE clause of the SELECT statement.
For example: Lets consider the employee table.
database table "employee";

id name dept age salary location


100 Ramesh Electrical 24 25000 Bangalore
101 Hrithik Electronics 28 35000 Bangalore
102 Harsha Aeronautics 28 35000 Mysore
103 Soumya Electronics 22 20000 Bangalore
104 Priya InfoTech 25 30000 Mangalore

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

SELECT name, salary, salary*1.2 AS new_salary FROM employee


WHERE salary*1.2 > 30000;

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.

The below table describes each comparison operator.


Comparison
Description
Operators
= equal to
<>, != is not equal to
< less than
> greater than
greater than or equal
>=
to
<= less than or equal to

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.

"OR" Logical Operator:


If you want to select rows that satisfy at least one of the given conditions, you can use the logical
operator, OR.

For example: if you want to find the names of students who are studying either Maths or Science,
the query would be like,

SELECT first_name, last_name, subject


FROM student_details
WHERE subject = 'Maths' OR subject = 'Science'

The output would be something like,


first_name last_name subject
Anajali Bhagwat Maths
Shekar Gowda Maths
Rahul Sharma Science
Stephen Fleming Science
The following table describes how logical "OR" operator selects a row.
Column1 Column2 Row
Satisfied? Satisfied? Selected
YES YES YES
YES NO YES
NO YES YES
NO NO NO

"AND" Logical Operator:


If you want to select rows that must satisfy all the given conditions, you can use the logical
operator, AND.

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 output would be something like,


338
first_name last_name Age
Rahul Sharma 10
Anajali Bhagwat 12
Shekar Gowda 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

"NOT" Logical Operator:

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:

SELECT first_name, last_name, games


FROM student_details
WHERE NOT games = 'Football'

The output would be something like,


first_name last_name Games
Rahul Sharma Cricket
Stephen Fleming Cricket
Shekar Gowda Badminton
Priya Chandra Chess

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

SELECT first_name, last_name, age, games


FROM student_details
WHERE age >= 10 AND age <= 15
OR NOT games = 'Football'

The output would be something like,


first_name last_name age games
Rahul Sharma 10 Cricket
Priya Chandra 15 Chess

In this case, the filter works as follows:


Condition 1: All the students you do not play football are selected.
Condition 2: All the students whose are aged between 10 and 15 are selected.
Condition 3: Finally the result is, the rows which satisfy at least one of the above conditions is
returned.

NOTE:The order in which you phrase the condition is important, if the order changes you are likely
to get a different result.

SQL Comparison Keywords


There are other comparison keywords available in sql which are used to enhance the search
capabilities of a sql query. They are "IN", "BETWEEN...AND", "IS NULL", "LIKE".

Table 17: SQL comparison keywords

Comparision Operators Description


LIKE column value is similar to specified character(s).
column value is equal to any one of a specified set of
IN
values.

340
column value is between two values, including the end
BETWEEN...AND
values specified in the range.
IS NULL column value does not exist.

SQL LIKE Operator


The LIKE operator is used to list all rows in a table whose column values match a specified pattern.
It is useful when you want to search rows to match a specific pattern, or when you do not know the
entire value. For this purpose we use a wildcard character '%'.

For example: To select all the students whose name begins with 'S'

SELECT first_name, last_name


FROM student_details
WHERE first_name LIKE 'S%';

The output would be similar to:


first_name last_name
Stephen Fleming
Shekar Gowda

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,

SELECT first_name, last_name


FROM student_details
WHERE first_name LIKE '_a%';

The output would be similar to:


first_name last_name
Rahul Sharma

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 BETWEEN ... AND Operator


341
The operator BETWEEN and AND, are used to compare data for a range of values.
For Example: to find the names of the students between age 10 to 15 years, the query would be
like,
SELECT first_name, last_name, age
FROM student_details
WHERE age BETWEEN 10 AND 15;

The output would be similar to:


first_name last_name age
Rahul Sharma 10
Anajali Bhagwat 12
Shekar Gowda 15

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,

SELECT first_name, last_name, subject


FROM student_details
WHERE subject IN ('Maths', 'Science');

The output would be similar to:


first_name last_name subject
Anajali Bhagwat Maths
Shekar Gowda Maths
Rahul Sharma Science
Stephen Fleming Science

You can include more subjects in the list like ('maths','science','history')


NOTE:The data used to compare is case sensitive.

SQL IS NULL Operator


A column value is NULL if it does not exist. The IS NULL operator is used to display all the rows
for columns that do not have a value.

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.

Syntax for using SQL ORDER BY clause to sort data is:


SELECT column-list
FROM table_name [WHERE condition]
[ORDER BY column1 [, column2, .. columnN] [DESC]];
database table "employee";

id name dept age salary location


100 Ramesh Electrical 24 25000 Bangalore
101 Hrithik Electronics 28 35000 Bangalore
102 Harsha Aeronautics 28 35000 Mysore
103 Soumya Electronics 22 20000 Bangalore
104 Priya InfoTech 25 30000 Mangalore

For Example: If you want to sort the employee table by salary of the employee, the sql query
would be.

SELECT name, salary FROM employee ORDER BY salary;

The output would be like


name Salary
Soumya 20000
Ramesh 25000
Priya 30000
Hrithik 35000
Harsha 35000

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;

The output would be like:


name salary
Soumya 20000
Ramesh 25000
Priya 30000
Harsha 35000
Hrithik 35000

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.

The above query can also be written as given below,


SELECT name, salary FROM employee ORDER BY 1, 2;

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.

SELECT name, salary


FROM employee
ORDER BY name, salary DESC;

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.

SELECT name, salary


FROM employee
ORDER BY name DESC, salary DESC;

How to use expressions in the ORDER BY Clause


For example: If you want to display employee name, current salary, and a 20% increase in the
salary for only those employees for whom the percentage increase in salary is greater than 30000
and in descending order of the increased price, the SELECT statement can be written as shown
below
344
SELECT name, salary, salary*1.2 AS new_salary
FROM employee
WHERE salary*1.2 > 30000
ORDER BY new_salary DESC;

The output for the above query is as follows.


name salary new_salary
Hrithik 35000 42000
Harsha 35000 42000
Priya 30000 36000

NOTE: Aliases defined in the SELECT Statement can be used in ORDER BY Clause.

SQL GROUP Functions


Group functions are built-in SQL functions that operate on groups of rows and return one value for
the entire group. These functions are: COUNT, MAX, MIN, AVG, SUM, DISTINCT

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;

The output would be '5' rows.

SQL DISTINCT(): This function is used to select the distinct rows.

For Example: If you want to select all distinct department names from employee table, the query
would be:

SELECT DISTINCT dept FROM employee;

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:

SELECT MAX (salary) FROM employee;

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:

SELECT MIN (salary) FROM employee;

SQL AVG(): This function is used to get the average value of a numeric column.
To get the average salary, the query would be

SELECT AVG (salary) FROM employee;

SQL SUM(): This function is used to get the sum of a numeric column
To get the total salary given out to the employees,

SELECT SUM (salary) FROM employee;

SQL GROUP BY Clause


The SQL GROUP BY Clause is used along with the group functions to retrieve data grouped
according to one or more columns.

For Example: If you want to know the total amount of salary spent on each department, the query
would be:

SELECT dept, SUM (salary)


FROM employee
GROUP BY dept;

The output would be like:

dept salary
Electrical 25000
Electronics 55000
Aeronautics 35000
InfoTech 30000

SQL HAVING Clause

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;

SELECT dept, SUM (salary)


FROM employee
GROUP BY dept
HAVING SUM (salary) > 25000

The output would be like:


dept Salary
Electronics 55000
Aeronautics 35000
InfoTech 30000

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.

Edit table schema using SQL ALTER statement


The ALTER statement in SQL is used to create, update or delete table columns and their respective
data types and constraints.

Syntax to add a column


ALTER TABLE table_name ADD column_name datatype;

For Example: To add a column "experience" to the employee table, the query would be like

ALTER TABLE employee ADD experience integer;

Syntax to drop a column


ALTER TABLE table_name DROP column_name;

For Example: To drop the column "location" from the employee table, the query
would be like

347
ALTER TABLE employee DROP location;

Syntax to modify a column


ALTER TABLE table_name MODIFY column_name datatype;

For Example: To modify the column salary in the employee table, the query would be like

ALTER TABLE employee MODIFY salary FLOAT(15,2);

SQL DROP command


The SQL DROP command is used to remove an object from the database. If you drop a table, all
the rows in the table is deleted and the table structure is removed from the database. Once a table is
dropped we cannot get it back, so be careful while using DROP command. When a table is dropped
all the references to the table will not be valid.

Syntax to drop a sql table structure:

DROP TABLE table_name;

For Example: To drop the table employee, the query would be like
DROP TABLE employee;

Data Manipulation using SQL


The INSERT statement

The INSERT Statement is used to add new rows of data to a table.

We can insert data to a table in two ways,

1) Inserting the data directly to a table.


Syntax for SQL INSERT is:

INSERT INTO TABLE_NAME


[ (col1, col2, col3,...colN)]
VALUES (value1, value2, value3,...valueN);
• col1, col2,...colN -- the names of the columns in the table into which you want to insert
data.

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.

The sql insert query will be as follows .

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,

INSERT INTO employee (id, name, dept, age, salary)


VALUES (105, 'Srinath', 'Aeronautics', 27, 33000);

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,

INSERT INTO employee


VALUES (105, 'Srinath', 'Aeronautics', 27, 33000);

Inserting data to a table through a select statement.


Syntax for SQL INSERT is:

INSERT INTO table_name


[(column1, column2, ... columnN)]
SELECT column1, column2, ...columnN
FROM table_name [WHERE condition];

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,

INSERT INTO employee


SELECT * FROM temp_employee;

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.

The UPDATE statement


The UPDATE Statement is used to modify the existing rows in a table.
The Syntax for SQL UPDATE Command is:

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);

The SQL DELETE statement


The DELETE Statement is used to delete rows from a table.

The Syntax of a SQL DELETE statement is:

DELETE FROM table_name [WHERE condition];


• table_name -- the table name which has to be updated.

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,

DELETE FROM employee WHERE id = 100;

To delete all the rows from the employee table, the query would be like,

DELETE FROM employee;

The SQL TRUNCATE statement


The SQL TRUNCATE command is used to delete all the rows from the table and free the space
containing the table.
Syntax to TRUNCATE a table:
TRUNCATE TABLE table_name;

For Example: To delete all the rows from employee table, the query would be like,
TRUNCATE TABLE employee;

Difference between DELETE and TRUNCATE Statements:

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.

The Syntax for joining two tables is:

SELECT col1, col2, col3...


FROM table_name1, table_name2
WHERE table_name1.col2 = table_name2.col1;

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

database table "order_items";


order_id product_id total_units customer
5100 104 30 Infosys
5101 102 5 Satyam
5102 103 25 Wipro
5103 101 10 TCS

SQL Joins can be classified into Equi join and Non Equi join.

1) SQL Equi joins


It is a simple SQL join condition which uses the equal sign as the comparison operator. Two types
of equi joins are SQL Outer join and SQL Inner join.

For example: You can get the information about a customer who purchased a product and the
quantity of product.

2) SQL Non equi joins


It is a SQL join condition which makes use of some comparison operator other than the equal sign
. For example >, <, >=, <=

SQL Equi Joins:


An equi-join is further classified into two categories:
a) SQL Inner Join
b) SQL Outer Join
a) SQL Inner Join:
All the rows returned by the SQL query satisfy the SQL join condition specified.

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 query for this type of sql joins would be like,

SELECT order_id, product_name, unit_price, supplier_name, total_units


FROM product, order_items
WHERE order_items.product_id = product.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,

SELECT o.order_id, p.product_name, p.unit_price, p.supplier_name, o.total_units


FROM product p, order_items o
WHERE o.product_id = p.product_id;

b) SQL Outer Join:


This SQL join condition returns all rows from both tables which satisfy the join condition along
with rows which do not satisfy the join condition from one of the tables. The SQL outer join
operator in Oracle is ( + ) and is used on one side of the join condition only.

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:

SELECT p.product_id, p.product_name, o.order_id, o.total_units


FROM order_items o, product p
WHERE o.product_id (+) = p.product_id;

The output would be like,

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.

Phases of Database Development


• Establish and specify the organisation requirements
• Design the conceptual database – ER model
• Design the logical database – Specify table schemas, normalize data tables
• Implement the database - Create the physical design; Create tables, insert data and create
required queries, create indexes, views, security systems, etc.
• Test the database
• Review and maintain the database – Make changes as necessary

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.

6.3.4.3 Self Assessment


Written Assessment
1. Which are data manipulation commands in SQL?
2. How does the ORDER by clause worn in SQL?
3. What is the difference between the DELETE and TRUNCATE commands?
4. Which are the uses of the asterisk (*) in various SQL commands?
5. ------------ command is used erase a table.
a. DELETE
b. ALTER
c. ALIAS
d. DROP

6. Which command is used to extract data from a database table?

354
a. Get
b. Select
cc Pop
d.Extract

7. Which operator allows you to specify multiple values in WHERE clause?


a. In
b. Range
c. Like
d. Between

9. Which key word is used with update command to change the value?
a. Alter
b. Set
c Change
d. Add

10. Which key word is used with alter-command to delete a column?


a. Remove
b. Change
c. Drop
d. delete.

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.4 Tools, Equipment, Supplies and Materials


• MS SQL server software
• Computers
• Instruction material
• Stationery
• Internet

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

Learning Activities Special Instructions

Activities may be carried out in groups


4.1 An object oriented database is explained or as individual
4.2 Object oriented database concepts are explained.
4.3 Object Oriented database concepts are implemented
from a set of requirements. ·
4.4 Creating of views and triggers in object oriented
databases is demonstrated.

·
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.

Comparison with other RDBMS


BASIS RDBMS OODBMS

Connection Between Two A Primary key distinctively An object identifier (OID) is


Relations identifies an object in a table. a name for any type of object
or entity.

Way of storing data Stores data in Entities, Stores data as Objects.


defined as tables hold
specific information.

357
Data Handling Handles comparatively Handles larger and complex
simpler data. data than RDBMS.

Object oriented database concepts

Object-A real-world entity which has a unique identity

Class-A collection of objects with the same or similar attributes and behavior.

Attributes-The characteristics used to describe objects, also called instance variables.

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

Implementation of Object Oriented Database (OOD) Concepts


Below is a demonstration of OOD concepts using PL/SQL – Oracle Programming Language for
SQL.

Objects are created using the CREATE [OR REPLACE] TYPE statement. Following is an example
to create a simple address object consisting of few attributes –

CREATE OR REPLACE TYPE address AS OBJECT


(house_no varchar2(10),
street varchar2(30),
city varchar2(20),
state varchar2(10),
pincode varchar2(10)
);
/
When the above code is executed at the SQL prompt, it produces the following result –

Type created.

Let's create one more object customer where we will wrap attributes and methods together to
have object-oriented feeling –

CREATE OR REPLACE TYPE customer AS OBJECT


(code number(5),
name varchar2(30),
358
contact_no varchar2(12),
addr address,
member procedure display
);
/
When the above code is executed at the SQL prompt, it produces the following result –
Type created.

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 −

House No: 103A


Street: M.G.Road
City: Jaipur
State: Rajasthan
Pincode: 201301

PL/SQL procedure successfully completed.

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 –

residence := address('103A', 'M.G.Road', 'Jaipur', 'Rajasthan','201301');

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.

Map method Demonstrated


Let us try to understand the above concepts using the following rectangle object −
CREATE OR REPLACE TYPE rectangle AS OBJECT
(length number,
width number,
member function enlarge( inc number) return rectangle,
member procedure display,
map member function measure return number
);
/
When the above code is executed at the SQL prompt, it produces the following result :
Type created.

Creating the type body

CREATE OR REPLACE TYPE BODY rectangle AS


MEMBER FUNCTION enlarge(inc number) return rectangle IS
BEGIN
return rectangle(self.length + inc, self.width + inc);
END enlarge;
MEMBER PROCEDURE display IS
BEGIN
dbms_output.put_line('Length: '|| length);
dbms_output.put_line('Width: '|| width);
END display;
MAP MEMBER FUNCTION measure return number IS
BEGIN
return (sqrt(length*length + width*width));
END measure;
END;
360
/
When the above code is executed at the SQL prompt, it produces the following result:
Type body created.

Now using the rectangle object and its member functions −


DECLARE
r1 rectangle;
r2 rectangle;
r3 rectangle;
inc_factor number := 5;
BEGIN
r1 := rectangle(3, 4);
r2 := rectangle(5, 7);
r3 := r1.enlarge(inc_factor);
r3.display;
IF (r1 > r2) THEN -- calling measure function
r1.display;
ELSE
r2.display;
END IF;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Length: 8
Width: 9
Length: 5
Width: 7

PL/SQL procedure successfully completed.

Inheritance for PL/SQL Objects


PL/SQL allows creating object from the existing base objects. To implement inheritance, the base
objects should be declared as NOT FINAL. The default is FINAL.
The following programs illustrate the inheritance in PL/SQL Objects. Let us create another object
named TableTop, this is inherited from the Rectangle object. For this, we need to create the
base rectangle object –

CREATE OR REPLACE TYPE rectangle AS OBJECT


(length number,
width number,
member function enlarge( inc number) return rectangle,
NOT FINAL member procedure display) NOT FINAL
361
/

When the above code is executed at the SQL prompt, it produces the following result −
Type created.

Creating the base type body


CREATE OR REPLACE TYPE BODY rectangle AS
MEMBER FUNCTION enlarge(inc number) return rectangle IS
BEGIN
return rectangle(self.length + inc, self.width + inc);
END enlarge;
MEMBER PROCEDURE display IS
BEGIN
dbms_output.put_line('Length: '|| length);
dbms_output.put_line('Width: '|| width);
END display;
END;
/
When the above code is executed at the SQL prompt, it produces the following result –
Type body created.

Creating the child object tabletop −


CREATE OR REPLACE TYPE tabletop UNDER rectangle
(
material varchar2(20),
OVERRIDING member procedure display
)
/
When the above code is executed at the SQL prompt, it produces the following result −
Type created.

Creating the type body for the child object tabletop


CREATE OR REPLACE TYPE BODY tabletop AS
OVERRIDING MEMBER PROCEDURE display IS
BEGIN
dbms_output.put_line('Length: '|| length);
dbms_output.put_line('Width: '|| width);
dbms_output.put_line('Material: '|| material);
END display;
/
When the above code is executed at the SQL prompt, it produces the following result –
362
Type body created.

Using the tabletop object and its member functions −


DECLARE
t1 tabletop;
t2 tabletop;
BEGIN
t1:= tabletop(20, 10, 'Wood');
t2 := tabletop(50, 30, 'Steel');
t1.display;
t2.display;
END;
/
When the above code is executed at the SQL prompt, it produces the following result –

Length: 20
Width: 10
Material: Wood
Length: 50
Width: 30
Material: Steel

PL/SQL procedure successfully completed.

Creation of views and triggers.


Views-A virtual table used for hiding unwanted information.
Syntax

create or replace
view view_name
as
select column_name1, column_name2,...
from table_name
where condition;

For example

CREATE VIEW Details View AS


SELECT NAME, ADDRESS
FROM Student Details
WHERE STU_ID < 4;

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

Triggers are used to:


● Automatically generate derived column values
● Prevent invalid transactions
● Enforce complex security authorizations
● Enforce complex business rules
● Provide transparent event logging

Syntax

➢ create trigger [trigger_name]: Creates or replaces an existing trigger with the


trigger_name.
➢ [before | after]: This specifies when the trigger will be executed.
➢ {insert | update | delete}: This specifies the DML operation.
➢ on [table_name]: This specifies the name of the table associated with the trigger.
➢ [for each row]: This specifies a row-level trigger, i.e., the trigger will be executed for
each row being affected.
➢ [trigger_body]: This provides the operation to be performed as trigger is fired

SQL Server CREATE TRIGGER example

“Virtual” tables for triggers: INSERTED and DELETED


SQL Server provides two virtual tables that are available specifically for triggers
called INSERTED and DELETED tables. SQL Server uses these tables to capture the data of the
modified row before and after the event occurs.

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.

Create a table for logging the changes


The following statement creates a table named production.product_audits to record information
when an INSERT or DELETE event occurs against the production.products table:

CREATE TABLE production.product_audits(


change_id INT IDENTITY PRIMARY KEY,
product_id INT NOT NULL,
product_name VARCHAR(255) NOT NULL,
brand_id INT NOT NULL,
category_id INT NOT NULL,
model_year SMALLINT NOT NULL,
list_price DEC(10,2) NOT NULL,
updated_at DATETIME NOT NULL,
operation CHAR(3) NOT NULL,
CHECK(operation = 'INS' or operation='DEL')
);
The production.product_audits table has all the columns from the production.products table. In
addition, it has a few more columns to record the changes e.g., updated_at, operation, and
the change_id.

Creating an after DML trigger


First, to create a new trigger, you specify the name of the trigger and schema to which the trigger
belongs in the CREATE TRIGGER clause:

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

The body of the trigger begins with the AS keyword:


AS
BEGIN

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;

The following put all parts together:

CREATE TRIGGER production.trg_product_audit


ON production.products
AFTER INSERT, DELETE
AS
BEGIN
SET NOCOUNT ON;
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 i

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:

Testing the trigger


The following statement inserts a new row into the production.products table:

INSERT INTO production.products(


product_name,
brand_id,
category_id,
model_year,
list_price

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.

Let’s examine the contents of the production.product_audits table:

SELECT
*
FROM
production.product_audits;
Here is the output:

The following statement deletes a row from the production.products table:


DELETE FROM
production.products
WHERE
product_id = 322;
As expected, the trigger was fired and inserted the deleted row into
the production.product_audits table:

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.

Employee (EmployeeNumber, FirstName, LastName, Age)

6.3.5.4 Tools. Equipment, Supplies and Materials


• MS SQL server software
• Computers
• Instruction material
• Stationery
6.3.5.5 Reference.
https://www.tutorialspoint.com/plsql/plsql_object_oriented.htm

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

Learning Activities Special Instructions

Activities may be carried out in groups or as


5.1 Indexing and hashing are explained. individual
5.2 Indexing in databases is demonstrated.
5.3 Hashing in databases is demonstrated.
5.4 Indexing and hashing is implemented in an ·
existing database

·
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.

There are two types of primary indexing;


● Dense indexing-For every search key value in the data file, there is an index
record which contains the search key and a reference to the first data record
with that search key value.
● Sparse index-The index record appears only for a few items in the data file. Each
item points to a block. To locate a record, we find the index record with the
largest search key value less than or equal to the search key value we are looking
for.
We start at that record pointed to by the index record, and proceed along with
pointers in the file (sequentially) until we find the desired record.

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).

When should indexes be avoided?


Although indexes are intended to enhance a database's performance, there are times when they
should be avoided.
The following guidelines indicate when the use of an index should be reconsidered.
• Indexes should not be used on small tables.
• Tables that have frequent, large batch updates or insert operations.
• Indexes should not be used on columns that contain a high number of NULL values.
• Columns that are frequently manipulated should not be indexed

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.

Data bucket-The memory locations where the records are stored.


372
Hash Function-It that maps all the set of search keys to actual record address. It can be a single
mathematical function

Hash Index-An address of the data block.

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.

Figure 78:Hashing in a database

SQL CREATE INDEX Statement


The CREATE INDEX statement is used to create indexes in tables. Indexes are used to retrieve data
from the database more quickly than otherwise. The users cannot see the indexes, they are just used
to speed up searches/queries.

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.

CREATE INDEX Syntax


Creates an index on a table. Duplicate values are allowed:
CREATE INDEX index_name
ON table_name (column1, column2, ...);

373
CREATE UNIQUE INDEX Syntax

Creates a unique index on a table. Duplicate values are not allowed:


CREATE UNIQUE INDEX index_name
ON table_name (column1, column2, ...);
Note: The syntax for creating indexes varies among different databases. Therefore: Check the
syntax for creating indexes in your database.

CREATE INDEX Example


The SQL statement below creates an index named "idx_lastname" on the "LastName" column in the
"Persons" table:
CREATE INDEX idx_lastname
ON Persons (LastName);
If you want to create an index on a combination of columns, you can list the column names within
the parentheses, separated by commas:

CREATE INDEX idx_pname


ON Persons (LastName, FirstName);

DROP INDEX Statement


The DROP INDEX statement is used to delete an index in a table.
DROP INDEX table_name.index_name;

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.

Employee (EmployeeNumber, FirstName, LastName, Age)

6.3.6.4 Tools. Equipment, Supplies and Materials


• MS SQL server software
• Computers
• Instruction material
• Stationery

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

Learning Activities Special Instructions

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.

Decision support system


DSS is an interactive computer-based system to help decision makers use communications
technologies, data, documents, knowledge and/or models to identify and solve problems, complete
decision process tasks, and make decisions e.g. Geographic Information Systems(GI.S)

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

Distributed database systems


This is a collection of logically related databases that are physically distributed across sites in a
computer network.A distributed database management system(DDMS) is a software that manages
the DDB and provides an access mechanism that makes this distribution transparent to the users.

Illustration of a Distributed Database

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.

Each branch maintains (among others) a relation account where

Account schema is follows: (account_number, branch-name, balance)

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).

Of course there are other relations maintained at the various sites.

Types of Distributed Databases


1. Homogeneous systems-is a network of two or more databases with the same type of
operating system, DBMS software and the data structures at all sites.
2. Heterogeneous Systems-is a network of two or more databases with different types of
DBMS software and schema at different sites

Features of distributed database systems


1. It’s a collection of logically related shared data
2. Data is split into a number of fragments or partitions.
3. Fragments may be duplicated
4. Fragments/Duplicates are allocated to different sites-Data available at site A might be
available at site B
5. The sites are linked by a communications network.
6. The data at each site is controlled by the local DBMS.

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.

Figure 79: Horizontal database fragmentation

Vertical Fragmentation
- Splits the table by assigning each column to one or more fragments.

Figure 80:Vertical database fragmentation

A hybrid (Mixed fragmentation) of horizontal and vertical fragmentation is also possible

Figure 81:Hybrid database fragmentation

Example

Horizontal fragmentation of PROJ table


• PROJ1: projects with budgets less than 200, 000
• PROJ2: projects with budgets greater than or equal to 200, 000

380
Vertical fragmentation of PROJ table
• PROJ1: information about project budgets
• PROJ2: information about project names and locations

HOMOGENEOUS DDBMS versus HETEROGENEOUS DDBMS


DDBMS might be implemented as homogeneous or heterogeneous DDBMS

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.

Reasons for building distributed databases


- Sharing Data
• Users at one site may be able to access the data residing at other sites.
• For example in a distributed banking system, where each branch stores data relevant
t that branch, it is possible for a user in one branch to access the data in another
branch.

- 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.

Applications of Distributed Databases


- Manufacturing, especially multi-plant manufacturing
- Military command and control
- Airlines
- Hotel chains
- Banking
- Any organization which has a decentralized organization structure

Advantages of distributed databases

(i) Higher reliability


o Replication of components
o No single points of failure
e.g., a broken communication link or processing element does not bring down the entire
system
o Distributed transaction processing guarantees the consistency of the database and
concurrency

(ii) Improved performance


o Proximity of data to its points of use
– Reduces remote access delays
382
– Requires some support for fragmentation and replication

o Parallelism in execution

(iii ) Easier system expansion


o Database upgrade is easier

(iv) Transparency of distributed and replicated data

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.

Challenges of Distributed Databases


• Complexity – A distributed DBMS is more complex to build than a centralized DBMS.
• Cost – Procurement and maintenance costs for a Distributed DBMS are higher than those for a
centralized DBMS. Furthermore, a distributed DBMS requires additional hardware to establish a
network between sites.
• Security – In a centralized system, access to the data can be easily controlled. However, in a distributed
DBMS not only does access to replicated data have to be controlled in multiple locations, but the
network itself has to be made secure.
• Integrity control more difficult because of the large amount of data required to define constraints.
• Distribution of control: Distribution creates problems of synchronization and coordination.
• Distributed database design: Various alternatives of achieving distribution (replication or
fragmentation must be weighed).
7. At each site has its own right, i.e. it can handle local applications independently.
8. Each DBMS in a distributed system participates in at least one global application

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.

Spatial Databases/Geographical database-A database used to store geographical information e.g.


Raster data such as satellite imagery represented in matrix form or vector data represented as
discrete points, lines and polygons and support efficient storage, indexing and querying of spatial
data.
383
Application of spatial databases
● Geographic Information Systems (GIS) to store geospatial information.
● Computer-Aided Design/Manufacturing to store spatial objects such as surface of airplane
fuselage
● Multimedia Databases where the images, video, text, etc. stored and retrieved by content

Multimedia databases - A database that stores data in the form of text, images, videos, audio
animations.

Features of Multimedia Databases


1. Media data – Refers to the actual data representing an object.
2. Media format data – Information such as sampling rate, resolution, encoding scheme
etc. about the format of the media data after it goes through the acquisition, processing
and encoding phase.
3. Media keyword data – Keywords description relating to the generation of data. It is
also known as content descriptive data. Example: date, time and place of recording.
4. Media feature data – Content dependent data such as the distribution of colors, kinds
of texture and different shapes present in data
Mobile and personal databases
A mobile database is a database that is transportable, portable, and can be physically separated or
detached from the main database server but has the capability to communicate with those servers
from remote sites allowing the sharing of various kinds of data.

Design and implementation of data warehouses.


Steps towards implementing a data warehouse.
1. Requirements analysis and capacity planning: It involves defining enterprise needs,
defining architectures, carrying out capacity planning, and selecting the hardware and
software tools.
2. Hardware integration: Once the hardware and software has been selected, they require to
be put by integrating the servers, the storage methods, and the user software tools.
3. Modelling -It involves designing the warehouse schema and views.
4. Physical Modelling-. This contains designing the physical data warehouse organization,
data placement, data partitioning, deciding on access techniques, and indexing.
5. Sources: This step contains identifying and connecting the sources for the information for a
data warehouse using the gateway, ODBC drives, or another wrapper.
6. Extract, Transform, Load(ETL):It's the process by which data is extracted from data
sources and moved to a central host
7. Populate the data warehouses:
8. User applications: For the data warehouses to be helpful, there must be end-user
applications. This step contains designing and implementing applications required by the
end-users to access the database

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.

Two types of database processing in a data warehouse


OLTP - On-line transaction processing.
- It is a class of program that facilitates and manages transaction-oriented applications.
- It is used for supporting daily busyness.

OLAP - On-line analytical processing


- It is a way of viewing data in a multidimensional format.
- It is used for supporting decision making.
Data Warehouse Design – Schemas
Schema is a logical description of the entire database. It includes the name and description of
records of all record types including all associated data-items and aggregates. Much like a
database, a data warehouse also requires to maintain a schema. A database uses relational model,
while a data warehouse uses Star, Snowflake, and Fact Constellation schema. In this chapter, we
will discuss the schemas used in a data warehouse.

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.

Fact Constellation Schema


• A fact constellation has multiple fact tables. It is also known as galaxy schema.
• The following diagram shows two fact tables, namely sales and shipping.

Figure 84:Fact Constellation Schema

• The sales fact table is same as that in the star schema.

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.

Syntax for Cube Definition


define cube < cube_name > [ < dimension-list > }: < measure_list >

Syntax for Dimension Definition


define dimension < dimension_name > as ( < attribute_or_dimension_list > )

Star Schema Definition


The star schema that we have discussed can be defined using Data Mining Query Language
(DMQL) as follows −

define cube sales star [time, item, branch, location]:

dollars sold = sum(sales in dollars), units sold = count(*)

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)

Snowflake Schema Definition


Snowflake schema can be defined using DMQL as follows −
define cube sales snowflake [time, item, branch, location]:
dollars sold = sum(sales in dollars), units sold = count(*)

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))

Fact Constellation Schema Definition


Fact constellation schema can be defined using DMQL as follows −
define cube sales [time, item, branch, location]:

dollars sold = sum(sales in dollars), units sold = count(*)

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]:

dollars cost = sum(cost in dollars), units shipped = count(*)

define dimension time as time in cube sales


define dimension item as item in cube sales
define dimension shipper as (shipper key, shipper name, location as
location in cube sales, shipper type)
define dimension from location as location in cube sales
define dimension to location as location in cube sales

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

6.3.7.3 Self assessment


Written Assessment
1 Which of the following is an autonomous homogenous environment ?
A .The same DBMS is at each node and each DBMS works independently.
B. The same DBMS is at each node and a central DBMS coordinates database access.
C. A different DBMS is at each node and each DBMS works independently.
D. A different DBMS is at each node and a central DBMS coordinates database access.

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

3. What is a distributed database?


A. A single logical database that is spread to multiple locations and is interconnected by a
network
B. A loose collection of file that is spread to multiple locations and is interconnected by a
network
C. A single logical database that is limited to one location.
D. A loose collection of file that is limited to one location.

4. What are Decision support systems (DSS)?


A. A family of relational database management systems marketed by IBM
B. Interactive systems that enable decision makers to use databases and models on a
computer in order to solve ill-structured problems
C. It consists of nodes and branches starting from a single root node. Each node represents
a test, or decision
D. None of these
5. What is Data Mining?
A. Data Mining is set to be a process of analyzing the data in different dimensions or
perspectives and summarizing into a useful information.
B. Is the subset of organization-wide data. This subset of data is valuable to specific
groups of an organization.
C. A data that contains data specific to a particular group.
D. None of the above
5. Which are the key features of a data warehouse?
6. Where are multimedia databases used in real life?
7. Outline the key reasons that organisations are increasingly implementing data warehouse

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.4 Tools, Equipment, Supplies and Materials


390
• MS SQL server software
• Computers
• Instruction material
• Stationery
• Internet

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.

7.2 Performance Standard


1. Described the software development process
2. Demonstrated Human Computer Interaction principles
3. Develop and test a VB.NET application

7.3 Learning Outcomes


7.3.1 List of Learning Outcomes
1. Understand fundamentals of Information Systems
2. Understand the Software Development Process
3. Demonstrate Human Computer Interaction Principles
4. Understand the VB.NET programming environment
5. Develop and test 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

1.1.Information system is explained Activities may be carried out


1.2.Types of information systems are outlined in groups or as individual
1.3.Emerging trends in information systems are explained
1.4.information systems are recommended for different
scenarios

7.3.2.2 Information Sheet No 7/LO1: Understand fundamentals of Information Systems

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.

Components of an information system


Information systems are made up of five components: hardware, software, data, people, and
process.
i) Hardware: Information systems hardware is the part of an information system you
can touch – the physical components of the technology. Computers, keyboards, disk
drives, iPads, and flash drives are all examples of information systems hardware.
ii) Software: is a set of instructions that tells the hardware what to do. Software is not
tangible – it cannot be touched.
iii) Data: data is a collection of facts. For example, your street address, the city you
live in, and your phone number are all pieces of data. Like software, data is also
intangible.
iv) People: the people involved with information systems; from the front-line help-
desk workers, to systems analysts, to programmers, all the way up to the chief
information officer (CIO)

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

Types of information systems


Among the types of information systems are:
i) Transaction Processing Systems: A Transaction Processing Systems (TPS) is used
primarily for record keeping which is required in any organization to conduct the business.
Examples of TPS are sales order entry, payroll, and shipping records etc. TPS is used for
periodic report generation in a scheduled manner. TPS is also used for producing reports on
demand as well as exception reports.
ii) Management Information Systems: Management Information System (MIS) provides
the management routine summary of basic operations of the organization. The essential
services are recorded by the TPS of the organization and MIS consolidates the data on sales,
production etc. MIS provides routine information to managers and decision makers. The
primary objective behind installing an MIS in the organization is to increase operational
efficiency. MIS may support marketing, production, finance, etc.
iii) Decision Support Systems: Decision Support System (DSS) serves the management of
an organization. A decision support system has sophisticated data analysis tools, which
support and assist all aspects of problem-specific decision-making. DSS may use data from
external sources such as current stock prices to enhance decision-making.
iv) Executive Information Systems: An Executive Information System (EIS) is also called
the Executive Support System. Senior managers of an organization use the EIS. Therefore, it
must be easy to use so that executives can use it without any assistance. EIS can do trend
analysis, exception reporting and have drill-down capabilities. The results are usually
presented in a graphical form tailored to the executive’s information needs. EIS has on-line
analysis tools and they access a broad range of internal and external data
v) Office Automation Systems: are computer based information systems that collect,
process, store and transmit electronic messages, documents and other forms of
communications among individuals, work groups and organizations

Emerging trends in information systems


It has always been the assumption that the implementation of information systems will, in and
of itself, bring a business competitive advantage. This goes to explain the emerging trends in
information systems, which majorly is to keep businesses afloat despite the competition.

Among the emerging trends is:


i) Globalization: The use of the Internet is growing all over the world, and with it the use of
digital devices

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.

ix) Information system security


In order for a company or an individual to use a computing device with confidence, they must
first be assured that the device is not compromised in any way and that all communications
will be secure. The same applies with any information system.

The following are fundamental concepts of information systems security:


i) Confidentiality: When protecting information, we want to be able to restrict access to those
who are allowed to see it; everyone else should be disallowed from learning anything about
its contents
ii) Integrity: Integrity is the assurance that the information being accessed has not been
altered and truly represents what is intended

395
iii) Availability: Availability means that information can be accessed and modified by anyone
authorized to do so in an appropriate time frame

Figure 85:The Information Security Triad: Confidentiality, Integrity, Availability (CIA)

Tools for information system security


These tools are to ensure confidentiality, integrity and availability of information systems. They
include:
i) Authentication: Authentication can be accomplished by identifying someone through one or
more of three factors: something they know, something they have, or something they are. For
example, the most common form of authentication today is the user ID and password.
ii) Access Control: Once a user has been authenticated, the next step is to ensure that they can only
access the information resources that are appropriate. This is done through the use of access control.
Access control determines which users are authorized to read, modify, add, and/or delete
information.
iii) Back ups: Another essential tool for information security is a comprehensive backup plan for
the entire organization
iv) Firewalls: Another method that an organization should use to increase security on its network is
a firewall. A firewall can exist as hardware or software (or both). A hardware firewall is a device
that is connected to the network and filters the packets based on a set of rules. A software firewall
runs on the operating system and intercepts packets as they arrive to a computer. A firewall protects
all company servers and computers by stopping packets from outside the organization’s network
that do not meet a strict set of criteria. A firewall may also be configured to restrict the flow of
packets leaving the organization.
v) Intrusion Detection Systems: Another device that can be placed on the network for security
purposes is an intrusion detection system, or IDS. An IDS does not add any additional security;
instead, it provides the functionality to identify if the network is being attacked.

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

viii) Mobile security


Creating a BYOD (“Bring Your Own Device”) policy allows employees to integrate themselves more
fully into their job and can bring higher employee satisfaction and productivity. In many cases, it may
be virtually impossible to prevent employees from having their own smartphones or iPads in the
workplace.
So what can be done to secure mobile devices?
i) Implement policies to govern the use of mobile devices within an organization
ii) Use of softwares such as:
a) Geolocation software: that aids in finding lost or misplaced mobile gadgets
b) Remote data removal software: which will remove data from a device if it becomes
a security risk

ix). Web security


Web security is mainly security of web applications such as websites, and web information systems
from attacks and intrusions.

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.4 Tools, Equipment, Supplies and Materials


• Computer
• Stationery
• Instruction material
• Internet

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

2.1.Software Development Life Cycle is explained Activities may be carried out in


2.2.Software Development Methodologies are explained groups or as individual
2.3.Modeling techniques are demonstrated using CASE
tools

7.3.3.2 Information Sheet No 7/LO2: Understand the Software Development Process

Introduction:
This learning outcome covers explaining the Software Development Life Cycle and software
development methodologies and demonstrating modeling techniques using CASE tools.

Software Development Life Cycle


The Software Development life cycle (SDLC), sometimes referred to as the waterfall methodology,
is the sequence of steps that take place during the development of a piece of software.

Software Development Methodologies


Waterfall methodology
The SDLC methodology is sometimes referred to as the waterfall methodology to represent
how each step is a separate part of the process; only when one step is completed can another
step begin. The following are its phases:

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.

Figure 86:SDLC waterfall

Rapid Application Development (RAD)


The RAD methodology is much more compressed than SDLC. Many of the SDLC steps are combined
and the focus is on user participation and iteration. This methodology is much better suited for smaller
projects than SDLC and has the added advantage of giving users the ability to provide feedback
throughout the process. SDLC requires more documentation and attention to detail and is well suited

401
to large, resource-intensive projects. RAD makes more sense for smaller projects that are less
resource-intensive and need to be developed quickly.

The RAD methodology consists of four phases:


i) Requirements Planning. This phase is similar to the preliminary-analysis, system-analysis,
and design phases of the SDLC. In this phase, the overall requirements for the system are
defined, a team is identified, and feasibility is determined.

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.

Figure 87:The RAD methodology

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.

The characteristics of agile methods include:


i) small cross-functional teams that include development-team members and users;
ii) daily status meetings to discuss the current state of the project;
iii) short time-frame increments (from days to one or two weeks) for each change to
be completed;
iv) and at the end of each iteration, a working project is completed to demonstrate to
the stakeholders.
The goal of the agile methodologies is to provide the flexibility of an iterative approach while
ensuring a quality product.

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.

Data Flow Diagrams (DFD)


DFD graphically representing the functions, or processes, which capture, manipulate, store, and
distribute data between a system and its environment and between components of a system.

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

Symbols is a DFD include:


1. Process: A process receives input data and produces output with a different
content or form. Processes can be as simple as collecting input data and saving
in the database, or it can be complex as producing a report containing monthly
sales of all retail stores in the northwest region.
Every process has a name that identifies the function it performs. The name
consists of a verb, followed by a singular noun.
Example: Apply Payment; Calculate Commission; Verify Order
Notation: A rounded rectangle represents a process; Processes are given IDs
for easy referencing.

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.

4. External Entity: An external entity is a person, department, outside


organization, or other information system that provides data to the system or
receives outputs from the system. External entities are components outside of
the boundaries of the information systems. They represent how the information
system interacts with the outside world.

A rectangle represents an external entity; They either supply data or receive


data; They do not process data
Notation:A customer submitting an order and then receive a bill from the
system; A vendor issue an invoice

Figure 88:Data Flow Diagram

Entity Relation Diagrams


An entity relationship diagram (ERD) shows the relationships of entity sets stored in
a database. An entity in this context is an object, a component of data. An entity set is
a collection of similar entities. These entities can have attributes that define its
properties.

Common Entity Relationship Diagram Symbols

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:

1. Entities, which are represented by rectangles. An entity is an object or concept


about which you want to store information.

2. Actions, which are represented by diamond shapes, show how two entities
share information in the database.

In some cases, entities can be self-linked. For example, employees can


supervise other employees.

3. Attributes, which are represented by ovals. A key attribute is the unique,


distinguishing characteristic of the entity. For example, an employee's social
security number might be the employee's key attribute.

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:

Information Engineering 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.

Structural UML diagrams


➔ Class diagram
➔ Package diagram
➔ Object diagram
➔ Component diagram
➔ Composite structure diagram
➔ Deployment diagram

Behavioral UML diagrams


➔ Activity diagram
➔ Sequence diagram
➔ Use case diagram
➔ State diagram
➔ Communication diagram
➔ Interaction overview diagram
➔ Timing diagram
407
Using CASE tools
CASE stands for Computer Aided Software Engineering. It means, development and maintenance
of software projects with help of various automated software tools.

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.

Components of CASE Tools


CASE tools can be broadly divided into the following parts based on their use at a particular SDLC
stage:
• Central Repository - CASE tools require a central repository, which can serve as a source
of common, integrated and consistent information. Central repository is a central place of
storage where product specifications, requirement documents, related reports and diagrams,
other useful information regarding management is stored. Central repository also serves as
data dictionary.
• Upper Case Tools - Upper CASE tools are used in planning, analysis and design stages of
SDLC.
• Lower Case Tools - Lower CASE tools are used in implementation, testing and maintenance.
• Integrated Case Tools - Integrated CASE tools are helpful in all the stages of SDLC, from
Requirement gathering to Testing and documentation.

CASE tools can be grouped together if they have similar functionality, process activities and
capability of getting integrated with other tools.

Scope of Case Tools


The scope of CASE tools goes throughout the SDLC.

Case Tools Types

Popular CASE tool types include:


Diagram tools
These tools are used to represent system components, data and control flow among various software
components and system structure in a graphical form. For example, Flow Chart Maker tool for
creating state-of-the-art flowcharts, Start UML for creating UML diagrams and MS Visio for many
categories of models.

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.

Web Development Tools

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.4 Tools, Equipment, Supplies and Materials


• UI/UX software
410
• Computer
• Internet
• Stationery
• Instruction material

7.3.3.5 References

1) Sommerville, Software Engineering, 9th ed, Addison Wesley, 2011


2) https://www.visual-paradigm.com/guide/data-flow-diagram/what-is-data-flow-diagram/

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

3.1 Human Computer Interaction is explained Activities may be carried out in


3.2 Interface design principles are explained groups or as individual
3.3 Interface design is demonstrated using a design
software

7.3.4.2 Information Sheet No 7/LO3: Demonstrate Human Computer Interaction Principles

Introduction
This learning outcome covers explaining the Human Computer Interaction and interaction design
principles and demonstrating interface design using a design software.

Human Computer Interaction Concepts


Human-computer interaction (HCI) is a multidisciplinary field of study focusing on the design of
computer technology and, in particular, the interaction between humans (the users) and
computers.

Role of interaction design


It is the design of the interaction between users and products. Most often when people talk about
interaction design, the products tend to be software products like apps or websites. The goal of
interaction design is to create products that enable the user to achieve their objective(s) in the best
way possible.

The 5 dimensions of interaction design


The 5 dimensions of interaction design is a useful model to understand what interaction design
involves.
1D: Words
Words—especially those used in interactions, like button labels—should be meaningful and
simple to understand. They should communicate information to users, but not too much
information to overwhelm the user.

2D: Visual representations


This concerns graphical elements like images, typography and icons that users interact with.
These usually supplement the words used to communicate information to users.

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.

Interface design principles


Despite its importance, good HCI design is generally difficult, mainly because it is a multi objective
task that involves simultaneous consideration of many things, such as the types of users,
characteristics of the tasks, capabilities and cost of the devices, lack of objective or exact quantitative
evaluation measures, and changing technologies, to name just a few. A considerable knowledge in
many different fields is required.

Main HCI principles include:


1. “Know Thy User”: This principle simply states that the interaction and interface should cater
to the needs and capabilities of the target user of the system in design.
2. Understand the Task: The term task refers to the job to be accomplished by the user through
the use of the interactive system. In fact, understanding the task at hand is closely related to
the interaction modeling and user analysis. It really boils down to identifying the sequence
and structure of subtasks at an abstraction level appropriate for the typical user within the
larger application context.
3. Reduce Memory Load: Designing interaction with as little memory load as possible is a
principle that also has a theoretical basis. Humans are certainly more efficient in carrying out
tasks that require less memory burden, long or short term. Keeping the user’s short-term
memory load light is of particular importance with regard to the interface’s role as a quick
and easy guidance to the completion of the task.
4. Strive for Consistency: ensure consistency throughout the design
5. Remind Users and Refresh Their Memory: Any significant task will involve the use of
memory, so another good strategy is to employ interfaces that give continuous reminders of

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

User interface Design Software (UI/UX) tools


• UI/UX stands for User Interface/User Experience
• These tools are most useful for prototyping the look and feel of user interfaces.

How to choose the right prototyping tool


In order to choose the right prototyping tool for designing, there are a few factors which need to be
evaluated for that tool to check whether it fits our needs or not.

1. Learning Curve – How is it easy to adapt to?


2. Sharing - As collaboration is key for design, we check how well suitable it is for teamwork. The
tool should provide collaboration ability for multiple people to be in sync with each other. Since
every designer has their own perspective/ ideas for a project it’s imperative that all of them stay on
the same page.
3. Usage - How well it fits your design process and other tools you regularly use. For example, if
you are designing in Photoshop, Illustrator or Sketch, it would be great if your prototyping software
could directly use the files produced by these apps without requiring you to export assets separately
and then build everything from scratch to create the interactions.
4. Ease of use and comfort - The ease of use in using the prototyping tool is essential for the
designer to save time and help increase output. It should reduce the number of steps required for a
designer to complete a task rather than increasing it.
5. Cost
6. Fidelity: What would be the requirement for the prototype? Whether you just require a mockup
of the app layout or do you need something that supports more details and complex interactions?

Some Popular Prototyping Tools


1. InVision
• Runs on Web
• Prototypes for Android, iOS, Web
• Invision is by far the most popular prototyping tool in the world.
• With InVision’s project management page, you can organize design components into a
status workflow.
• You can set columns for To-do, In progress, Needs review, and Approved, and drag and
drop your design components into the appropriate column.
• You could add interactions and animations to static images. You can upload multiple file
types, including JPG, PNG, GIF, AI, and PSD.

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.4 Tools, Equipment, Supplies and Materials


415
• UX/UI software
• Computer
• Internet
• Stationery
• Instruction material

7.3.4.5 References

1. Grudin, J. (2012) A Moving Target: The evolution of Human-computer Interaction. In J.


Jacko (Ed.), Human-computer interaction handbook: Fundamentals, evolving technologies,
and emerging applications. (3rd edition). Taylor & Francis
2. Human–Computer Interaction: Fundamentals and Practice by Gerard Jounghyun Kim; ISBN
978-1-4822-3389-6
3. https://asktog.com/atc/principles-of-interaction-design/

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

4.1. The .Net framework is explained Activities may be carried out in


4.2 Visual Studio is installed groups or as individual
4.3 Features of VB.Net are outlined
4.4 The IDE environment is explained
4.5 VB.Net program structure is explained
4.6. VB.Net project is created and compiled

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

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.

Following are some of the components of the .Net framework −


1. Common Language Runtime (CLR)
2. The .Net Framework Class Library

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

Installation of Visual Studio


Download it online from Microsoft.

Installation of Visual Studio

It gets automatically installed in your machine. Please note that you need an active internet connection
for installing

Integrated Development Environment (IDE) For VB.Net


Visual Studio IDE
Visual Studio is a powerful and customizable programming environment that contains all the tools
you need to build programs quickly and efficiently. It offers a set of tools that help you write and
modify the code for your programs, and also detect and correct errors in your programs.

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.

VB.NET Program Structure


A VB.Net program basically consists of the following parts −
• Namespace declaration
• A class or module
• One or more procedures
• Variables
• The Main procedure
• Statements & Expressions
• Comments

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!

Let us look various parts of the above program −


• The first line of the program Imports System is used to include the System namespace in the
program.
• The next line has a Module declaration, the module Module1. VB.Net is completely object
oriented, so every program must contain a module of a class that contains the data and
procedures that your program uses.
• Classes or Modules generally would contain more than one procedure. Procedures contain
the executable code, or in other words, they define the behavior of the class. A procedure
could be any of the following −
o Function
o Sub
o Operator
o Get
o Set
o AddHandler
o RemoveHandler
o RaiseEvent
• The next line( 'This program) will be ignored by the compiler and it has been put to add
additional comments in the program.
• The next line defines the Main procedure, which is the entry point for all VB.Net programs.
The Main procedure states what the module or class will do when executed.
• The Main procedure specifies its behavior with the statement
Console.WriteLine("Hello World") WriteLine is a method of the Console class defined in
the System namespace. This statement causes the message "Hello, World!" to be displayed
on the screen.
• The last line Console.ReadKey() is for the VS.NET Users. This will prevent the screen from
running and closing quickly when the program is launched from Visual Studio .NET.

Compile & Execute VB.Net Program


If you are using Visual Studio.Net IDE, take the following steps −
• Start Visual Studio.
420
• On the menu bar, choose File → New → Project.
• Choose Visual Basic from templates
• Choose Console Application.
• Specify a name and location for your project using the Browse button, and then choose the
OK button.
• The new project appears in Solution Explorer.
• Write code in the Code Editor.
• Click the Run button or the F5 key to run the project. A Command Prompt window appears
that contains the line 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.

VB.Net is an object-oriented programming language. In Object-Oriented Programming


methodology, a program consists of various objects that interact with each other by means of actions.
The actions that an object may take are called methods. Objects of the same kind are said to have
the same type or, more often, are said to be in the same class.
When we consider a VB.Net program, it can be defined as a collection of objects that communicate
via invoking each other's methods. Let us now briefly look into what do class, object, methods and
instance variables mean.

• 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.

Example: A Rectangle Class in VB.Net


For example, let us consider a Rectangle object. It has attributes like length and width. Depending
upon the design, it may need ways for accepting the values of these attributes, calculating area and
displaying details.

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.

An object is an instance of a class −


Dim r As New Rectangle()

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

Creating aVB.Net project


To start Vb.net from your computer, go to Start Menu->All Programs->Visual Studio (2015). A
splash screen will display for a view seconds and finally, a dashboard will be displayed.

Then click on the File menu and select “New project”


On the template (Top left of the form), select Visual Basic and make sure “Windows Form
Application” is selected as shown on the image below.

Windows Form Application

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.

Figure 91:VB.NET - Windows Forms

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.

Select project type from New project dialog Box.

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.4 Tools, Equipment, Supplies and Materials


• Visual Studio
• Computer
• Internet
• Stationery
• Instruction material

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

7.3.6.2 Information Sheet No 7/LO5: Develop and test a VB.NET application

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.

VB.Net - Basic Controls


An object is a type of user interface element you create on a Visual Basic form by using a toolbox
control. In fact, in Visual Basic, the form itself is an object. Every Visual

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.

For example, Form1.Caption="Hello"

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.

The following are some of the commonly used controls −


i) Forms: The container for all the controls that make up the user interface.
ii) TextBox: It represents a Windows textbox control.
iii) Label: It represents a standard Windows label.
iv) Button: It represents a Windows button control.
v) ListBox: It represents a Windows control to display a list of items.
vi) ComboBox: It represents a Windows combo box control.
vii) RadioButton: It enables the user to select a single option from a group of choices when paired
with other RadioButton controls.
viii) CheckBox: It represents a Windows CheckBox.
ix) PictureBox: It represents a Windows picture box control for displaying an image.
x) ProgressBar: It represents a Windows progress bar control.
xi) ScrollBar: It Implements the basic functionality of a scroll bar control.
xii) DateTimePicker: It represents a Windows control that allows the user to select a date and a
time and to display the date and time with a specified format.
xiii) TreeView: It displays a hierarchical collection of labeled items, each represented by a
TreeNode.
xiiii) ListView: It represents a Windows list view control, which displays a collection of items that
can be displayed using one of four different views.

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.

VB.Net is an event-driven language. There are mainly two types of events −


• Mouse events
• Keyboard events

Handling Mouse Events


Mouse events occur with mouse movements in forms and controls. Following are the various mouse
events related with a Control class −
• MouseDown − it occurs when a mouse button is pressed
• MouseEnter − it occurs when the mouse pointer enters the control
• MouseHover − it occurs when the mouse pointer hovers over the control

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

Private Sub txtID_MouseEnter(sender As Object, e As EventArgs)_


Handles txtID.MouseEnter
'code for handling mouse enter on ID textbox
txtID.BackColor = Color.CornflowerBlue
txtID.ForeColor = Color.White
End Sub

Private Sub txtID_MouseLeave(sender As Object, e As EventArgs) _


Handles txtID.MouseLeave
'code for handling mouse leave on ID textbox
txtID.BackColor = Color.White
txtID.ForeColor = Color.Blue
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

Private Sub txtName_MouseLeave(sender As Object, e As EventArgs) _


Handles txtName.MouseLeave
'code for handling mouse leave on Name textbox
txtName.BackColor = Color.White
txtName.ForeColor = Color.Blue
End Sub

Private Sub txtAddress_MouseEnter(sender As Object, e As EventArgs) _


Handles txtAddress.MouseEnter
'code for handling mouse enter on Address textbox
txtAddress.BackColor = Color.CornflowerBlue
txtAddress.ForeColor = Color.White
End Sub

Private Sub txtAddress_MouseLeave(sender As Object, e As EventArgs) _


Handles txtAddress.MouseLeave
'code for handling mouse leave on Address textbox
txtAddress.BackColor = Color.White
txtAddress.ForeColor = Color.Blue
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) _
Handles Button1.Click
MsgBox("Thank you " & txtName.Text & ", for your kind cooperation")
End Sub
End Class
When the above code is executed and run using Start button available at the Microsoft Visual Studio
tool bar, it will show the following window −

431
Try to enter text in the text boxes and check the mouse events −

Handling Keyboard Events


Following are the various keyboard events related with a Control class −
• KeyDown − occurs when a key is pressed down and the control has focus
• KeyPress − occurs when a key is pressed and the control has focus
• KeyUp − occurs when a key is released while the control has focus

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.

Private Sub txtID_KeyUP(sender As Object, e As KeyEventArgs) _


Handles txtID.KeyUp

If (Not Char.IsNumber(ChrW(e.KeyCode))) Then


MessageBox.Show("Enter numbers for your Customer ID")
txtID.Text = " "
End If
End Sub
• Add the following codes for handling the KeyUP events of the text box txtID.
Private Sub txtAge_KeyUP(sender As Object, e As KeyEventArgs) _
Handles txtAge.KeyUp

If (Not Char.IsNumber(ChrW(e.keyCode))) Then


MessageBox.Show("Enter numbers for age")
txtAge.Text = " "
End If
End Sub
When the above code is executed and run using Start button available at the Microsoft Visual Studio
tool bar, it will show the following window −

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 −

Database Access with VB.NET


Applications communicate with a database, firstly, to retrieve the data stored there and present it in
a user-friendly way, and secondly, to update the database by inserting, modifying and deleting data.
Microsoft ActiveX Data Objects.Net (ADO.Net) is a model, a part of the .Net framework that is
used by the .Net applications for retrieving, accessing and updating data.

ADO.Net Object Model


ADO.Net object model is nothing but the structured process flow through various components. The
object model can be pictorially described as −

Figure 92:ADO.Net Object Model

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.

There are following different types of data providers included in ADO.Net


• The .Net Framework data provider for SQL Server - provides access to Microsoft SQL
Server.
• The .Net Framework data provider for OLE DB - provides access to data sources exposed by
using OLE DB.
• The .Net Framework data provider for ODBC - provides access to data sources exposed by
ODBC.
• The .Net Framework data provider for Oracle - provides access to Oracle data source.
• The EntityClient provider - enables accessing data through Entity Data Model (EDM)
applications.

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 −

Figure 93: VB.NET DataSet objects

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.

Let us connect to this database. Take the following steps −


• Select TOOLS → Connect to Database

• 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.

• Add a DataGridView on the form.

• Click on the Choose Data Source combo box.


• Click on the Add Project Data Source link.

438
• This opens the Data Source Configuration Wizard.
• Select Database as the data source type

• Choose DataSet as the database model.

• Choose the connection already set up.

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

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles


Button1.Click
Dim connection As SqlConnection = New sqlconnection()
connection.ConnectionString = "Data Source=KABIR-DESKTOP; _
Initial Catalog=testDB;Integrated Security=True"
connection.Open()
Dim adp As SqlDataAdapter = New SqlDataAdapter _
("select * from Customers", connection)
Dim ds As DataSet = New DataSet()
adp.Fill(ds)
DataGridView1.DataSource = ds.Tables(0)
End Sub
End Class
• When the above code is executed and run using Start button available at the Microsoft Visual
Studio tool bar, it will show the following window −

• 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

Private Function CreateDataSet() As DataSet


'creating a DataSet object for tables
Dim dataset As DataSet = New DataSet()
' creating the student table
Dim Students As DataTable = CreateStudentTable()
dataset.Tables.Add(Students)
Return dataset
End Function

Private Function CreateStudentTable() As DataTable


443
Dim Students As DataTable
Students = New DataTable("Student")
' adding columns
AddNewColumn(Students, "System.Int32", "StudentID")
AddNewColumn(Students, "System.String", "StudentName")
AddNewColumn(Students, "System.String", "StudentCity")
' adding rows
AddNewRow(Students, 1, "Zara Ali", "Kolkata")
AddNewRow(Students, 2, "Shreya Sharma", "Delhi")
AddNewRow(Students, 3, "Rini Mukherjee", "Hyderabad")
AddNewRow(Students, 4, "Sunil Dubey", "Bikaner")
AddNewRow(Students, 5, "Rajat Mishra", "Patna")
Return Students
End Function

Private Sub AddNewColumn(ByRef table As DataTable, _


ByVal columnType As String, ByVal columnName As String)
Dim column As DataColumn = _
table.Columns.Add(columnName, Type.GetType(columnType))
End Sub

'adding data into the table


Private Sub AddNewRow(ByRef table As DataTable, ByRef id As Integer,_
ByRef name As String, ByRef city As String)
Dim newrow As DataRow = table.NewRow()
newrow("StudentID") = id
newrow("StudentName") = name
newrow("StudentCity") = city
table.Rows.Add(newrow)
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles


Button1.Click
Dim ds As New DataSet
ds = CreateDataSet()
DataGridView1.DataSource = ds.Tables("Student")
End Sub
End Class
• When the above code is executed and run using Start button available at the Microsoft Visual
Studio tool bar, it will show the following window −
444
• Clicking the Fill button displays the table on the data grid view control −

Deployment of a VB.NET Application


This entails getting the necessary files and resources from the development environment to the
production environment.

The process of deployment involves two categories of computers, as follows:


• The computer used to create the Setup project (your computer) is called the development
computer. The purpose of a Setup project is to create another program called an installer.
The Setup project bundles all of the elements of an application so that it can be distributed
to another computer. To distribute the application, you can copy the output of the Setup
project to removable media such as a CD-ROM, or DVD. Setup files can also be placed
on a Web site where they can be downloaded by anyone connected to the Internet or a
company intranet.
• The end user’s computer is called the target computer. The end user typically runs the
installer (the file named Setup.exe) that you created to install your application on their
computer. By running the installer, all of the files necessary to run your application are

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.4 Tools, Equipment, Supplies and Materials


• Visual Studio
• Computer
• Internet
• Stationery
• Instruction material

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.

8.2 Performance Standard


1. Illustrated different types of networks
2. Illustrated different types of topologies
3. Specified network requirements for a site
4. Illustrated different types of distributed systems
5. Illustrated different types of distributed system architectures
6. Specified distributed system architecture requirements for a simulated site
7. Illustrated different types of distributed processing
8. Illustrated different types of file systems
9. Illustrated file sharing and accessing methods
10. Set up a network as per site requirements
11. Troubleshot a network as per IEEE standard
12. Illustrated different functions of OSI layers

8.3 Learning Outcomes


8.3.1 List of Learning Outcomes
1. Understand networking and distributed systems
2. Understand distributed systems architectures
3. Understand file management distributed processing
4. Set up a network in a distributed environment
5. Troubleshoot 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

Learning Activities Special Instructions

1.1 Fundamentals of networking are Activities may be carried out in groups or as


explained individual
1.2 Types of networks are illustrated
1.3 Network topologies are illustrated
1.4 Transmission media are outlined ·
1.5 Distributed system is explained
1.6 Types of distributed systems are
illustrated
1.7 Models in distributed systems are
illustrated
1.8 Network requirements for a site are
specified

·
8.3.2.1 Information Sheet No. 8/LO1: Understand networking and distributed systems concepts

Introduction

This learning outcome covers explaining fundamentals of networking, illustrating types


of networks, network topologies, outlining transmission media, explaining distributed
systems, illustrating types of distributed systems and models in distributed systems and
specifying network requirements for a site.

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.

Definition of network terminologies


WAN
It stands for Wide Area Network and covers a wide area such as a city.

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.

World Wide Web (WWW)


It is the service that is used on Internet to view and search contents (in the form of web-pages).

Instant messaging (IM)


It is an online facility that facilitates us to chat or talk. Such service is provided by Skype, Google
Talk, Windows Live Messenger, Yahoo Messenger, etc.

Voice over Internet Protocol (VoIP)


It is a Protocol, which is used especially for voice transfer over IP network. Likewise, it facilitates
users to make phone-calls by using internet.

Really Simple Syndication (RSS)


It is a technique, which is used for the dissemination of information, articles, etc. Users normally
subscribe to the RSS channel in order to receive news. After subscription, users do not need to visit
the respective website rather they receive emails regarding the same.

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.

Integrated Services Digital Network (ISDN)


It is a set of communication standards that transmits voice, video, data, and other network services
simultaneously.

Asymmetric Digital Subscriber Line (ADSL)


It is a sort of digital subscriber line (DSL) technology that facilitates faster data transmission.

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.

Social networking websites


It refers to the websites that facilitate users with a common platform where they can share their
message (in text, audio, or even video form), images, videos, etc. For example, Facebook, Google+,
Twitter, LinkedIn, MySpace, etc.

Network components

Figure 94:Network components

NIC(Network interface card)

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.

Cables and connectors


Cable is a transmission media that transmits the communication signals. There are three types of
cables:

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.

Application and benefits of networking

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

Metropolitan Area Network (MAN)


• A MAN is a network that covers a larger geographic area by interconnecting a different
LAN to form a larger network.
• Government agencies use MAN to connect to the citizens and private industries.
• In MAN, various LANs are connected to each other through a telephone exchange line.
• The most widely used protocols in MAN are RS-232, Frame Relay, ATM, ISDN, OC-3,
ADSL, etc.
453
• It has a higher range than LAN

Figure 96:MAN

Wide Area Network (WAN)


• A WAN is a network that extends over a large geographical area such as states or
countries.
• Not limited to a single location, but it spans over a large geographical area through a
telephone line, Fibre optic cable or satellite links.
• The internet is one of the biggest WAN in the world
• Widely used in the field of Business, government, and education.

Figure 97:WAN

Personal Area Network (PAN)


• PAN is a network arranged within an individual person, typically within a range of 10
meters.
• Is used for connecting the computer devices of personal use is known as Personal Area
Network.
• Covers an area of 30 feet.
• Personal computer devices that are used to develop the personal area network are the
laptop, mobile phones, media player and play stations
454
Figure 98:PAN

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.

Figure 99:Star topology

Advantages of Star topology


• Efficient troubleshooting: Troubleshooting is quite efficient in a star topology as
compared to bus topology. In a bus topology, the manager has to inspect the kilometers of
cable. In a star topology, all the stations are connected to the centralized network.
Therefore, the network administrator has to go to the single station to troubleshoot the
problem.
• Network control: Complex network control features can be easily implemented in the star
topology. Any changes made in the star topology are automatically accommodated.
• Limited failure: As each station is connected to the central hub with its own cable,
therefore failure in one cable will not affect the entire network.
455
• Familiar technology: Star topology is a familiar technology as its tools are cost-effective.
• Easily expandable: It is easily expandable as new stations can be added to the open ports
on the hub.
• Cost effective: Star topology networks are cost-effective as it uses inexpensive coaxial
cable.
• High data speeds: It supports a bandwidth of approx 100Mbps. Ethernet 100BaseT is one
of the most popular Star topology networks.

Disadvantages of Star topology


• A Central point of failure: If the central hub or switch goes down, then all the connected
nodes will not be able to communicate with each other.
• Cable: Sometimes cable routing becomes difficult when a significant amount of routing is
required.

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.

Figure 100:Ring topology

Working of Token passing


• A token moves around the network, and it is passed from computer to computer until it
reaches the destination.
• The sender modifies the token by putting the address along with the data.
• The data is passed from one device to another device until the destination address
matches. Once the token received by the destination device, then it sends the
acknowledgment to the sender.
• In a ring topology, a token is used as a carrier.
456
Advantages of Ring topology:
• Network Management: Faulty devices can be removed from the network without bringing
the network down.
• Product availability: Many hardware and software tools for network operation and
monitoring are available.
• Cost: Twisted pair cabling is inexpensive and easily available. Therefore, the installation
cost is very low.
• Reliable: It is a more reliable network because the communication system is not
dependent on the single host computer.

Disadvantages of Ring topology:


• Difficult troubleshooting: It requires specialized test equipment to determine the cable
faults. If any fault occurs in the cable, then it would disrupt the communication for all the
nodes.
• Failure: The breakdown in one station leads to the failure of the overall network.
• Reconfiguration difficult: Adding new devices to the network would slow down the
network.
• Delay: Communication delay is directly proportional to the number of nodes. Adding new
devices increases the communication delay.

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

Mesh topology is divided into two categories:


• Fully connected mesh topology
• Partially connected mesh topology

Advantages of Mesh topology:


• Reliable: The mesh topology networks are very reliable as if any link breakdown will not
affect the communication between connected computers.
• Fast Communication: Communication is very fast between the nodes.
• Easier Reconfiguration: Adding new devices would not disrupt the communication
between other devices.

Disadvantages of Mesh topology


• Cost: A mesh topology contains a large number of connected devices such as a router and
more transmission media than other topologies.
• Management: Mesh topology networks are very large and very difficult to maintain and
manage. If the network is not monitored carefully, then the communication link failure
goes undetected.
• Efficiency: In this topology, redundant connections are high that reduces the efficiency of
the network.

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).

Figure 102:Bus Topology

• 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".

Advantages of Bus topology:


• Low-cost cable: In bus topology, nodes are directly connected to the cable without
passing through a hub. Therefore, the initial cost of installation is low.
• Moderate data speeds: Coaxial or twisted pair cables are mainly used in bus-based
networks that support up to 10 Mbps.
• Familiar technology: Bus topology is a familiar technology as the installation and
troubleshooting techniques are well known, and hardware components are easily
available.
• Limited failure: A failure in one node will not have any effect on other nodes.

Disadvantages of Bus topology:


• Extensive cabling: A bus topology is quite simpler, but still it requires a lot of cabling.
• Difficult troubleshooting: It requires specialized test equipment to determine the cable
faults. If any fault occurs in the cable, then it would disrupt the communication for all the
nodes.
• Signal interference: If two nodes send the messages simultaneously, then the signals of
both the nodes collide with each other.
• Reconfiguration difficult: Adding new devices to the network would slow down the
network.

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.

Twisted Pair is of two types:


a) Unshielded Twisted Pair (UTP):
This type of cable has the ability to block interference and does not depend on a physical shield
for this purpose. It is used for telephonic applications.

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

There are 3 major types of Unguided Media:


(i) Radio waves
• These are easy to generate and can penetrate through buildings. The sending and receiving
antennas need not be aligned. Frequency Range: 3 KHz – 1GHz. AM and FM radios and
cordless phones use radio waves for transmission.
• Further Categorized as (i) Terrestrial and (ii) Satellite.

(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.

Types of distributed systems

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).

Distributed systems models

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.

Figure 103: Client Server Distributed Model

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.

Synchronous distributed systems model

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.

Asynchronous distributed systems model


• Many distributed systems (including those on the Internet) are asynchronous. - No bound
on process execution time (nothing can be assumed about speed, load, and reliability of
computers). - No bound on message transmission delays (nothing can be assumed about
speed, load, and reliability of interconnections) - No bounds on drift rates between local
clocks.

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”.

Specifying network requirements for a site:


1) Type of network: Wired vs. Wireless Networks
Wired networks offer many advantages over wireless networks, especially in terms of speed and
cost, although if your home or business isn't pre-wired with Ethernet cabling it can often end up
being quite expensive to add new wiring.

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.

Selecting a Wireless Network Standard


• The wireless standard you select for your network will dictate the router(s) and network
interface cards (NICs) you'll need to purchase for your computers and other network
resources.
• Each standard varies in terms of cost, speed, maximum distance and potential for
interference, so you'll want to prioritize your network needs and select the standard that
will best meet both your current and future requirements.
• The newer standards are often backwards-compatible with older standards, although the
downside is that you won't be able to reach maximum speeds when working in a mixed-
standards mode.

Main wireless standards in use today and their specifications:


• 802.11a - Expensive, with max. theoretical speed of 11Mbps, 100 foot max. range and
low risk of interference on the 5GHz spectrum
466
• 802.11b - Inexpensive, with max. theoretical speed of 54 Mbps, 150 foot max. range and
high risk of interference on the 2.4 GHz spectrum
• 802.11g - Moderate cost, with max. theoretical speed of 54 Mbps, 150 foot range and high
risk of interference on the 2.4 GHz spectrum
• 802.11n - Moderate to expensive cost, with max. theoretical speed of 250+ Mbps, 250
foot max. range and moderate risk of interference on both 2.4 GHz and 5 GHz spectrum.

What Equipment Will I Need?

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.

Your shopping list of networking essentials will include:


1. At least one router, which provides Internet connectivity to your network.
2. At least one access point (for wireless networks), which establishes and manages your
wireless network.
3. At least one hub or switch, which manages your wired Ethernet network and its connections.
4. Wireless network adapters and/or Ethernet network interface cards (NICs) for each of
your computers and network resources.
5. Repeaters to strengthen your wireless signal and therefore increase the maximum range of
your wireless network.
6. Network bridges to connect two or more networks.

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.

Following are some offerings to look for.


i) Content Filtering. You may want to be able to control and monitor the websites that your
employees are visiting. Find a content filter that gives you the flexibility that you need.
ii) Intrusion Prevention and Gateway Antivirus. Many routers advertise this service. You need a
device that is not only effective, but also easily configurable and offers good reporting.
iii) Firewall. Almost every router has a firewall built into it. The configurability of each firewall
depends on the quality of the router. Most businesses need to be able to configure their firewall so
that they not only block threats, but also allow other traffic through without issue.

f) Manufacturers and reputations


Every network administrator probably already has an idea of which router manufacturers they
like, and which ones they don't. These ideas can reflect past experiences, general preferences, and
industry reporting. Be sure that the manufacturer you choose has a good reputation and meets
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.

iv) Complexity. Unmanaged switches are simple; there is no configuration


needed. Many knowledgeable administrators still have a hard time grasping
the details of managed switch configuration. Don't make administration more
complicated if it isn't necessary.
v) Cost. Managed switches can be expensive, at least double the cost of an
unmanaged switch. If you won't be taking advantage of the features of a
managed switch, purchasing an unmanaged switch will save you some
money.
vi) Configurability. If your network needs to utilize VLAN technology, you
will need a managed switch. With a managed switch, each port can be
configured to do exactly what you need it to do. This approach is often used
in networks using VoIP phone technology.
c) Number of Ports
Switches come in a number of different port configurations, generally starting at 5 ports and up to
48 (and occasionally more). It's always a good idea to have a complete count of the number of
devices in your network that will need switch ports. It's also good practice to be sure to leave
enough open ports available for future expansion.

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.

Here are a number of suggestions for securing your wireless network.


• Security keys. All networks with corporate-level access must be encrypted and force
users to use a key to authenticate. For increased security, guest networks can be
password-protected as well.
• Network segmentation. Your guest network should be separated from your corporate
network. This could be done in a number of ways, including VLANs, router
configuration, or even separate internet connections. If your corporate wireless network
doesn't need the same access as the wired network, these networks should be segmented
as well.
• MAC address filtering. Administrators can use MAC address filtering on corporate
networks to provide additional verification for devices to connect. For devices to be able
to access a filtered network, not only do users need to know the wireless key, but the
administrator must add the device's MAC address to a list of allowed devices. Keep in
mind, however, that attackers can easily “spoof” MAC addresses (by making a device
appear to have a valid MAC address in order to connect), so you should not rely on this
safeguard alone to secure your wireless network.

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.

Here are a few things to consider.


• Consult the experts. You need to verify that you are purchasing the right equipment for
your situation. Talk to the software companies that you integrate with, as well as your
friends in the business, to see what hardware works best for them.
472
• Consider regulations. Different industries must abide by government regulations. Before
purchasing hardware, be sure that it follows all of the regulations for your industry, now
and into the future.
• Determine vendor options. Figure out where you can purchase equipment. Do you need to
purchase hardware directly from your software provider, or can you shop around for the
best price? How can you verify that what you purchase will be compatible and meet
regulations?

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

1. Combination of two or more networks are called


A. Internetwork
B. WAN
C. MAN
D. LAN
2. Which topology covers security, robust and eliminating the traffic factor?
A. Mesh
B. Ring
C. Star
D. Bus
3. Average data rate is equal to
A. amount of data/ amount of Entries sent
B. amount of data/ time
C. time/amount of data
D. total number of bits sent/Packets
4. Elapsed time between an inquiry and a response is called.
A Transit Time
B Delay Time
C Processing Time
473
D Response time

5. What is the other name of Nodes?


A Devices
B Links
C Medium
D Modes
6. Which topology covers security, robust and eliminating traffic factor?
A Mesh
B Ring
C Star
D Bus
7. National Internet Service Provider (ISP) networks are connected to one another by private
switching stations called
A Network Access Points
B Peering Points
C National ISP
D Regional ISP
8. Multipoint topology is
A Bus
B Star
C Mesh
D Ring
9. A communication path way that transfers data from one point to another is called
A Link
B Node
C Medium
D Topology

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.4 Tools, Equipment, Supplies and Materials

• Networking tool kit


• Essential network devices
• Computers
• Stationery
• Internet
• Instruction material

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

Learning Activities Special Instructions

2.1 Distributed architecture is illustrated Activities may be carried out in groups


2.2 Architecture styles are illustrated or as individual
2.3 Types of distributed system architectures are
illustrated
2.4 Distributed system architecture requirements for a ·
simulated site are specified

8.3.2.2 Information Sheet No 8/LO2: 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.

Object Based 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

● This architecture is based on a data center, where the primary communication


happens via a central data repository. This common repository can be either active or
passive.
● This is more like a producer consumer problem. The producers produce items to a
common data store, and the consumers can request data from it. This common
repository, could even be a simple database. The communication between objects
happening through this shared common storage. This supports different components
(or objects) by providing a persistent storage space for those components (such as a
MySQL database).

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.

Types of distributed system architectures:


Centralized
Thinking in terms of clients that request services from servers helps us understand and manage the
complexity of distributed systems.
● In the basic client-server model, processes in a distributed system are divided into
two (possibly overlapping) groups. A server is a process implementing a specific
service, for example, a file system service or a database service.
● A client is a process that requests a service from a server by sending it a request and
subsequently waiting for the server's reply. This client-server interaction, also known
as request-reply behavior is shown in the figure below.

Figure 105:Client Server Interaction

General interaction between a client and a server.


● Communication between a client and a server can be implemented by means of a
simple connectionless protocol when the underlying network is fairly reliable as in
many local-area networks.
● In these cases, when a client requests a service, it simply packages a message for the
server, identifying the service it wants, along with the necessary input data.
● The message is then sent to the server. The latter, in turn, will always wait for an
incoming request, subsequently process it, and package the results in a reply
message that is then sent to the client.
● Using a connectionless protocol has the obvious advantage of being efficient. As
long as messages do not get lost or corrupted, the request/reply protocol just
sketched works fine.
● Unfortunately, making the protocol resistant to occasional transmission failures is
not trivial. The only thing we can do is possibly let the client resend the request
478
when no reply message comes in. The problem, however, is that the client cannot
detect whether the original request message was lost, or that transmission of the
reply failed.
● If the reply was lost, then resending a request may result in performing the operation
twice. If the operation was something like "transfer $10,000 from my bank account,"
then clearly, it would have been better that we simply reported an error instead. On
the other hand, if the operation was "tell me how much money I have left," it would
be perfectly acceptable to resend the request.
● When an operation can be repeated multiple times without harm, it is said to be
idempotent. Since some requests are idempotent and others are not it should be clear
that there is no single solution for dealing with lost messages.
● As an alternative, many client-server systems use a reliable connection-oriented
protocol. Although this solution is not entirely appropriate in a local-area network
due to relatively low performance, it works perfectly fine in wide-area systems in
which communication is inherently unreliable. For example, virtually all Internet
application protocols are based on reliable TCP/IP connections. In this case,
whenever a client requests a service, it first sets up a connection to the server before
sending the request. The server generally uses that same connection to send the reply
message, after which the connection is torn down. The trouble is that setting up and
tearing down a connection is relatively costly, especially when the request and reply
messages are small.
Decentralized
● Multitiered client-server architectures are a direct consequence of dividing
applications into a user-interface, processing components, and a data level. The
different tiers correspond directly with the logical organization of applications.
● In many business environments, distributed processing is equivalent to organizing a
client-server application as a multitiered architecture. We refer to this type of
distribution as vertical distribution. The characteristic feature of vertical
distribution is that it is achieved by placing logically different components on
different machines. The term is related to the concept of vertical fragmentation as
used in distributed relational databases, where it means that tables are split column-
wise, and subsequently distributed across multiple machines.
● From a system management perspective, having a vertical distribution can help:
functions are logically and physically split across multiple machines, where each
machine is tailored to a specific group of functions. However, vertical distribution is
only one way of organizing client-server applications. In modern architectures, it is
often the distribution of the clients and the servers that counts, which we refer to as
horizontal distribution. In this type of distribution, a client or server may be
physically split up into logically equivalent parts, but each part is operating on its
own share of the complete data set, thus balancing the load.

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.

Figure 106: 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.

Specifying distributed system architecture requirements for a simulated site


i) Architecture style

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

2. What do you understand by the distributed system architectures below?


● Centralized
● Decentralized
● Hybrid
3. What are the main factors to consider when designing a network?

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.4 Tools, Equipment, Supplies and Materials


● Network tool kit
● Essential networking devices
● Computers
● Internet
● Stationery
● Instruction material

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

Learning Activities Special Instructions

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.

Types of distributed processing


Distributed processing
● Distributed processing is a phrase used to refer to a variety of computer systems that
use more than one computer (or processor) to run an application.
● More often, however, distributed processing refers to local-area networks (LANs)
designed so that a single program can run simultaneously at various sites. Most
distributed processing systems contain sophisticated software that detects idle CPUs
on the network and parcels out programs to utilize them.
● Another form of distributed processing involves distributed databases. This is
databases in which the data is stored across two or more computer systems. The
database system keeps track of where the data is so that the distributed nature of the
database is not apparent to users.

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.

Types of file systems:


Everything is stored as files in a computer system. The files can be data files or application files.
Each operating system has its own way of organizing data internally. The operating system
performs this management with the help of a program called File System.

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.

FAT File System


FAT stands for “File Allocation Table”. The file allocation table is used by the operating system to
locate files on a disk. A file may be divided into many sections and scattered around the disk due
to fragmentation. FAT keeps track of all pieces of a file. In DOS systems, FAT is stored after boot
sector. The file system has been used since the advent of PC.

Features of FAT File System


Naming convention
● FAT file system used by MS-DOS provides file name of only 8 characters long.
● FAT file system used by Windows 2000 supports long file name. The full path of
file including filename can be up to 255 characters long.
● File names can contain any character except “/ [] = , ^ ?a “”
● File names should begin with alphanumeric characters.
● File names can contain spaces and multiple periods. The characters after the last
period are treated as file extension.

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.

FAT32 File System

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.

Features of FAT32 File System


Partition size
● FAT32 increases the number of bits used to address cluster. A cluster is a set of
sectors. It reduces the size of each cluster. It supports larger disk (up to 2TB) and
better storage efficiency.

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.

NTFS File System


NTFS stands for “New Technology File System”. Windows 2000 professional fully supports
NTFS.

Features of NTFS File System


Naming Conventions
● File names can be up to 255 characters
● File names can contain most characters except “ / <> * | :
● File names are not case sensitive

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.

Bad cluster Mapping


● NTFS supports bad-cluster mapping. It means that file system detects bad clusters or
areas of disk with errors.
● If there is any data in those clusters, it is retrieved and stored on another area. The
bad clusters are marked to prevent data storage in those areas in future.

File sharing and accessing methods


i) Remote access
In computer networking, remote access technology allows someone to log in to a system as an
authorized user without being physically present at its keyboard. Remote access is commonly used
on corporate computer networks but can also be used on home networks.

ii) Data caching


Caching is a technique of storing frequently used data/information in memory, so that, when the
same data/information is needed next time, it could be directly retrieved from the memory instead
of being generated by the application.

The data will not be available in the following cases:


• If its lifetime expires,
• If the application releases its memory,
• If caching does not take place for some reason.

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.

Demonstration of distributed file sharing and access:

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.

A distributed file system provides the following types of services:


1. Storage service- Allocation and management of space on a secondary storage device thus
providing a logical view of the storage system.
2. True file service - Includes file-sharing semantics, file-caching mechanism, file replication
mechanism, concurrency control, multiple copy update protocol etc.
3. Name/Directory service- Responsible for directory related activities such as creation and
deletion of directories, adding a new file to a directory, deleting a file from a directory, changing
the name of a file, moving a file from one directory to another etc.

Desirable features of a distributed file system:


1. Transparency
- Structure transparency
Clients should not know the number or locations of file servers and the storage devices. Note:
multiple file servers provided for performance, scalability, and reliability.
- Access transparency
Both local and remote files should be accessible in the same way. The file system should
automatically locate an accessed file and transport it to the client’s site.
- Naming transparency
The name of the file should give no hint as to the location of the file. The name of the
file must not be changed when moving from one node to another.
- Replication transparency
If a file is replicated on multiple nodes, both the existence of multiple copies and their
locations should be hidden from the clients.
2. User mobility
● Automatically bring the users environment (e.g. users home directory) to the node
where the user logs in.
3. Performance
● Performance is measured as the average amount of time needed to satisfy client
requests. This time includes CPU time + time for accessing secondary storage +
network access time. It is desirable that the performance of a distributed file system
be comparable to that of a centralized file system.
4. Simplicity and ease of use
● User interface to the file system be simple and number of commands should be as
small as possible.
5. Scalability
● Growth of nodes and users should not seriously disrupt service.
6. High availability
● A distributed file system should continue to function in the face of partial failures
such as a link failure, a node failure, or a storage device crash.

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

2. File type can be represented by ____________


a) file name
b) file extension
c) file identifier
d) none of the mentioned

3. ACL stands for


a) ACCESS control list
b) ACCESS check list
c) Audit control list
d) Audit check list
4. In files, if order of operation on two or more files are similar, then operation will be

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

1. What is the difference between distributed and parallel processing?


2. What are the three major file systems in distributed processing?
3. What is data caching? When can the cached data be lost?

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.

8.3.4.4 Tools, Equipment, Supplies and Materials


● Networking tool kit
● Essential networking devices
● Computers
● Internet
● Stationery
● Instruction material
8.3.4.5 References
1. https://www.webopedia.com/TERM/P/parallel_processing.html
2. https://www.lifewire.com/remote-access-to-computer-networks-817773
3. https://www.unf.edu/~sahuja/cis6302/filesystems.html

491
8.3.5 Learning Outcome 4: Set up a Network in a Distributed Environment
8.3.5.1 Learning Activities

Learning Outcome No.4: Set up a Network in a Distributed Environment

Learning Activities Special Instructions

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

8.3.5.2 Information Sheet No. 8/LO4: Set up a Network in a Distributed Environment

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.

Selection of tools, materials and devices

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).

How Network Equipment Works


Networking equipment interconnects devices so that data can be shared between them. The layout
or topology of these connected devices describes the network's design or structure.

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.

This diagram depicts a network with various types of equipment

Figure 107:Data Network showing devices

Types of Network Equipment.


● Hubs provide a central location for attaching wires to workstations. There are two
types: passive and active.
● Switches connect devices to host computers and allow large numbers of these
devices to share a limited number of ports.
● Routers are protocol-dependent devices that connect sub-networks or divide a very
large network into smaller sub-networks.
● Repeaters use regeneration and retiming to ensure that signals are transmitted
clearly through all network segments.

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.

Product and Performance Specifications

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.

Features and Applications


When selecting network equipment, buyers may need to consider whether a device is power over
Ethernet (PoE) ready, or if it supports voice-over-Internet protocol (VoIP). Devices with full duplex
capabilities can transmit data simultaneously in both directions, and may be stackable or rack-
mountable. Product features such as alarms and LED indicators provide audible and visual
notifications to network administrators.

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.

Connection and configuration of network devices:

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".

NIC (Network Interface Card)


● A network interface card is a computer hardware component designed to allow
computers to communicate over a computer network.
495
● It is both an OSI layer 1 (physical layer) and layer 2 (data link layer) device, as it
provides physical access to a networking medium and provides a low-level
addressing system through the use of MAC addresses.
● It allows users to connect to each other either by using cables or wirelessly. Most
motherboards today come equipped with a network interface card in the form of a
controller, with the hardware built into the board itself, eliminating the need for a
standalone card.

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.

Figure 110:How a bridge works

Wireless Access Point


● A wireless access point (WAP or AP) is a device that allows wireless
communication devices to connect to a wireless network using Wi-Fi, Bluetooth or
related standards.
● The WAP usually connects to a wired network, and can relay data between the
wireless devices (such as computers or printers) and wired devices on the network.
● A typical corporate use involves attaching several WAPs to a wired network and
then providing wireless access to the office Local Area Network. Within the range of
the WAPs, the wireless end user has a full network connection with the benefit of
mobility. In this instance, the WAP functions as a gateway for clients to access the
wired network.

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.

Figure 111:How a Wireless Access Point works

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.

Figure 113: How a firewall works

Installation and configuration of network software:


Network Server Setup: Installation and Configuration
Following is an overview of a typical installation of the network operating system (NOS) Windows
Server 2008 and configuration of your server. Although the details vary, the overall process for
other NOS is similar.

Installing a Network Operating System


The best way to install Windows Server 2008 is to perform a new install directly from the DVD
installation media. Although upgrade installs are possible, your server will be more stable if you
perform a new install. (For this reason, most network administrators avoid upgrading to Windows
Server 2008 until it’s time to replace the server hardware.)

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.

Phase 1: Collecting Information


In the first installation phase, the setup program asks for the preliminary information that it needs
to begin the installation.

A setup wizard prompts you for the following information:


· Language: Select your language, time-zone, and keyboard type.
· Product Key: Enter the 25-character product key that came with the installation media. If
setup says you entered an invalid product key, double-check it carefully. You probably just typed
the key incorrectly.
499
· Operating System Type: The setup program lets you select Windows Server 2008 Standard
Edition or Core. Choose Standard Edition to install the full server operating system; choose Core
if you want to install the new text-only version.
· License Agreement: The official license agreement is displayed. You have to agree to its
terms in order to proceed.
· Install Type: Choose an Upgrade or Clean Install type.
· Disk Location: Choose the partition in which you want to install Windows.
· Upgrade to NTFS: If you want to upgrade a FAT32 system to NTFS, you’ll need to say so
now.

Phase 2: Installing Windows


In this phase, Windows setup begins the actual process of installing Windows.

The following steps are performed in sequence:


1. Copying Files: Compressed versions of the installation files are copied to the server
computer.
2. Expanding Files: The compressed installation files are expanded.
3. Installing Features: Windows server features are installed.
4. Installing Updates: The setup program checks Microsoft’s website and downloads any
critical updates to the operating system.
5. Completing Installation: When the updates are installed, the setup program reboots so it can
complete the installation.

Configuring Your Server


After you’ve installed Windows Server 2008, the computer automatically reboots, and you’re
presented with the Initial Configuration Tasks Wizard. This wizard guides you through the most
important initial tasks for configuring your new server.

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.

Testing the network:

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.

Testing Network Connectivity:


To test connectivity with a host on a network or internetwork, use the PING utility.

● Open a command prompt


● For Windows XP: Click Start, select Run, type cmd and press Enter or select OK
button
● For higher versions of Windows: 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
PING servername
or
PING serverIP
where servername is the name of the server or serverIP is the IP address of the
server with which you want to communicate.
● A response of four lines, each with a time (TTL=) response indicates the server is
reachable.
● A response of Bad IP address indicates the name or IP address is incorrect or
unknown.
● A response of Request timed out indicates the server is known but is not able to
respond within a reasonable time.

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.4 Tools, Equipment, Supplies and Materials


● Computers
● Networking toolkit
● Essential network devices
● Stationery
● Internet
504
● Instruction material

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

Learning Activities Special Instructions

1.1 OSI Model is outlined Activities may be carried out in groups or as


1.2 Data communication components are individual
explained
1.3 Network IP address classes are
demonstrated
8.3.6.2 Information Sheet No. 8/LO5: 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.

Figure 114: OSI model layers

506
Functions of different OSI model layers

1. Physical Layer (Layer 1):


The lowest layer of the OSI reference model is the physical layer. It is responsible for the actual
physical connection between the devices.
The physical layer contains information in the form of bits. It is responsible for transmitting
individual bits from one node to the next.
When receiving data, this layer will get the signal received and convert it into 0s and 1s and send
them to the Data Link layer, which will put the frame back together.

The functions of the physical layer are:


1. Bit synchronization: The physical layer provides the synchronization of the bits by
providing a clock. This clock controls both sender and receiver thus providing
synchronization at bit level.
2. Bit rate control: The Physical layer also defines the transmission rate i.e. the number of
bits sent per second.
3. Physical topologies: Physical layer specifies the way in which the different, devices/nodes
are arranged in a network i.e. bus, star or mesh topology.
4. Transmission mode: Physical layer also defines the way in which the data flows between
the two connected devices. The various transmission modes possible are: Simplex, half-
duplex and full-duplex.
Hub, Repeater, Modem, Cables are Physical Layer devices.
Network Layer, Data Link Layer and Physical Layer are also known as Lower Layers or
Hardware Layers.

2. Data Link Layer (DLL) (Layer 2):


The data link layer is responsible for the node to node delivery of the message. The main function
of this layer is to make sure data transfer is error-free from one node to another, over the physical
layer. When a packet arrives in a network, it is the responsibility of DLL to transmit it to the Host
using its MAC address.

Data Link Layer is divided into two sub layers:


1. Logical Link Control (LLC)
2. Media Access Control (MAC)

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.

The functions of the data Link layer are:


1. Framing: Framing is a function of the data link layer. It provides a way for a sender to
transmit a set of bits that are meaningful to the receiver. This can be accomplished by
attaching special bit patterns to the beginning and end of the frame.
2. Physical addressing: After creating frames, Data link layer adds physical addresses (MAC
address) of sender and/or receiver in the header of each frame.
3. Error control: Data link layer provides the mechanism of error control in which it detects
and retransmits damaged or lost frames.
4. Flow Control: The data rate must be constant on both sides else the data may get corrupted
thus, flow control coordinates that amount of data that can be sent before receiving
acknowledgement.
5. Access control: When a single communication channel is shared by multiple devices, MAC
sub-layer of data link layer helps to determine which device has control over the channel at
a given time.

• Packet in Data Link layer is referred as Frame.


• Data Link layer is handled by the NIC (Network Interface Card) and device drivers of host
machines.
• Switch & Bridge are Data Link Layer devices.

3. Network Layer (Layer 3):


Network layer works for the transmission of data from one host to the other located in different
networks. It also takes care of packet routing i.e. selection of the shortest path to transmit the
packet, from the number of routes available. The sender & receiver’s IP address are placed in the
header by the network layer.

The functions of the Network layer are:


● Routing: The network layer protocols determine which route is suitable from source
to destination. This function of network layer is known as routing.
● Logical Addressing: In order to identify each device on internetwork uniquely,
network layer defines an addressing scheme. The sender & receiver’s IP address are
placed in the header by network layer. Such an address distinguishes each device
uniquely and universally.
● Network layer is implemented by networking devices such as routers.

4. Transport Layer (Layer 4):


Transport layer provides services to application layer and takes services from network layer. The
data in the transport layer is referred to as Segments. It is responsible for the End to End Delivery

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.

The services provided by the transport layer:


Connection Oriented Service: It is a three-phase process which include
– Connection Establishment
– Data Transfer
– Termination / disconnection

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.

Data in the Transport Layer is called Segments.

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.

Transport Layer is called as Heart of OSI model.

5. Session Layer (Layer 5):


This layer is responsible for establishment of connection, maintenance of sessions, authentication
and also ensures security.

The functions of the session layer are:


● Session establishment, maintenance and termination: The layer allows the two
processes to establish, use and terminate a connection.
● Synchronization: This layer allows a process to add checkpoints which are
considered as synchronization points into the data. These synchronization point help
to identify the error so that the data is re-synchronized properly, and ends of the
messages are not cut prematurely and data loss is avoided.
● Dialog Controller: The session layer allows two systems to start communication
with each other in half-duplex or full-duplex.
All the below 3 layers (including Session Layer) are integrated as a single layer in the TCP/IP
model as “Application Layer”.

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.

6. Presentation Layer (Layer 6):


Presentation layer is also called the Translation layer. The data from the application layer is
extracted here and manipulated as per the required format to transmit over the network.

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.

7. Application Layer (Layer 7):


At the very top of the OSI Reference Model stack of layers, we find Application layer which is
implemented by the network applications. These applications produce the data, which has to be
transferred over the network. This layer also serves as a window for the application services to
access the network and for displaying the received information to the user.

Example: Application – Browsers, Skype Messenger etc.


Application Layer is also called as Desktop Layer.

The functions of the Application layer are:


● Network Virtual Terminal
● FTAM-File transfer access and management
● Mail Services
● Directory Services

OSI layer Protocols Illustration


The OSI protocol stack works on a hierarchical form, from the hardware physical layer to the
software application layer.

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.

Data communication components:

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.

Network IP Address classes:

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 and Private IP Address:

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.

● To allow direct access to a local device which is assigned a private IP address, a


Network Address Translator (NAT) should be used.

Automatic Private IP Address (APIPA)


● The Windows function that provides DHCP autoconfiguration addressing. APIPA
assigns a class B IP address from 169.254.0.0 to 169.254.255.255 to the client when
a DHCP server is either permanently or temporarily unavailable.
● Designed for small non-routable networks, if a DHCP server becomes available
later, the APIPA address is replaced with one from the DHCP server. For example,
when a Windows Vista machine starts up, it waits only six seconds to find a DHCP
server before assigning an IP from the APIPA range. It then continues to look for a
DHCP server.

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.

8.3.6.4 Tools, Equipment, Supplies and Materials

● 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

Learning Activities Special Instructions

1.1 Troubleshooting is explained. Activities may be carried out in groups or as


1.2 Troubleshooting tools are demonstrated. individual
1.3 Troubleshooting of a network is done as per
IEEE standards
·

8.3.7.2 Information Sheet No.8/LO6: 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.

Network Troubleshooting Best Practices


To make troubleshooting as efficient and painless as possible, it’s also important to have some best
practices in place. As you work through the steps to try to solve network issues, following these
network troubleshooting best practices can help streamline the process and avoid unnecessary or
redundant efforts.

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.

Figure 116:Tracert/traceroute utility

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.

Figure 4: Nslookup utility

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

Figure 119:Mtr utility

Demonstration of network troubleshooting as per IEEE standard

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

Figure 120: Networking Issues resolution


525
a. Network Issues
i) Network reachability is the network state which illustrates that the clients are unable to connect
to the servers. This is the most popular issues in the network systems. There are two kinds of
reachability issues, containing transient and non-transient unreachability.

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

9.2 Performance Standard


1. Demonstrated installation of Python
2. Demonstrated Python syntax
3. Demonstrate data types in Python
4. Demonstrated use of control structures in Python
5. Demonstrated use of functions in Python
6. Demonstrated use ofObject Oriented Python
7. Demonstrated use of scientific modules
8. Demonstrated machine learning

9.3 Learning Outcomes


9.3.1 List of Learning Outcomes
1. Understand Artificial Intelligence fundamentals.
2. Understand problem solving techniques.
3. Understand Python programming environment.
4. Develop 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

14.3 Artificial Intelligence is defined Activities may be carried out in


14.4 The history of Artificial Intelligence is explained groups or as individual
14.5 Foundations of Artificial Intelligence are explained
14.6 Applications of Artificial Intelligence are explained
14.7 Intelligence agents are explained
14.8 Artificial Intelligence applications in real life are
recognized

9.3.2.2 Information Sheet No 9/LO1: Understand Artificial Intelligence fundamentals

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.

Artificial Intelligence Basic Concepts


What is Intelligence?
The ability of a system to calculate, reason, perceive relationships and analogies, learn from
experience, store and retrieve information from memory, solve problems, comprehend complex
ideas, use natural language fluently, classify, generalize, and adapt new situations.

Definition of artificial intelligence


AI is the theory and development of computer systems able to perform tasks normally requiring
human intelligence, such as visual perception, speech recognition, decision-making, and translation
between languages.

History of artificial intelligence (Milestone since 1950s)


Year Milestone/Innovation

John McCarthy coined the term Artificial Intelligence. Demonstration of the first
1956
running AI program at Carnegie Mellon University.

1958 John McCarthy invents LISP programming language for AI.

531
Danny Bob row’s dissertation at MIT showed that computers can understand
1964
natural language well enough to solve algebra word problems correctly.

Joseph Weizenbaum at MIT built ELIZA, an interactive problem that carries on a


1965
dialogue in English.

Scientists at Stanford Research Institute Developed Shakey, a robot, equipped


1969
with locomotion, perception, and problem solving.

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.

Major advances in all areas of AI −


• Significant demonstrations in machine learning
• Case-based reasoning
• Multi-agent planning
1990 • Scheduling
• Data mining, Web Crawler
• natural language understanding and translation
• Vision, Virtual Reality
• Games

The Deep Blue Chess Program beats the then world chess champion, Garry
1997
Kasparov.

Interactive robot pets become commercially available. MIT displays Kismet, a


2000 robot with a face that expresses emotions. The robot Nomad explores remote
regions of Antarctica and locates meteorites.

Foundations of Artificial Intelligence

Figure 121: AI related fields


532
● Philosophy: Logic, methods of reasoning, mind as physical system foundations of
learning, language, rationality
● Mathematics: Formal representation and proof algorithms, computation,
(un)decidability, (in)tractability, probability
● Economics: utility, decision theory
● Neuroscience: physical substrate for mental activity
● Psychology: phenomena of perception and motor control, experimental techniques
● Computer engineering: building fast computers
● Control theory: design systems that maximize an objective function over time
● Linguistics: knowledge representation, grammar

Applications of Artificial Intelligence


Machine Learning
Machine learning (ML) is the science of empowering machines to make decisions without
human intervention. This sub-discipline forms the backbone of
AI, enabling computers to learn and interpret patterns in images, sounds, and structured data.

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.

Natural Language Processing


Natural language processing (NLP) is the automatic extraction, analysis, and generation of human
language. NLP algorithms parse sentences in various ways (e.g., splitting by word, splitting by letter,
reading both left-to-right and right-to-left, etc.) to automatically draw inferences about the writer’s
meaning and intent.

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

What are Sensors, Actuators and Effectors in agents

Figure 122:Intelligence agent

• 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.

PEAS Representation of agents’ operations


PEAS is a type of model on which an AI agent works upon.
o P: Performance measure
o E: Environment
o A: Actuators
o S: Sensors

PEAS for self-driving cars:

• Performance: Safety, time, legal drive, comfort


• Environment: Roads, other vehicles, road signs, pedestrian
• Actuators: Steering, accelerator, brake, signal, horn
• Sensors: Camera, GPS, speedometer, odometer, accelerometer

534
Agent Performance Environment Actuators Sensors
measure

Medical o Healthy o Patient o Tests o Keyboard


Diagnose patient o Hospital o Treatments (Entry of symptoms)
o Minimized o Staff
cost

Vacuum o Cleanness o Room o Wheels o Camera


Cleaner o Efficiency o Table o Brushes o Dirt detection sensor
o Battery life o Wood floor o Vacuum o Cliff sensor
o Security o Carpet Extractor o Bump Sensor
o Various o Infrared Wall Sensor
obstacles

Part- o Percentage o Conveyor belt o Jointed o Camera


picking of parts in correct with parts, Arms o Joint angle sensors.
Robot bins. o Bins o Hand

Example of Agents with their PEAS representation


Artificial Intelligence applications in real life

AI has been dominant in various fields such as –


• Business – AI has wide use in including consumer behavior forecasting and product
recommendations, fraud detection, personalized advertising and marketing messaging and
customer service via telephone or chatbots
• Education: AI methods can be employed to design and facilitate interactive learning
environments that would support learning by doing and to design and implement tutoring
systems by adapting instructions with respect to the students' knowledge state
• Health care- AI is being used or trialed for a variety of healthcare and research purposes,
including detection of disease, management of chronic conditions such as cancer, delivery
of health services, and drug discovery.
• Social media: Marketers use pictures to boost the rates of engagement. Image recognition is
used by marketers to determine the behavior of the customer. Facebook uses advanced
machine learning to do everything from serve its users content to recognize their faces in
photos to target users with advertising. Instagram uses AI to identify visuals.
• Gaming − AI plays crucial role in strategic games such as chess, poker, tic-tac-toe, etc.,
where machine can think of large number of possible positions based on heuristic knowledge.
• Intelligent Robots − Robots are able to perform the tasks given by a human. They have
sensors to detect physical data from the real world such as light, heat, temperature,
movement, sound, bump, and pressure.

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.4 Tools, Equipment, Supplies and Materials


● Computer
● Internet
● Stationery
● Instruction material

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

2.1 Logical operators are outlined. Activities may be carried out in


2.2 Propositional and Predicate logic are explained. groups or as individual
2.3 Types of inferencing are explained.
2.4 Machine Learning is defined.
2.5 Types of Machine Learning are explained.
2.6 Applications of different types of inferencing are
recognized

9.3.3.2 Information Sheet No 9/LO2: Understand problem solving techniques

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.

Mathematical logics can be broadly categorized into three categories.


• Propositional Logic − Propositional Logic is concerned with statements to which the truth
values, "true" and "false", can be assigned. The purpose is to analyse these statements either
individually or in a composite manner.
• Predicate Logic − Predicate Logic deals with predicates, which are propositions containing
variables. A predicate represents an expression of one or more variables.
• Rules of Inference − to deduce new statements from the statements whose truth that we
already know, Rules of Inference are used. Rules of Inference provide the templates or
guidelines for constructing valid arguments from the statements that we already have.

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.

Some examples of Propositions are given below −


• "Man is Mortal", it returns truth value TRUE
• "12 + 9 = 3 – 2", it returns truth value FALSE

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

True True True

539
True False True

False True True

False False False


AND ( ∧) − The AND operation of two propositions A and B (written as A∧B) is true if both the
propositional variable A and B is true.
The truth table is as follows −
A B A∧B

True True True

True False False

False True False

False False False


Negation ( ¬) − The negation of a proposition A (written as ¬A) is false when A is true and is true
when A is false.
The truth table is as follows −
A ¬A

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

True True True

True False False

False True True

False False True


If and only if ( ⇔) − A⇔B is bi-conditional logical connective which is true when p and q are
same, i.e. both are false or both are true.
The truth table is as follows −
A B A⇔B

540
True True True

True False False

False True False

False False True


Predicate Logic
Predicate Logic deals with predicates, which are propositions containing variables.

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.

The following are some examples of predicates −


• Let E(x, y) denote "x = y"
• Let X(a, b, c) denote "a + b + c = 0"
• Let M(x, y) denote "x is married to y"

Well Formed Formula


Well Formed Formula (wff) is a predicate holding any of the following −
• All propositional constants and propositional variables are wffs
• If x is a variable and Y is a wff, ∀xY and ∃xY are also wff
• Truth value and false values are wffs
• Each atomic formula is a wff
• All connectives connecting wffs are wffs

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.

Following are some terminologies related to inference rules:


o Implication: It is one of the logical connectives which can be represented as P → Q. It is a
Boolean expression.
o Converse: The converse of implication, which means the right-hand side proposition goes
to the left-hand side and vice-versa. It can be written as Q → P.
o Contrapositive: The negation of converse is termed as contrapositive, and it can be
represented as ¬ Q → ¬ P.
o Inverse: The negation of implication is called inverse. It can be represented as ¬ P → ¬ Q.
From the above term some of the compound statements are equivalent to each other, which we can
prove using truth table:

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.

Types of Inference rules and Examples


1. Modus Ponens:
The Modus Ponens rule is one of the most important rules of inference, and it states that if P and P
→ Q is true, then we can infer that Q will be true. It can be represented as:

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:

Statement-1: "If I am sleepy then I go to bed" ==> P→ Q


Statement-2: "I do not go to the bed."==> ~Q
Statement-3: Which infers that "I am not sleepy" => ~P

Proof by Truth table:

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

Proof by truth table:

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 (ML)


• Definitions
✓ Learning in AI
Learning is a process that improves the knowledge of an AI program by making observations
about its environment

✓ 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.

Types of Machine learning algorithms


There are four types of Machine Learning algorithms:
i) Supervised learning algorithms
ii) Unsupervised learning algorithms
iii) Semi supervised learning algorithms
iv) Reinforcement machine learning algorithms

i) Supervised learning algorithms


✓ These are Machine learning algorithms that learn from input/output pairs
✓ They are “supervised” because a “teacher” provides supervision to the algorithms in
the form of the desired outputs for each example that they learn from.

ii) Unsupervised learning algorithms


✓ These are used when the information used to train is neither classified nor labeled.
Unsupervised learning studies how systems can infer a function to describe a hidden
structure from unlabeled data.
✓ The system doesn’t tell out the right output, but it explores the data and can draw
inferences from datasets to describe hidden structures from unlabeled data.
iii) Semi-supervised machine learning algorithms
✓ They fall in between supervised and unsupervised learning, since they use both labeled
and unlabeled data for training – usually a small amount of labeled data and a large amount
of unlabeled data.
✓ The systems that use this method are able to considerably improve learning accuracy.
✓ Usually, semi-supervised learning is chosen when the acquired labeled data requires
skilled and relevant resources in order to train it / learn from it.

iv) Reinforcement machine learning algorithms


✓ It is a learning method that interacts with its environment by producing actions and
discovers errors or rewards.
✓ This method allows machines and software agents to automatically determine the ideal
behavior within a specific context in order to maximize its performance.
✓ Simple reward feedback is required for the agent to learn which action is best; this is
known as the reinforcement signal.

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.4 Tools, Equipment, Supplies and Materials


• Computer
• Internet
• Stationery
• Instruction material

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

3.1 Installation of Python is demonstrated. Activities may be carried out in


3.2 Python syntax is demonstrated. groups or as individual
3.3 Data types in Python are demonstrated.
3.4 Control structures in Python are demonstrated.
3.5 Functions in python are demonstrated
3.6 Object Oriented Python is demonstrated.
3.7 Scientific Modules in Python are demonstrated.

9.3.4.2 Information sheet No 9/LO3: Understand Python programming environment

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.

Step 3: You can see Python installing at this point.

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.

This is a program with single space indentation.

This is a program with single tab 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.

Python has the following standard or built-in data types:

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 {}.

Control Structures in Python

Decision Control Structures


Decision making statements in programming languages decides the direction of flow of program
execution. Decision making statements available in python are:
• if statement
• if-else statements
• nested if statements
• if-elif ladder

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:

# python program to illustrate If statement

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:

# python program to illustrate If else statement


#!/usr/bin/python

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:

Python program to illustrate nested If statement

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: -

Repetition Control Structures


Repetition statements are called loops, and are used to repeat the same code multiple times in
succession. Python has two types of loops:
Condition-Controlled and Count-Controlled

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.

The for loop


The for loop as a Count-Controlled loop iterates a specific number of times.
Basic syntax:

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.

Procedures and functions in Python

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:

Example 3 - Use two arguments


The following program first creates a procedure which takes a name and gender and then correctl
y creates the start of a story using the correct pronouns, he or she. This procedure is used later wh
en it is called using the information which the user inputs.

Output

562
Output:

Parameters and Arguments


A parameter is a variable in a method definition. When a method is called, the arguments are the
data you pass into the method's parameters.
Parameter is variable in the declaration of function. Argument is the actual value of this variable
that gets passed to function.
Types of arguments
Arguments are part of a function call. There are four different kinds of arguments:
• Positional: Arguments without a name.
Each is matched to the positional-or-keyword or positional-only parameter with the same index, or
to the var-positional parameter if there is no matching index (or, if there is no var-positional
parameter, it's an error if there is no match).
• Keyword: Arguments with a name.
Each is matched to the positional-or-keyword or keyword-only parameter with the same name, or
to the var-keyword parameter if there is no matching name (or, if there is no var-keyword
parameter, it's an error if there is no match).
• Packed positional: An iterator preceded by *.
The iterator is unpacked, and the values treated as separate positional arguments.
• Packed keyword: A mapping preceded by **.
The mapping is iterated, and the key-value pairs treated as separate keyword arguments.
There is no direct connection between parameters with a default value and keyword arguments.
You can pass keyword arguments to parameters without default values, or positional arguments
to parameters with them.
563
Similarly, there is no direct connection between a *args in a function call and a *args in a
function definition. A packed positional argument with three values might be unpacked into the
last three positional-or-keyword parameters, or all three may be extended to the last two normal
positional arguments and passed together to the var-positional, or its first two values may be
unpacked into positional-or-keyword parameters and the last into the var-positional.

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).

With the same function from above:


>>> a = [2,3,4]
>>> d = {'foo': 5, 'baz': 6}
>>> func(1, *a, **d)
1 2 (3, 4) 5 2 {'baz': 6}
>>> func(1, 2, 3, 4, foo=5, baz=6)
1 2 (3, 4) 5 2 {'baz': 6}
In the first call, the a iterable is unpacked into three positional arguments, and the **d is unpacked
into keyword arguments named "foo" and "baz". So, this has the exact same effect as the second
call.

Object Oriented Python


Object-oriented Programming, or OOP for short, is a programming paradigm which provides a
means of structuring programs so that properties and behaviors are bundled into individual objects.

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..

How to Define a Class in Python

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.)

Python Objects (Instances)


While the class is the blueprint, an instance is a copy of the class with actual values, literally an
object belonging to a specific class.

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.

What do you think the type of a class instance is?

A more detailed example

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

Scientific Modules (Libraries) in Python


NumPy
NumPy is the fundamental package for scientific computing with Python. It contains among other
things:

• a powerful N-dimensional array object


• sophisticated (broadcasting) functions
• tools for integrating C/C++ and Fortran code
• useful linear algebra, Fourier transform, and random number capabilities

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.

Demonstrating Pandas basics

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.

Creating a Series in Pandas

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.4 Tools, Equipment, Supplies and Materials


• Computer
572
• Python IDE
• Stationery
• Instruction material
• Internet

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

4.1 Sci-Kit Learn is explained. Activities may be carried out in


4.2 Machine Learning with K-Nearest Neighbours is groups or as individual
demonstrated.
4.3 Machine Learning with Naïve Bayes Algorithm is
demonstrated.

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

If it successfully imports (no errors), then sklearn is installed correctly.

Machine Learning with K-Nearest Neighbours

The k-nearest neighbors (KNN) algorithm is a simple, easy-to-implement supervised machine


learning algorithm that can be used to solve both classification and regression problems.

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

The KNN Algorithm


1. Load the data
2. Initialize K to your chosen number of neighbors
3. For each example in the data

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

Example: Unsupervised Nearest Neighbors


NearestNeighbors implements unsupervised nearest neighbors learning. It acts as a uniform
interface to three different nearest neighbors algorithms: BallTree, KDTree, and a brute-force
algorithm based on routines in sklearn.metrics.pairwise. The choice of neighbors search algorithm
is controlled through the keyword 'algorithm', which must be one
of ['auto', 'ball_tree', 'kd_tree', 'brute']. When the default value 'auto' is passed, the algorithm
attempts to determine the best approach from the training data.

For the simple task of finding the nearest neighbors between two sets of data, the unsupervised
algorithms within sklearn.neighbors can be used:

>>> from sklearn.neighbors import NearestNeighbors


>>> import numpy as np
>>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
>>> nbrs = NearestNeighbors(n_neighbors=2, algorithm='ball_tree').fit(X)
>>> distances, indices = nbrs.kneighbors(X)
>>> indices

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()

array([[1., 1., 0., 0., 0., 0.],


[1., 1., 0., 0., 0., 0.],
[0., 1., 1., 0., 0., 0.],
[0., 0., 0., 1., 1., 0.],
[0., 0., 0., 1., 1., 0.],
[0., 0., 0., 0., 1., 1.]])

Machine Learning with Naïve Bayes Algorithm


Naive Bayes classifiers are a collection of classification algorithms based on Bayes’
Theorem. It is not a single algorithm but a family of algorithms where all of them share a
common principle, i.e. every pair of features being classified is independent of each other.

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

0 Rainy Hot High False No

1 Rainy Hot High True No

2 Overcast Hot High False Yes

3 Sunny Mild High False Yes

4 Sunny Cool Normal False Yes

5 Sunny Cool Normal True No

6 Overcast Cool Normal True Yes

7 Rainy Mild High False No

8 Rainy Cool Normal False Yes

9 Sunny Mild Normal False Yes

10 Rainy Mild Normal True Yes

577
OUTLOOK TEMPERATURE HUMIDITY WINDY PLAY GOLF

11 Overcast Mild High True Yes

12 Overcast Hot Normal False Yes

13 Sunny Mild High True No

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

contribution to the outcome.


With relation to our dataset, this concept can be understood as:
• We assume that no pair of features are dependent. For example, the temperature
being ‘Hot’ has nothing to do with the humidity or the outlook being ‘Rainy’ has no
effect on the winds. Hence, the features are assumed to be independent.
• Secondly, each feature is given the same weight(or importance). For example,
knowing only temperature and humidity alone can’t predict the outcome accurately.
None of the attributes is irrelevant and assumed to be contributing equally to the
outcome.

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.

Example :The sklearn.naive_bayes.GaussianNB library is needed to implement the library.

>>> import numpy as np


>>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
>>> Y = np.array([1, 1, 1, 2, 2, 2])
>>> from sklearn.naive_bayes import GaussianNB
>>> clf = GaussianNB()
>>> clf.fit(X, Y)
GaussianNB()

578
>>> print(clf.predict([[-0.8, -1]]))

[1]

>>> clf_pf = GaussianNB()


>>> clf_pf.partial_fit(X, Y, np.unique(Y))
GaussianNB()
>>> print(clf_pf.predict([[-0.8, -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.

9.3.5.4 Tools, Equipment, Supplies and Materials

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.

10.2 Performance Standard


1. Wrote an algorithm
2. Demonstrated array operations
3. Demonstrated basic operations for the various linked lists
4. Demonstrated basic operations in stacks and queues
5. Demonstrated search techniques
6. Demonstrated sorting algorithms

10.3 Learning Outcomes


10.3.1 List of Learning Outcomes
1. Understand fundamental principles of algorithms
2. Understand fundamental concepts of data structures
3. Understand Linked lists
4. Understand Stacks and Queues
5. Understand Search Techniques
6. Understand Sorting Techniques

581
10.3.2 Learning outcome 1: Understand fundamental principles of algorithms
10.3.2.1 Learning activities

Learning Outcome 1: Understand fundamental principles of algorithms


Learning Activities Special Instructions

1.1 Algorithm is defined Activities may be carried out in


1.2 Characteristics of an Algorithm are explained groups or as individual
1.3 Algorithm writing is demonstrated
1.4 Algorithm Analysis is explained
1.5 Complexities of algorithms are explained
1.6 Greedy algorithms are outlined
1.7 Divide and conquer is demonstrated

10.3.2.2 Information Sheet No 10/LO1: Understand fundamental principles of algorithms

Introduction

This learning outcome covers defining an algorithm, explaining characteristics of an


algorithm, analyzing algorithms, explaining their complexities, outlining greedy algorithms
and demonstrating divide and conquer algorithms.

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

Principles of algorithm writing


1. Experiment with examples.
2. Simplify the problem.
3. Look for similar problems
4. Delegate the work.
5. Design according to the runtime.

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.

Illustration: Counting coins


Given a value V, if we want to make change for V cents, and we have infinite supply of each of C
= { C1, C2, .. , Cm} valued coins, what is the minimum number of coins to make the change?
Examples:
Input: coins[] = {25, 10, 5}, V = 30
Output: Minimum 2 coins required
We can use one coin of 25 cents and one of 5 cents

Input: coins[] = {9, 6, 5, 1}, V = 11


Output: Minimum 2 coins required
We can use one coin of 6 cents and 1 coin of 5 cents
Most networking algorithms use the greedy approach. Here is a list of few of them −
• Travelling Salesman Problem
• Knapsack Problem
• Job Scheduling Problem
• Activity Selection Problem
• Water Connection Problem
• Fitting Shelves Problem

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.

Pros and cons of Divide and Conquer Approach


Divide and conquer approach supports parallelism as sub-problems are independent. Hence, an
algorithm, which is designed using this technique, can run on the multiprocessor system or in
different machines simultaneously.

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.

Application of Divide and Conquer Approach


Following are some problems, which are solved using divide and conquer approach.

• Finding the maximum and minimum of a sequence of numbers


• Merge sort
• Binary search
Example:
To find the maximum and minimum element in a given array.

Input: { 70, 250, 50, 80, 140, 12, 14 }


Output: The minimum number in a given array is : 12
The maximum number in a given array is : 250

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.

if(index >= l-2)


{
if(a[index]>a[index+1])
{
// (a[index]
// Now, we can say that the last element will be maximum in a given array.
}
else
{
//(a[index+1]
// Now, we can say that last element will be maximum in a given array.
}
}

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.

// Recursive call for the right side in the given array.


min = DAC_Min(a, index+1, l);

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];

// Here min will be minimum in a given array.


else
return min;

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.

10.3.2.4 Tools, Equipment, Supplies and Materials


• Computers
• Internet
• Stationery
• C++ compiler
• Instruction material

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

Learning Activities Special Instructions

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++

10.3.3.2 Information Sheet No 10/LO2:Understand fundamental concepts of data structures


Introduction

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++.

Key concepts in data structures


✓ Data
Data is any set of characters that is gathered and translated for some purpose, usually analysis. It
can be any character, including text and numbers, pictures, sound, or video. If data is not put into
context, it doesn't do anything to a human or computer.

✓ 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.

✓ At the given index


In this scenario, we are given the exact location (index) of an array where a new data element
(value) needs to be inserted. First we shall check if the array is full, if it is not, then we shall move
all data elements from that location one step downward. This will make room for a new data
element.

✓ After the given index


In this scenario we are given a location (index) of an array after which a new data element (value)
has to be inserted. Only the seek process varies, the rest of the activities are the same

✓ Before the given index


In this scenario we are given a location (index) of an array before which a new data element (value)
has to be inserted. This time we seek till index-1 i.e., one location ahead of given index, rest of the
activities are same

Array delete, search and update


• Delete refers to removing an existing element from the array and re-organizing all elements of an
array
• Search can be performed on an array element based on its value or its index
• Update operation refers to updating an existing element from the array at a given index

Demonstration of array operations


Arrays can be declared in various ways in different languages. For illustration, let's take C array
declaration.

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 ];

Array declaration by specifying the size


This is called a single-dimension array. The arraySize must be an integer constant greater than zero
and type can be any valid C++ data type. For example, to declare a 10-element array called balance
of type double, use this statement −
double balance[10];

Elements of an Array and How to access them?


An individual data in an array is the element of the array. You can access elements of an array by
using indices.
Suppose you declared an array mark as above. The first element is mark[0], the second element is
mark[1] and so on. The array starts with 0 index.

How to initialize an array in C++ programming


Array declaration by specifying size and initializing elements
int mark[5] = {19, 10, 8, 17, 9};

Array declaration by initializing elements


int mark[] = {19, 10, 8, 17, 9};
Here,
mark[0] is equal to 19; mark[1] is equal to 10; mark[2] is equal to 8; mark[3]
is equal to 17; mark[4] is equal to 9

How to insert and print array elements


int mark[5] = {19, 10, 8, 17, 9}

// change 4th element to 9


591
mark[3] = 9;
// take input from the user and insert in third element
cin >> mark[2];
// take input from the user and insert in (i+1)th element
cin >> mark[i];
// print first element of the array
cout << mark[0];
// print ith element of the array
cout >> mark[i-1];

Example: C++ Array


C++ program to store and calculate the sum of 5 numbers entered by the user using arrays

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;
}

How to Insert an element at a specific position in an Array in C++

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:

// C++ Program to Insert an element


// at a specific position in an Array

#include <iostream>
using namespace std;

// Function to insert x in arr at position pos


int* insertX(int n, int arr[],
int x, int pos)
{
int i;

// increase the size by 1


n++;

// shift elements forward

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;

// initial array of size 10


for (i = 0; i < 10; i++)
arr[i] = i + 1;

// print the original array


for (i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;

// element to be inserted
x = 50;

// position at which element is to be inserted


pos = 5;

// Insert x at pos
insertX(n, arr, x, pos);

// print the updated array


for (i = 0; i < n + 1; i++)
cout << arr[i] << " ";
cout << endl;

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

Deleting an Element from an Array in C++


There are 2 basic ways of deleting an element
1. Shifting Elements
2. Without Shifting Elements

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

cout<<"Enter 5 elements\n"; //2


for(int i=0;i<5;i++)
{
cin>>arr[i];
}

int ind, maxsize=5; //3

cout<<"Enter index to be deleted\n"; //4


cin>>ind;

if(ind<0 || ind>=maxsize) //5


{
cout<<"Invalid\n";
}
else
{
for(int i=ind;i<=maxsize-1;i++)
{
arr[i]=arr[i+1];
}
arr[maxsize-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

Simple Searching In Array Example


/*##Simple Searching In Array* C++ Example*/
/*##Searching Programs in C++, Array Example Programs in C++*/

// 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];
}

cout<<"Enter the key\n";


cin>>search_key;

/* Simple Search with Position */


for (i = 0; i < ARRAY_SIZE; i++)
{
if(numbers[i] == search_key)
{
cout<<"Search Element Found . Position Is :"<< (i+1) <<" \n";
break;
}
if(i == ARRAY_SIZE - 1)
597
{
cout<<"Search Element is not in Array.\n";
}
}

Sample 1:

Enter the Number : 1 : 45


Enter the Number : 2 : 56
Enter the Number : 3 : 67
Enter the Number : 4 : 78
Enter the Number : 5 : 34
Enter the key
78
Search Element Found . Position Is : 4

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.

10.3.3.4 Tools, Equipment, Supplies and Material


• Computers
• Internet
• Stationery
• C++ compiler
• Instruction material

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

Learning Activities Special Instructions

3.6 Linked lists are explained Activities may be


3.7 Doubly linked lists are explained. carried out in groups or
3.8 Circular linked lists are explained. as individual
3.4 Basic operations for the various linked lists are demonstrated
using C++
·

10.3.4.2 Information Sheet No 10/LO3: Understand Linked lists


Introduction

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 lists representation

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

Types of linked lists


There are three common types of Linked List
1. Singly Linked List
2. Doubly Linked List
3. Circular Linked List

Basic operations in a linked list


1. Insertion − Adds an element at the beginning of the list.
2. Deletion − Deletes an element at the beginning of the list.
3. Insert Last − Adds an element at the end of the list.
4. Delete Last − Deletes an element from the end of the list

Doubly linked lists


✓ Representation
We add a pointer to the previous node in a doubly-linked list.
Thus, we can go in either direction: forward or backward.

✓ Basic operations

• add_front: Adds a new node in the beginning of list


• add_after: Adds a new node after another node
• add_before: Adds a new node before another node
• add_end: Adds a new node in the end of list
• delete: Removes the node
• forward_traverse: Traverse the list in forward direction
• backward_traverse: Traverse the list in backward direction

Circular linked lists


✓ Representation
A circular linked list is a variation of linked list in which the last element is linked to the first
element. This forms a circular loop.

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.

Demonstration of Doubly linked list in C++


#include <iostream>
using namespace std;
struct Node {
int data;
struct Node *prev;
struct Node *next;
};
struct Node* head = NULL;
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;
}
void display() {
struct Node* ptr;
ptr = head;
while(ptr != NULL) {
cout<< ptr->data <<" ";
ptr = ptr->next;
}
}

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.

This is given below.

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;
}

Demonstration on Circular Singly linked list in C++

#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.4 Tools, Equipment, Supplies and Materials


• Computers
• Internet
• Stationery
• C++ compiler
• Instruction material

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

Learning Activities Special Instructions

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++

10.3.5.2 Information Sheet No 10/LO4: Understand Stacks and Queues


Introduction
This learning outcome covers defining stacks and queues, outlining stack and queue
representations, explaining basic operations of stacks and queues and demonstrating basic
operations in stacks 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.

Demonstration of stacks using C++


Principle operations in a stack are −
• Push - This adds a data value to the top of the stack.
• Pop - This removes the data value on top of the stack
• Peek - This returns the top data value of the stack

A program that implements a stack using array is given as follows.


Input: Push elements 11, 22, 33, 44, 55, 66
Output: Pop elements 66, 55, 44, 33, 22, 11

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 <--

after two node deletion

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.4 Tools, Equipment, Supplies and Materials


• Computers
• Internet
• Stationery
• C++ compiler
• Instruction material

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

Learning Activities Special Instructions

5.7 Search is defined Activities may be carried out


5.8 Linear Search is explained in groups or as individual
5.9 Binary Search is explained
5.10 Search techniques are demonstrated using C++

10.3.6.2Information Sheet No 10/LO5: Understand Search Techniques


Introduction

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

This procedure is also applicable for unsorted data set.

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.

Demonstration of linear search and binary search using C++


Linear search

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;

int linSearch(int array[], int size, int key) {


for(int i = 0; i<size; i++) {
if(array[i] == key) //search key in each places of the array
return i; //location where key is found for the first time
}
return -1; //when the key is not in the list
}
int main() {
int n, searchKey, loc;
cout << "Enter number of items: ";
cin >> n;
int arr[n]; //create an array of size n
cout << "Enter items: " << endl;

for(int i = 0; i< n; i++) {


620
cin >> arr[i];
}
cout << "Enter search key to search in the list: ";
cin >> searchKey;
if((loc = linSearch(arr, n, searchKey)) >= 0)
cout << "Item found at location: " << loc << endl;
else
cout << "Item is not found in the list." << endl;
}
Output
Enter number of items: 8
Enter items:
20 4 89 75 10 23 45 69
Enter search key to search in the list: 10
Item found at location: 4

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.

int binarySearch(int arr[], int p, int r, int num)

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

Learning Activities Special Instructions

6.1 Sorting is defined Activities may be carried out in


6.2 Categories of sorting techniques are outlined groups or as individual
6.3 Types of Sorting algorithms are explained
6.4Sorting algorithms are demonstrated using C++

10.3.7.2 Information Sheet No 10/LO6: Understand Sorting Techniques


Introduction

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.

✓ Adaptive and Non-Adaptive Sorting Algorithm


A sorting algorithm is said to be adaptive, if it takes advantage of already 'sorted' elements in the list
that is to be sorted. That is, while sorting if the source list has some element already sorted, adaptive
algorithms will take this into account and will try not to re-order them.
A non-adaptive algorithm is one which does not take into account the elements which are already
sorted. They try to force every single element to be re-ordered to confirm their sortedness.

✓ In place and not in place


624
In-place algorithm is an algorithm which transforms input using no auxiliary data structure.
However a small amount of extra storage space is allowed for auxiliary variables. The input is
usually overwritten by the output as the algorithm executes. In-place algorithm updates input
sequence only through replacement or swapping of elements.

❑ Types of Sorting algorithms


✓ Bubble sort
Bubble Sort Algorithm is used to arrange N elements in ascending order, and for that, you
have to begin with 0th element and compare it with the first element. If the 0th element is
found greater than the 1st element, then the swapping operation will be performed, i.e., the
two values will get interchanged. In this way, all the elements of the array get compared.

✓ 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

Example Program: Insertion Sort Using C++


Input and Output
Input:
The unsorted list: 9 45 23 71 80 55
Output:
Array before Sorting: 9 45 23 71 80 55
Array after Sorting: 9 23 45 55 71 80

Algorithm
insertionSort(array, size)

Input − An array of data, and the total number in the array


Output The sorted Array
Begin
for i := 1 to size-1 do
key := array[i]
j := i
while j > 0 AND array[j-1] > key do
array[j] := array[j-1];
j := j – 1
done
array[j] := key
done
625
End

Example Code
#include<iostream>
using namespace std;

void display(int *array, int size) {


for(int i = 0; i<size; i++)
cout << array[i] << " ";
cout << endl;
}

void insertionSort(int *array, int size) {


int key, j;

for(int i = 1; i<size; i++) {


key = array[i];//take value
j = i;

while(j > 0 && array[j-1]>key) {


array[j] = array[j-1];
j--;
}

array[j] = key;//insert in right place


}
}

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;

for(int i = 0; i<n; i++) {


cin >> arr[i];
}

cout << "Array before Sorting: ";


626
display(arr, n);
insertionSort(arr, n);
cout << "Array after Sorting: ";
display(arr, n);
}
Output
Enter the number of elements: 6
Enter elements:
9 45 23 71 80 55
Array before Sorting: 9 45 23 71 80 55
Array after Sorting: 9 23 45 55 71 80

✓ 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.

Example Program: Selection Sort Using C++


#include <iostream>
#include <string.h>
using namespace std;
#define MAX_LEN 50
void selectionSort(char arr[][50], int n){
int i, j, mIndex;
// Move boundary of unsorted subarray one by one
char minStr[50];
for (i = 0; i < n-1; i++){
// Determine minimum element in unsorted array
int mIndex = i;
strcpy(minStr, arr[i]);
for (j = i + 1; j < n; j++){
// check whether the min is greater than arr[j]
if (strcmp(minStr, arr[j]) > 0){
// Make arr[j] as minStr and update min_idx
strcpy(minStr, arr[j]);
mIndex = j;
}
}
627
// Swap the minimum with the first element
if (mIndex != i){
char temp[50];
strcpy(temp, arr[i]); //swap item[pos] and item[i]
strcpy(arr[i], arr[mIndex]);
strcpy(arr[mIndex], temp);
}
}
}
int main(){
char arr[][50] = {"Tom", "Boyaka", "Matt" ,"Luke"};
int n = sizeof(arr)/sizeof(arr[0]);
int i;
cout<<"Given String is:: Tom, Boyaka, Matt, Luke\n";
selectionSort(arr, n);
cout << "\nSelection Sorted is::\n";
for (i = 0; i < n; i++)
cout << i << ": " << arr[i] << endl;
return 0;
}
This above program initially chooses the smallest component in the exhibit and swaps it with the
principal component in the cluster. Next, it swaps the second littlest component in the cluster with
the subsequent component, etc. In this manner for each pass, the smallest component in the exhibit is
chosen and put in its legitimate situation until the whole cluster is arranged. Finally, the section sort
method sorts the given string in ascending order as follows;

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.4 Tools, Equipment, Supplies and Materials


• Computers
629
• Internet
• Stationery
• C++ compiler
• Instruction material

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.

11.2 Performance Standard


1. Created a HTML document
2. Added attributes to HTML documents
3. Formatted a web page
4. Added styles to a web page
5. Used JavaScript to change HTML elements
6. Demonstrated event handling in JQuery

11.3 Learning Outcomes


11.3.1 List of Learning Outcomes
1. Understand HTML basics
2. Use HTML elements
3. Demonstrate web page formatting
4. Apply styles
5. Understand Java Script basics
6. Use JavaScript data types
7. Use JavaScript functions
8. Use 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

1.1. HTML is defined Activities may be carried out


1.2. Terminologies used in HTML are defined in groups or as individual
1.3. HTML file is created
1.4. HTML core elements are explained
1.5 HTML core elements are added to the file
·
11.3.2.2 Information Sheet No 11/LO1: Understand HTML basics

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.

Creation of HTML file


632
1. Document type declaration-The HTML document type declaration, also known
as DOCTYPE , is the first line of code required in every HTML or XHTML document.
The DOCTYPE declaration is an instruction to the web browser about what version
of HTML the page is written in.
Example
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>

<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).

Saving as .html file

HTML core elements


1. <head> - Defines information about the document
2. <title>- Defines the title of a document
3. <body> -Defines the document's body.
4. <html>-This tag tells the browser that this is an HTML document. The <html> tag
is the container for all other HTML elements (except for the <!DOCTYPE> tag).

Addition of HTML core elements to file


Open notepad and type the following;

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>

7. What is html Document?


8. What is html Stylesheet?
9. What is html attribute?
10. What are Four HTML core elements?

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.4 Tools, Equipment, Supplies and Materials


• Internet
• Computer
• Stationery
• Instruction material

11.3.2.5 References

1. Powell, T. A. (2002). HTML: the complete reference. McGraw-Hill Professional.


2. Callihan, S. (2003). Learn html 4 in a weekend 4th edition. Premier Press.
3. Brooks, D. R. (2007). an Introduction to HTML and JavaScript: for Scientists and Engineers.
Springer Science & Business Media.
4. Michaud, T. (2013). Foundations of Web Design: Introduction to HTML & CSS. New Riders.
5. https://www.w3schools.com/html/html_basic.asp

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

11.3.3.2 Information Sheet No 11/LO2: Use of HTML 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.

Basic HTML elements


1. <p> -The HTML <p> element represents a paragraph. Paragraphs are usually
represented in visual media as blocks of text separated from adjacent blocks by
blank lines and/or first-line indentation, but HTML paragraphs can be any
structural grouping of related content, such as images or form fields
2. <br> -The HTML <br> element produces a line break in text (carriage-return). It is
useful for writing a poem or an address, where the division of lines is significant
3. <h1> -The <h1> to <h6> tags are used to define HTML headings. <h1> defines the
most important heading. <h6> defines the least important heading.

Addition of basic HTML elements to HTML document


Open notepad and type the following;
<!DOCTYPE html>
<html>
<body>
<h1>My First Heading</h1>
<p>My first paragraph with a <br> line break.</p>
</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

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.

Addition of attributes to elements


Open notepad and type the following

<!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

1. What is the correct HTML element for the largest heading


a. <h6>
b. <h1>
c. <heading>
d. <head>
2. What is the correct HTML element for inserting a line break?
a. <lb>
b. <break>
c. <br>
3. What is the correct HTML element for inserting a paragraph?
a. <p>
b. <break>
638
c. <br>
4. Which HTML attribute specifies an alternate text for an image, if the image cannot be
displayed?
a.src
b. title
c. longdesc
d.alt
5. Which HTML attribute specifies the URL of the image?
a. <a>
b. <scr>
c. <br
6. Which HTML attribute specifies the URL (web address) for a link?
a. <a>
b. <break>
c. <br
7. What is the correct HTML element for specifying a heading 1?
a. <h1>
b. <heading 1>
c. <1>
8. What does scr specify in html?
9. What does alt specify in html?
10. What does href specify in html?

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

11.3.3.4 Tools, Equipment, Supplies and Materials


• Internet
• Computer
• Stationery
• Instruction material

639
11.3.3.5 References

1. Powell, T. A. (2002). HTML: the complete reference. McGraw-Hill Professional.


2. Callihan, S. (2003). Learn html 4 in a weekend 4th edition. Premier Press.
3. Brooks, D. R. (2007). an Introduction to HTML and JavaScript: for Scientists and Engineers.
Springer Science & Business Media.
4. Michaud, T. (2013). Foundations of Web Design: Introduction to HTML & CSS. New Riders.

640
11.3.4 Learning Outcome 3: Demonstrate Web Page Formatting
11.3.4.1 Learning Activities

Learning Outcome No. 3: Demonstrate Web Page Formatting


Learning Activities Special Instructions

3.1 Layout elements are explained Activities may be carried out


3.2 Layout elements are added to the HTML document in groups or as individual
3.3 Layout element attributes are added to the HTML document

11.3.4.2 Information Sheet No 11/LO3: Demonstrate web page formatting

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

Addition of layout elements to HTML document


Open notepad and type the following, and save as .html

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

Open notepad and type the following, and save as .html

<!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>

Addition of layout element attributes to HTML document


Class -The HTML class attribute is used to define equal styles for elements with the same class
name. So, all HTML elements with the same class attribute will get the same style. 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.

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

11.3.4.4 Tools, Equipment, Supplies and Materials


• Computer
• Stationery
• Instruction material

645
11.3.4.5 References

1. Powell, T. A. (2002). HTML: the complete reference. McGraw-Hill Professional.


2. Callihan, S. (2003). Learn html 4 in a weekend 4th edition. Premier Press.
3. Brooks, D. R. (2007). an Introduction to HTML and JavaScript: for Scientists and Engineers.
Springer Science & Business Media.
4. Michaud, T. (2013). Foundations of Web Design: Introduction to HTML & CSS. New Riders.
5. https://www.w3schools.com/htmL/html_formatting.asp

646
11.3.5 Learning Outcome 4: Apply Styles
11.3.5.1 Learning Activities

Learning Outcome No. 4: Apply Styles

Learning Activities Special Instructions

4.1 Style concepts are explained Activities may be carried out


4.2 Internal styles are applied in groups or as individual
4.3 External CSS file is created

11.3.5.2 Information Sheet No 11/LO4: Apply Styles

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;
}

Application of internal styles


The internal style sheet is used to add a unique style for a single document. An internal style
sheet may be used if one single HTML page has a unique style. The internal style is defined
inside the <style> element, inside the head section.

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>

Creation of external CSS file


An external style sheet is used to define the style for many HTML pages .External style sheets are
created in separate documents with a .css extension. An external style sheet is simply a listing of
CSS rules. It cannot contain HTML tags. The <link> tag, which goes in the head of an HTML page,
is used to link to an external style sheet.

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.4 Tools, Equipment, Supplies and Materials


• Computer
• Stationery
• Instruction material

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

Learning Outcome No. 5: Understand JavaScript


Learning Activities Special Instructions

5.1 Purpose of JavaScript is highlighted Activities may be carried out


5.2 JavaScript syntax is outlined in groups or as individual
5.3 Access to HTML element attributes is demonstrated using
JavaScript Document Object Model (DOM)
5.4 Changing HTML element attributes is demonstrated using
DOM

11.3.6.2 Information Sheet No 11/LO5: Understand JavaScript

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.

Thus the purpose of the Javascript is to:


1. To make web development easier and more attractive.
2. To create responsive web pages.
3. To create interactive elements for web pages.
4. To enhance the user experience

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 uses an assignment operator ( = ) to assign values to variables:


Example
var x, y;
x = 5;
y = 6;

JavaScript Expressions
An expression is a combination of values, variables, and operators, which computes to a value.

The computation is called an evaluation.


For example, 5 * 10 evaluates to 50:
Expressions can also contain variable values:
Example
x * 10
The values can be of various types, such as numbers and strings.
For example, "John" + " " + "Doe", evaluates to "John Doe":

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

// var x = 6; I will NOT 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:

JavaScript and Camel Case


Historically, programmers have used different ways of joining multiple words into one variable
name:

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.

Upper Camel Case (Pascal Case):


FirstName, LastName, MasterCard, InterCity.

Lower Camel Case:


JavaScript programmers tend to use camel case that starts with a lowercase letter:

653
firstName, lastName, masterCard, interCity.

JavaScript Character Set


JavaScript uses the Unicode character set.
Unicode covers (almost) all the characters, punctuations, and symbols in the world.

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!

The DOM supplies the following 3 methods to tackle HTML attributes:


-getAttribute()
-setAttribute()
-removeAttribute()

These methods can be used on any element that supports attributes.

getAttribute()
getAttribute() retrieves the corresponding value of an attribute. If the attribute does not exist, an
empty string is returned. For example:

<img id="myimage" src="test.gif">


<script type="text/javascript">
//returns "test.gif"
var getvalue=document.getElementById("myimage").getAttribute("src")
</script>

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>

Finding HTML Elements


Get element by ID
The getElementById() method is used to get a single element by its id.

Example
var title = document.getElementById(‘header-title’);
Here we get the element with the id of header-title and save it into a variable.

Get elements by class name


We can also get more than one object using the getElementsByClassName() method which returns
an array of elements.
var items = document.getElementsByClassName(‘list-items’);

Here we get the element with the id of header-title and save it into a variable.

Get element by tag name


We can also get our elements by tag name using the getElementsByTagName() method.

var listItems = document.getElementsByTagName(‘li’);


Here we get all li elements of our HTML document and save them into a variable.

Changing HTML Elements attributes using JavaScript DOM Model


Property Description

element.innerHTML = new html content Change the inner HTML of an element


element.attribute = new value Change the attribute value of an HTML
element
element.style.property = new style Change the style of an HTML element
Method Description
element.setAttribute(attribute, value) Change the attribute value of an HTML
element
Adding HTML Elements
Method Description
document.createElement(element) Create an HTML element
document.removeChild(element) Remove an HTML element
document.appendChild(element) Add an HTML element

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

1. Which one of the following is correct way to declare a variable in JavaScript?


a. Var x,y,z;
b. X=5; y=6;
c. Z=x+y;
2. Which one of the following is correct way to assign values in JavaScript?
a. Var x,y,z;
b. X=5; y=6;
c. Z=x+y;
3. Which one of the following is correct way to compute values in JavaScript?
a. Var x,y,z;
b. X=5; y=6;
c. Z=x+y;
4. JavaScript syntax defines two types of values: Fixed values and variable values.
a. True
b. False
5. What do we call fixed values in JavaScript?
6. What do we call variable values in JavaScript?
7. What is String?
8. What does “element.style.property = new style” mean?
9. Which one of the following is used to retrieves the corresponding value of an attribute
a. getAttribute()
b. setAttribute()
c. removeAttribute()
Oral Assessment
1. Why prefer to use JavaScript?
2. What are the three get getAttribute()

656
Practical Assessment
1. Create a Java Script code declaring a variable and assigning it a value.

11.3.6.4 Tools, Equipment, Supplies and Materials


• Computer
• Stationery
• Instruction material

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

Learning Outcome No. 6: Use JavaScript Data types


Learning Activities Special Instructions

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

11.3.7.2 Information Sheet No 11/LO6: Use JavaScript Data types

Introduction
This learning outcome covers explaining JavaScript data types, demonstrating operations on the
data types and demonstrating arrays.

JavaScript Data types


Strings
A string (or a text string) is a series of characters like "John Doe". Strings are written with
quotes. You can use single or double quotes.
String is used to represent textual data. It is a set of "elements" of 16-bit unsigned integer values.
Each element in the String occupies a position in the String.
Example:
var lastName = "Johnson";

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

Demonstration of data type operations

Variables declarations and scope

1. JavaScript Function Scope


In JavaScript there are two types of scope:
• Local scope
• Global scope

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.

Local JavaScript Variables


Variables declared within a JavaScript function, become LOCAL to the function. Local variables
have Function scope: They can only be accessed from within the function.

Example

// code here can NOT use carName


function myFunction() {
var carName = "Volvo";

// code here CAN use carName


}

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.

Global JavaScript Variables


A variable declared outside a function, becomes GLOBAL.
A global variable has global scope: All scripts and functions on a web page can access it.

Example

659
var carName = "Volvo";
// code here can use carName
function myFunction() {
// code here can also use carName
}

In JavaScript, objects and functions are also variables.


Scope determines the accessibility of variables, objects, and functions from different parts of the
code.

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();

// code here can use carName

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;

Declaring variables with the var keyword


When you declare a variable using the var keyword, the scope is as follows:
▪ If the variable is declared outside of any functions, the variable is available in the global
scope.
▪ If the variable is declared within a function, the variable is available from its point of
declaration until the end of the function definition.

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.

Declaring variables with the let keyword


Variables declared using the let keyword have three important characteristics.
▪ They are block scoped
▪ They are not accessible before they are assigned

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"
}

console.log(a); // 5, outside the if block, the outer a shines through


}
console.log(a); // ReferenceError, a is not accessible outside the function.

Here's what happens in this function.


1. Inside the function, we create an a variable using let, this variable exists throughout the scope
of this function.
2. Inside the if block, we create another let -declared a variable. Being block scoped, we just
created a new a variable.
3. This variable is totally different from, and independent of, the outer a variable.
4. This variable is only available within the if block, and not accessible outside this block.

In addition, you can't re-declare a let variable:


Example
let a = 2;
let a = 3// SyntaxError, cannot re-declare the a variable

Declaring variables with the const keyword


Variables declared with the const keyword share all the characteristics of variables declared using
the let keyword, plus one important distinguishing characteristic:
▪ They can't be reassigned

Example
const a = 2;
a = 3 // Error, reassignment is not allowed
const a = 2;
const a = 3 // Error, re-declaration is not allowed

Expressions

1. Arithmetic- Arithmetic expressions evaluate to a numeric value. Examples include the


following

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'

Demonstration on arrays operations


✓ count()-The count() function returns the number of elements in an array.
✓ pop()-Delete the last element of an array:
Example:

Let fruits = ["Apple", "Orange", "Pear"];


alert( fruits.pop() ); // remove "Pear" and alert it
alert( fruits ); // Apple, Orange
Returns - Pear

✓ push()-The array_push() function inserts one or more elements to the end of an array.
Example:

let fruits = ["Apple", "Orange"];


fruits.push("Pear");
alert( fruits ); // Apple, Orange, Pear
Returns-Apple,Orange,Pear

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

1. Which one is not a scope of declaring variable?


a. Local
b. Global
c. Internal
2. What is correct data type of the following variable?
Var lastName = “Trancy”; //
a. String
b. Number
c. Boolean
3. What does Booleans data type represent?
a. True or False
b. Numbers
c. String
4. What does Booleans data type represent?
a. True or False
b. Numbers
c. String
5. What are the two values which are represented by Boolean Explanations?
6. Which one of the following represents an array operation to return a number of element in
array.
a. Count()
b. Pop()
c. Push()
7. Which one of the following represents an array operation to delete the last number of an
array
a. Count()
b. Pop()
c. Push()
8. Which one of the following represents an array function to insert one or more elements to
end of an array
664
a. Count()
b. Pop()
c. Push()
Oral Questions
1. How do you declare a variable in JavaScript?
2. What happens if you assign a value to a variable that has not been declared
Practical
1. Create a Java Script code declare a variable using let keyword
2. Create a Java Script code declare a variable using const keyword
11.3.7.4 Tools, Equipment, Supplies and Materials
• Computer
• Stationery
• Instruction material

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

Learning Outcome No. 7: Use of JavaScript Functions


Learning Activities Special Instructions

7.1 Structure of a JavaScript function is explained Activities may be carried out


7.2 A JavaScript function is created in groups or as individual
7.3 A JavaScript function is invoked
7.4 Values are returned using functions

11.3.8.2 Information Sheet No 11/LO7: Use of JavaScript Functions

Introduction
This learning outcome covers explaining the structure of a Javascript function, creation and
invoking JavaScript functions and returning values from JavaScript functions.

JavaScript function structure


Like the program itself, a function is composed of a sequence of statements called
the function body. Values can be passed to a function, and the function will return a value.

In JavaScript, functions are first-class objects, because they can have properties and methods just
like any other object

A JavaScript function is a block of code designed to perform a particular task.


A function is executed when "something" invokes it (calls it).

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.

JavaScript Function Syntax


666
A JavaScript function is defined with the function keyword, followed by a name, followed by
parentheses ().

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.

Note: A Function is much the same as a Procedure or a Subroutine, in other programming


languages.

Why use functions?


You can reuse code: Define the code once, and use it many times. You can use the same code many
times with different arguments, to produce different results.

Creation of JavaScript function


To create a function in JavaScript, we have to first use the keyword function, separated by name
of function and parameters within parenthesis. The part of function inside the curly braces {} is
the body of the function. Before, using a user-defined function in JavaScript we have to create
one.

We can create functions in JavaScript using the keyword function. The basic syntax to create a
function in JavaScript is shown below.

function functionName(Parameter1, Parameter2, ..)


{
// Function body
}

Invoking of JavaScript function


JavaScript Function Invocation is used to executes the function code and it is common to use the
term “call a function” instead of “invoke a function”. The code inside a function is executed when
the function is invoked.
The code inside the function will execute when "something" invokes (calls) the function:

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:

// This is a function constructor:


function myFunction(arg1, arg2) {
this.firstName = arg1;
this.lastName = arg2;
}

// This creates a new object


var x = new myFunction("John", "Doe");
x.firstName; // Will return "John"

Invoking a Function as a Method


In JavaScript you can define functions as object methods.
The following example creates an object (myObject), with two properties
(firstName and lastName), and a method (fullName):

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.

Returning values from functions

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
}

The Result will be: 12

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

1. Name two ways of invoking a function.


2. How to place a code to be executed by function
a. <>
b. {}
c. }
3. What is function argument?
4. Can you use the term call a function” instead of “invoke a function
a. Yes
b. No
5. Which operator Invokes the Function.
a. ()
b. {}
c. }
6. What are local variables in Java Script functions?
Oral Questions
669
1. How is a Javascript function invoked?
2. What is Javascript Functions?
Practical
1. Create a code to Execute the function named “myFunction()
2. Create a code to demonstrate basic syntax to create a function in JavaScript

11.3.8.4 Tools, Equipment, Supplies and Materials


• Computer
• Stationery
• Instruction material

11.3.8.5 References

1. Haverbeke, M. (2014). Eloquent javascript: A modern introduction to programming. No


Starch Press.
2. Morrison, M. (2007). Head first javascript. " O'Reilly Media, Inc.".
3. https://www.digitalocean.com/community/tutorials/how-to-define-functions-in-javascript
4. https://www.w3schools.com/js/js_functions.asp

670
11.3.9 Learning Outcome 8: Use JavaScript Libraries
11.3.9.1 Learning Activities

Learning Outcome No. 8: Use of JavaScript Libraries


Learning Activities Special Instructions

8.1. Concept of libraries is explained Activities may be carried out


8.2. JQuery framework is explained in groups or as individual
8.3. Referencing of JQuery is demonstrated
8.4. JQuery syntax is demonstrated
8.5. JQuery events are explained
8.6. DOM Manipulation with JQuery is demonstrated

11.3.9.2 Information Sheet No 11/LO8: Use of JavaScript Libraries

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.

The JQuery library contains the following features:


• HTML/DOM manipulation
• CSS manipulation
• HTML event methods
• Effects and animations
• AJAX
• Utilities

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).

Basic syntax is: $(selector).action()


• A $ sign to define/access JQuery
• A (selector) to "query (or find)" HTML elements
• A JQuery action() to be performed 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

Document Window Events


a. Load
b. Resize
c. Scroll
d. Unload

DOM Manipulation with JQuery


One very important part of JQuery is the possibility to manipulate the DOM.
JQuery provides various methods to add, edit or delete DOM element(s) in the HTML page.
The following table lists some important methods to add/remove new DOM elements.

Other DOM Manipulation Methods


Method Description
after() Inserts content (new or
existing DOM elements) after an element(s)
which is specified by a selector.
prepend() Insert content at the beginning of an element(s)
specified by a selector.
remove() Removes element(s) from DOM which is
specified by selector.
append() Inserts content to the end of element(s) which is
specified by a selector.
before() Inserts content (new or existing DOM elements)
before an element(s) which is specified by a selector.
replaceAll() Replace target element(s) with specified element.
wrap() Wrap an HTML structure around each element which
is specified by selector.

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

1. Which one of the below is a sign to define or access JQuery?


a. $
b. &
c. #
2. What does $("p").hide() hide?
a. Hides the current element
b. Hides all <p> elements
c. Hides all elements with class=”test”
3. Which one is not a keyboard event?
a. Keypress
b. Keydown
c. Click
4. Which one is not a Mouse event?
a. Click
b. Dbclick
c. Keyup
5. Which one is not a Form Event?
a. Submit
b. Click
c. Change
6. Which one of the below Sets or returns the text content of selected elements
a. Text()
b. html()
c. val()
7. Which one of the below Sets or returns the content of selected elements (including HTML
markup)
a. Text()
b. html()
c. val()
8. Which one of the below Sets or returns the value of form fields
a. Text()
b. html()
c. val()
9. What is a JavaScript Library?
10. What is jQuery event?

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.4 Tools, Equipment, Supplies and Materials


• Computer
• Stationery
• Instruction material

11.3.9.5 References

1. Haverbeke, M. (2014). Eloquent javascript: A modern introduction to programming. No


Starch Press.
2. Morrison, M. (2007). Head first javascript. " O'Reilly Media, Inc.".
3. https://www.tutorialsteacher.com/jquery/jquery-dom-manipulation

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.

12.2 Performance Standard:


1. Identified graphic design equipment as per user requirements
2. Selected graphic design elements as per design requirements
3. Explained Measurements, standards and guidelines of typography.
4. Selected software and tools for graphic design and photography.
5. Created and manipulated images using appropriate software.
6. Used typographic tools to create dynamic layout.
7. Selected and used appropriate printing tools and equipment

12.3 Learning Outcomes


12.3.1 List of Learning Outcomes
1. Understand graphic design fundamentals
2. Understand elements and principles of graphic design
3. Apply typography techniques
4. Create and edit images
5. Perform layout design
6. Print 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

Learning Activities Special Instructions

1.1 Graphic Design is explained Activities may be carried out in groups or as


1.2 Graphic design equipment is identified based individual
on the design.
1.3 Applications areas of Graphic design are
explained. ·
1.4 Specification of requirements as per the user

12.3.2.1 Information Sheet No 12/LO1: Understand Graphic Design Fundamentals


Introduction

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.

Graphic Design Equipment


Computer
For digital creatives, this is the ultimate tool that performs all the heavy lifting in the profession. If
you can afford the best and most powerful — the iMac Pro or the Surface Studio.

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.

Application areas of graphic design


Graphic design is everywhere, from the wrappers on candy bars to the logo on your favorite coffee
mug. In fact, you see hundreds of examples of graphic design every single day, and most of the
time, you don't realize it.

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

Uses of graphic design:


Graphic design is the art of communication, stylizing, and problem-solving through the use of type
and image. The field is also often erroneously referred to as Visual Communication or
Communication Design due to overlapping skills involved.

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.

Important requirements for good graphic design

• 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.4 Tools, Equipment, Supplies and Materials


● Graphic design software
● Computers
● Printers
● Scanners
● Stationery
● Instruction material

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

Learning Activities Special Instructions

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.

Jason Julien’s portfolio uses a grunge texture


Color
Color makes the graphics meaningful. It does not only make the output visually-pleasing but serves
emotion as well. For example, red represents strength, anger, or passion. On the other hand, blue
invokes peace, professionalism, and security. Color is one of the very many obvious elements used
for attention-seeking purposes and, as mentioned beforehand, evoke mood and emotion.

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

A symmetrically balanced design.

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.

Repetition is a fundamental design element, especially when it comes to branding. It creates a


rhythm and strengthens the overall design by tying together consistent elements such as logo and
colour palette, making the brand or design instantly recognisable to viewers.

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.4 Tools, Equipment, Supplies and Materials


● Graphic design software
● Computers
● Printers
● Internet
● Instruction materials
● Stationery

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

Learning Activities Special Instructions

3.1 Typography is explained Activities may be carried out in


3.2 Typography guidelines are explained groups or as individual
3.3 Measurements and standards of typography are
demonstrated
3.4 Typography techniques for a graphic design project as ·
per user requirements is selected

12.3.4.2 Information Sheet No 12/LO3: 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.”

Lots of contrast, and thus, impact!

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.

Many amateur designers make the mistake of overusing center alignment

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:

1. Hue — the shade of color

2. Saturation — how brilliant the color is

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

1 — Ask yourself some fundamental questions


Before starting with the design, it is essential to study the brand identity.

Try to conceptualise the mindset of your targeted audience and make it rule to ask yourself some
primary questions:

1. Does the content strategy match with the typography?


2. Does it convey the right message?
3. How will users perceive your design as a whole?

Typography is a union of art and science. You need to get the basics right to move forward with the
typefaces.

2 — what does your typeface communicate?


Typefaces are not merely a random play of words that can be adjusted according to someone’s
personal choice.
• Every type of font comes with a history of its origin and a directive.
• Fonts are supposed to convey a message and choosing aimlessly rarely helps.
• If you want to choose the right font, it is essential to focus on the connection with your
audience.
• Something that is not connecting is of no benefit.
• Typefaces play a massive role in audience engagement and building trust.
• Focus on your audience, learn about their interest and make the right decision.

3 — Learn the art of mixing typefaces


• Mixing typefaces is an art that every designer should be aware of.
• A clever combination of fonts goes a long way in enhancing the quality of your design.
• It is like making a salad. With a proper mix and match, create combinations that go well
following size, texture, and colour.

4 — Learn about Kerning


• Kerning in design terms is the way to set up spaces between two letters.
• Characters in the past were not designed by keeping the spacing in mind. This is why
alphabets that form angles in the outward direction (W, Y, T, and V) look a bit awkward as
compared to other alphabets.
698
5 — Setting the right alignment
One of the most crucial concepts of typography is alignment.

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.

6 — Your text should be readable


• The primary need for typography rules are to make the font readable.
• Never fall into the pit of beautiful fonts and choose something that makes reading difficult.
• Something that looks good as a set but breaks the flow while reading can be a reason for
your decreased sales. Especially when you write in paragraphs.
• You might have chosen the right font for your heading to draw user attention but choosing
the same font in a paragraph is not always the smartest choice.

7 — The Typography rules of proper grammar


• Your grammar can make or break the flow of your typography.
• Since there are so many content and typography rules, messing up with the grammar in your
design piece can be a big mistake.
• Take care of the ampersands, hyphens and spaces after punctuation and choose fonts that
complement your design.
• There are specific hidden rules in grammar that needs to be addressed before choosing the
design font.
• Construct a design specific content structure that pays attention to the sentence and
highlights the message you want to convey to your targeted audience.

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.

9 — Don’t stretch or distort fonts


• Once you have found the perfect font that compliments your design and content, do not
stretch it to make it wider or taller than it already is. Not even just a little bit.
• Often designers decide to stretch fonts to fill in blank spaces.
• Each font is created with a meticulous technique followed by proper attention to every letter
case (keeping in mind its shape, size and texture).
• Make it as standard typography rules never to modify fonts to adjust to your screen size.

Measurements and standards

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.

Em-based White-Space Adjustments


The spaces between letters are also measured in relative units: fractions of an em. This assures that
if, for example, 12-point type is resized to 14-point, any spaces between characters that have been
adjusted will also be resized proportionately, and those adjustments will be correct at the new type
size.

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.

Selecting an appropriate typography techniques for graphic design project


Choosing the right typeface can make a real difference to the effectiveness of the design. Typefaces
are just as important to the visual effect of the webpage as images.

Legibility is very important


It is important for a font to be legible in order for the reader to be able to distinguish one letter from
another. There are many factors that need to be taken into account when considering the legibility

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.

Picking fonts for a website and using them properly


It is important for the typography used on a website to attract a viewer and retain their attention. In
order to achieve this the font needs to be readable, appealing and clear.

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.

Picking fonts for print


Choosing the right font for print is essential for creating a good first impression. Picking the right
combination of fonts can ensure the printed designs stand out, whether it is a letterhead, business
card or leaflet.

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.4 Tools, Equipment, Supplies and Materials


● Graphic design software
703
● Computers
● Printers
● Internet
● Instruction materials
● Stationery

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

Learning Activities Special Instructions

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.

12.3.5.2 Information Sheet No 12/LO4: Create and edit images

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.

Identification of graphic design and photography Software and tools:

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.

Best Graphic design software for graphic designers


1. PhotoShop
2. GIMP
3. Illustrator
4. Inkscape
5. CorelDraw
705
6. Adobe InDesign
7. Serif Drawplus
8. Xara Xtreme
9. Coral paintshop
10. Coral photoimpact

Image file types

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.

Below are some of the vector image file types:


PDF (Portable Document Format)
PDF is a platform-independent image file format. That’s why the file system is not affected by
Operating System and you can open the file in Windows, OSX, and even Linux.

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.

AI (Adobe Illustrator Artwork)


This is Adobe Illustrator file format. AI file acts like PSD that can be reopened and edited as you
want. AI file is the native image format of Adobe Illustrator. It is a modified version of the older EPS
format. The tools that can read EPS can also read AI format. This file format is mostly used for
creating logos, Illustrations, and print layouts. In short, this AI Formats are best from of Vector File
Formats.

SVG (Scalable Vector Graphics)


Scalable vector graphics are actually high quality image formats. The image of this format can be
created by various Adobe Programs including Adobe Illustrator, Flash, After Effects, and more.

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.

SWF (Small Web Format)


SWF is the file format that helps you to see the flash animations. This is in fact an Adobe Flash file
format and it is used for multimedia, Vector graphics, and ActionScript. A SWF file format contains
various interactive and functional animations or applets. They occur in a lot of programs using
ActionScript. Many programs can generate SWF files.

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.

Creation of letter forms, lines of type and body copy:

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.

Below are some terminologies used in typography:

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.

Lines: The Five Line Types of Graphic Design


In graphic design, as in other visual arts, the line is absolutely fundamental. Graphic designers use
this basic tool to divide space, frame images, draw attention and communicate information or
emotion, all key elements to effective design work.

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.

For effective body copy here are some guidelines.

Pick a boring font.


There is a reason that Times New Roman is so popular for body copy. It has high readability for
long documents. The more unusual a font is, the more fatigued your reader will be at the end of
each paragraph. Serifs are good because studies have shown that they lead the reader’s eye from
one letter to the next.

Change up the look.


It may be necessary to make some adjustments for your graphic design and marketing. Squeeze
those letters together a little bit or add more space between your lines or your paragraphs. Making
changes like this will add some sophistication, whereas leaving your body copy on the default
settings will make you look like an amateur.

Stay away from the reverse text.


Humans have been conditioned to read black on white. If we had been raised reading white on
black, we would be singing a different tune. Using too much reverse text will make your readers’
eyes tire out that much faster. If you want a hard and fast rule: Try to avoid anything more than
three lines of reverse text in your body copy. Follow this rule when it comes to any other color
besides very dark colors on a light background.

No body copy on patterned backgrounds.


Too much background interference is going to confuse the heck out of your readers. If you want
your background to be visible behind your body copy, pick a background that doesn’t have too
much going on

Creation and manipulation of images:


1) Work with exciting concepts: An advertising strategy focusing on space does not mean that
you have to actually go to space to take those pictures.
A good graphic designer can blend images to make them appear as if they were one. Powerful
concepts that could not be worked on before due to there not being enough visual content now gets
a chance at being revealed to the world.

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

Learning Activities Special Instructions

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.

12.3.6.2 Information Sheet No 12/LO5:

Introduction

This learning outcome covers explaining proportion on layout design, creating


Unified systems out of dissimilar elements, creating dynamic layouts by using typographic tools
and creating a type and image project.

Proportion on layout design


Rules of design composition and layout
The Grid
Most designers see an invisible grid running through all their designs. There are a few simple
reasons for this: grids make your designs cleaner, more efficient and easier to adapt.

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!

Emphasis and scale


This ad uses color and scale to emphasize the cake, which is the focal point of the design.

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.

Creation of unified systems out of dissimilar elements

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.

Creation of dynamic layouts using typographic tools

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.

Start in Black + White


If you are designing a print piece, magazine layout, media kit, document or another designed
layout, start your design in black and white. If your layout requires illustrations, photographs or
patterns, simply fill in that area with a placeholder gray box/circle.

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.

Round out the Design


Now that your layout is refined, you can add in color + other graphic elements to round out the
design. Make sure to hang onto the original wireframe for reference, in case you need to create an
alternate version. Focus your design on a strict color palette, applied to photography, illustration,
typography and patterns.

722
Creation of Type and image project

Visual Hierarchy: What’s Important? What’s Related?


The concept of visual hierarchy plays a part in all forms of graphic design. Put simply, the most
important content should stand out the most, and the least important should stand out the least.

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.

In short, a good visual hierarchy gives instant clues about:


· The relative importance of page elements
· The relationships among them

How to make things look important


For short but large text—such as headlines and short phrases—use font size, contrasting color, and
visual weight. You can also make text look very dramatic by setting it off with generous whitespace
or background color. Use two or more of these characteristics at a time on emphasized text to
differentiate it from body text.

Blocks of smaller items—such as body text, links, or interactive tools—can be emphasized or


deemphasized with the following tools.

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.

Position and size


A medium or large text block, roughly in the center of the page, calls attention to itself as
the primary content (like an article or blog post).
Rhythm
Lists, grids, alternating elements such as headlines and summaries, and whitespace
separation can create a strong visual rhythm that irresistibly draws the eye.

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.

Using Dynamic Displays


There are many, many ways you can take advantage of the dynamic nature of computer displays.
Consider space usage, for example—even the biggest consumer-grade computer screens have less
usable space than, say, a poster or a newspaper page. If you design for mobile devices, you’ve got
an especially tiny space to work in.
724
There are many dynamic techniques for using that space to present more content than you can show
at one time. Scrollbars are one very common way of presenting a small “viewport” onto a large
thing, such as text, an image, or a table. Scrollbars let the user move around at will, in one or two
dimensions (but refrain from using horizontal scrolling with text).

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

Learning Activities Special Instructions

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

12.3.7.2 Information Sheet No 12/LO6: Print Design

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.

Printing tools and Equipment

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 – Proofing Tool


ProofHub is a wonderful proofing tool that allows design teams to manage their tasks with zero
hassle. Clients can use this proofing tool to explain or request for minor changes to be made, such
as adding color and shifting texts to the required portion of the design.

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.

Gloss coated paper


Gloss paper is typically used for flyers and brochures as it has a high shine. As the ink dries well
there is no need for a seal varnish as the ink does not rub off.

Matt coated paper


Matt paper is the opposite to gloss – it is coated with a matt finish to produce a paper that isn’t
shiny, preventing glare. This type of paper is perfect for reports, flyers and leaflets.

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.

Silk coated paper


The interim between gloss and matt, silk coated paper has a smooth silky coating, leaving it smooth
to the touch but without the shine of glass paper. This type of paper can be used for many things
such as magazines, books and catalogues.

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.

Table of Paper Sizes from A0 to A10


Size Width x Height (mm) Width x Height (in)
A0 841 x 1189 mm 33.1 x 46.8 in
A1 594 x 841 mm 23.4 x 33.1 in
A2 420 x 594 mm 16.5 x 23.4 in

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

Paper Weight Descriptions


Weight Feels Similar to:
35-55 gsm Most newspapers
90 gsm Mid-market magazine inner pages
130-250 gsm A good quality promotional poster
180-250 gsm Mid-market magazine cover
350 gsm Most reasonable quality business cards
Standard paper weights are between 75gsm and 100gsm for common business applications; photo
paper is much higher and goes up to 280gsm in weight.

Selection of printing chemicals

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.

Potential health effects of chemicals


• Solvents and inks can irritate the skin leading to dermatitis
• Some products can cause skin allergy and asthma (e.g. UV inks, laminating adhesives)
• Some solvent vapours can make you dizzy, drowsy and affect your central nervous
system
• Some solvents can damage internal organs (e.g. liver /kidney) if exposure is over a long
period
• Corrosive acids and alkalis can cause skin burns and eye damage (e.g. plate developers)
• Some inks cured by UV can cause cancer and harm to the unborn child.

Actual design printing considerations

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.

12.3.7.4 Tools, Equipment, Supplies and Materials


● Graphic design software

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

You might also like