89% found this document useful (9 votes)
11K views384 pages

CS25C03-Essentials of Computing

CS25C03 Essential Of Computing Notes Regulation 2025
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
89% found this document useful (9 votes)
11K views384 pages

CS25C03-Essentials of Computing

CS25C03 Essential Of Computing Notes Regulation 2025
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 384

CS25C03 - ESSENTIALS OF COMPUTING

AS PER THE LATEST ANNA UNIVERSITY SYLLABUS

COMMON TO I SEMESTER B.E & B.TECH


CSE/IT/AI&DS/CS&BS/CSE(AI&ML)/CSE(Cyber Security)

Regulation 2025

EDITORS

Mrs.G.Ponseka
Mr.K.Daniel Raj

PRIMARY AUTHORS

Mrs.A.Ananthakumari
Mrs.S.N.Sheebha
Dr.S.Sumathi
Dr.G.Indra Navaroj
Ms.J.Grace Priyanka

Ryan Publishers
CS25C03 - ESSENTIALS OF COMPUTING REG 25

ISBN:

Publisher: Ryan Publishers


15, Sivan Koil 1st Street,
Banker’s colony Extension,
Kumaran Nagar,
Trichy - 620017, TamilNadu, India.
Website: www.ryanpublishers.co.in
Email: [email protected]
Ph: +91 6374561101

Copyright © 2025 by Ryan Publishers

No part of this book shall be reproduced or transmitted in any form or


by any means (electronic or mechanical including photocopy,
recording, or any information storage or retrieval system) without the
permission in writing of the publisher.

ii
CS25C03 - ESSENTIALS OF COMPUTING REG 25

EDITORS and AUTHORS

Ponseka G is an Assistant Professor at


Dr. G.U. Pope College of Engineering,
with over 18 years of academic experience
in Electronics and Communication
Engineering (ECE) and Computer
Science and Engineering (CSE). She is
currently pursuing her Ph.D., with research
Mrs .Ponseka G interests in Image Processing, Machine
Assitant Professor Learning Approaches.She has guided
(Senior Grade) students in building strong foundations in
Dept.Of.CSE computing and applying knowledge to solve
Dr.GUPCOE practical problems. She actively contributes
Sawyerpuram. to academic and professional development
Mr. K. Daniel Raj is a passionate educator
and researcher with a strong academic
background in Information Technology and
Computer Science. His research interests lie
in Python programming, Artificial
Mr.K.Daniel Intelligence, and Machine Learning,
Raj where he actively explores innovative
passionate solutions to real-world challenges. As both
educator and an author and reviewer, he has
researcher contributed to several national and
Dept.Of.CSE international journals. A member of the
Dr.GUPCOE Indian Society for Technical Education
Sawyerpuram. (ISTE), he remains dedicated to advancing
knowledge, mentoring students, and
contributing to the growth of academic and
research communities.

iii
CS25C03 - ESSENTIALS OF COMPUTING REG 25

PRIMARY AUTHORS

A.Ananthakumari is currently working as a


Assistant Professor in the Department of
Computer Science and Engineering , Dr.G.U
Pope College of Engineering, Thoothukudi,
Tamilnadu,India. At present, She is pursuing
her PhD in Anna University Chennai. She
completed her MTech degree in 2011 from
Manonmaniam Sundaranar University,
Thirunelveli and did her BE in Computer
Mrs.A.Anantha
Science and Engineering in 2007 from Anna
kumari
University. She is having more than 8 years
Assitant
of experience in teaching. She has
Professor
participated in various Workshops, Seminars
(Senior Grade)
and Faculty development programmes to
Dept.Of.CSE
boost up the knowledge of students’
Dr.GUPCOE
community. She published a patent in 2022
Sawyerpuram
under the title of “Smart Non-Invasive
Blood Glucose Monitoring Device For
Diabetes Patient” as IPR application
Number 202241044319.She has published a
paper in UGC care Group-I journal. She has
presented papers in various National and
International conferences. She participated
in research oriented Faculty development
programme. She has organized Hands-on-
Training and webinars. Her research area
includes Machine Learning and Deep
Learning.

iv
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Dr. S Sumathi received her Bachelor's in


Computer Science and Engineering, a
Master's in Computer Science and
Engineering, and a Ph.D. in Computer Science
and Engineering from Anna University,
Chennai, India. She is an Assistant Professor
Dr. S Sumathi (Senior Grade) at the University VOC
Assitant College of Engineering, Thoothukudi, Tamil
Professor Nadu, India. Professor Sumathi has over a
(Senior Grade) decade of experience teaching and
Dept.Of.CSE conducting research at both the
University VOC undergraduate and postgraduate levels. She
College of did extensive research work in the field of
Engineering, cyber security attack detection using
Thoothukudi machine learning. Her research areas include
machine learning, deep learning, cyber
security, and biomedical data analysis.
Mrs. S. N. Sheebha, M.E., is an Assistant
Professor in the Department of Computer
Science and Engineering at Dr. G.U. Pope
College of Engineering, Tuticorin. With 7
years of teaching and research experience, she
is pursuing her Ph.D. in Artificial
Intelligence with Deep Learning at Anna
University. She holds a B.E. in CSE from
Mrs. S.N. Sheebha Karunya Institute of Technology and Science,
Assistant Coimbatore, and an M.E. from Dr. Sivanthi
Professor Aditanar College of Engineering,
Dept.Of.CSE Tiruchendur. She has published in reputed
Dr.GUPCOE journals, presented papers internationally, and
Sawyerpuram received the Best Paper Award at
ICTIEECC 2016.

v
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Dr. G. Indra Navaroj is currently working as an


Assistant Professor in the Department of
Information Technology, Vel Tech Rangarajan Dr.
Sagunthala R&D Institute of
Science and Technology, Chennai, Tamil Nadu,
India. She received a Ph.D degree in
Information and Communication
Dr. G. Indra
Engineering from Anna University,
Navaroj
Assistant Chennai , in the year 2022. She
Professor received her B.Tech. degree in Information
Department of Technology in 2007 from Anna University,
Information Chennai, and her M.Tech., degree in Computer
Technology, and Information Technology in 2010 from
Vel Tech Manonmaniam Sundaranar University,
Rangarajan Dr. Tirunelveli. She has 17.10 years of teaching
Sagunthala R&D experience. She completed more than ten NPTEL
Institute of courses and an AICTE FDP. "Blockchain
Science and Architecture Design and Use Case",
Technology, "Introduction to Internet of Things ",
Chennai. "Industrial 4.0 and Industrial Internet of
Things", "Object Oriented Analysis and
Design", "Cloud Computing", "Object
Oriented System Development using UML,
Java and Pattern". She received a certificate of
Appreciation from NPTEL to be recognized as an
"NPTEL Star" –NPTEL_DISPLINE, Dec 2020.
She received the 'Certificate of Recognition' from
the Research Center, Anna University, Chennai,
for publishing her research in a Q1 journal.
She has participated in more than 45 Faculty

vi
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Development Programs (FDPs), seminars, and


webinars hosted by various colleges. She has
written two book chapters and published many
research papers on IoT and Wireless Sensor
Networks. Her research area includes Wireless
Sensor Networks, Blockchain, and IoT.

Ms. J. Grace Priyanka, M.E., MISTE is an


Assistant Professor in the Department of
Computer Science and Engineering at Dr.
G.U. Pope College of Engineering, affiliated
with Anna University. She has over 16+
years of teaching experience and is an active
member of the Indian Society for Technical
Education (MISTE). She has contributed to
Ms.J.Grace academic research, guided students in
Priyanka projects, and participated in numerous Faculty
Assitant Development Programs, workshops, and
Professor seminars. Her areas of expertise include
(Senior Grade) Computer Science, Programming, and
Dept.Of.CSE emerging technologies, and she is committed
Dr.GUPCOE to fostering innovation and excellence in
Sawyerpuram education.

vii
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Message from the Editor(s)


We are pleased to present “CS25C03 – Essentials of
Computing”, an effort that reflects the dedication and hard work
of the authors in creating a resource that is comprehensive,
relevant, and student-focused.

The subject of computing forms the backbone of modern


engineering education, and this book has been designed with the
intention of helping students grasp the core concepts at an early
stage of their academic journey. The clarity of explanations,
logical flow of topics, and practical orientation make this work a
valuable companion for learners.

As editors, we deeply appreciate the contributions of the authors


and their commitment to ensuring quality and accuracy. We
believe that this book will benefit not only students but also
faculty members in guiding and supporting their teaching.

We extend our best wishes to all readers and hope that this work
will inspire curiosity, enhance understanding, and serve as a
strong foundation for further studies.

Mrs. G. Ponseka
Mr. K. Daniel Raj
Editors&Authors

viii
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Message from the Author(s)


It gives us immense pleasure to present this book, “CS25C03 –
Essentials of Computing”, carefully prepared in alignment with
the Anna University Regulation 2025 syllabus. The primary
objective of this book is to introduce first-year engineering
students to the fundamental concepts of computing and to equip
them with the knowledge and skills required for further learning
in the field of Computer Science and related domains.

We have strived to organize the content in a simple, clear, and


structured manner, blending theoretical principles with practical
examples. Our intention is to make the subject both
approachable and engaging for learners who are beginning their
journey in engineering education.

We express our gratitude to our colleagues, mentors, and peers


for their constant encouragement during the preparation of this
book. We are equally thankful to Ryan Publishers for their
valuable support throughout the publishing process.

We sincerely hope that this book will serve as a helpful resource


to students and educators alike and inspire further exploration
into the vast world of computing.

Mrs. A. Ananthakumari
Mrs. S. N. Sheebha
Dr. S. Sumathi
Dr. G. Indra Navaroj
Ms. J. Grace Priyanka
Primary Authors

ix
CS25C03 - ESSENTIALS OF COMPUTING REG 25

CS25C03 - ESSENTIALS OF COMPUTING


SYLLABUS

UNIT I INTRODUCTION TO COMPUTERS

Computers: Computer, Characteristics of Computers, History of


Computers, Classification of Computers, Applications of
Computers, Basic Organization of a Computer. Data
Representation, Using spread sheets for basic operations on data
and visualize the data.
Practical:
1. Office Software for documentation and presentation
2. Spread sheets for calculations and data. Visualization

UNIT II COMPUTATIONAL THINKING

What is Computational Thinking, Decomposition, Abstraction,


Real World Information to Computable Data, Number Systems,
Conversions among Number systems, what is Logic, Boolean
Logic, Applications of Propositional Logic.
Activities:
1. Solving problems based on number systems and logics.
2. Virtual Demonstration of Computational thinking

UNIT III PROBLEM SOLVING BASICS

Problem Definition, Logical Reasoning, Decomposition,


Software Design Concept of an Algorithm, Algorithm
Representation – Algorithm Discovery – Iterative Structures –

x
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Recursive Structures – Efficiency and Correctness -


Implementation of Algorithms - Fundamental Algorithms:
Exchanging the values of two variables, Counting, Summation
of a set of numbers, Factorial computation, Generation of
Fibonacci Sequence, Reversing the digits of an Integer, Base
Conversion.
Activities: Algorithm Development for simple mathematical
problems

UNIT IV PROGRAMMING LANGUAGES

Program Development Life Cycle, Program Design Tools,


Algorithms, Flowcharts, Pseudocodes, Role of Algorithms,
Programming Languages, Programming Paradigms Traditional
Programming Concepts, Procedural Units, Language
Implementation, Declarative Programming.
Activities: Flowchart design for simple mathematical problems

UNIT V SCRATCH PROGRAMMING AND APP


DEVELOPMENT
SCRATCH PROGRAMMING

What is Scratch, Scratch Programming Environment, Paint


Editor, Scratch Blocks, Arithmetic Operators and Functions,
Use Motion Commands, Pen Commands and Easy Draw, Looks
Palette, Sound Palette, Power of Repeat, Data Types, Variables,
Getting Input from Users. Making Decisions, Comparison
Operators, Decision Structures, Logical Operators, Repetition,
Loop Blocks, Stop Commands, Counters, Nested Loops,

xi
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Recursion, String Processing, String Manipulation, Lists,


Dynamic Lists, Numerical Lists, Searching and Sorting Lists.
Activities:
1. Creation of Functional Block for simple mathematical
problems
2. Drawing and Painting operations
3. Scratch Animation for understanding Conditional and Loop
statements.
4. Draw artistic, geometric patterns and create games.
5. Scratch Programs for applied scientific computing and data
manipulations

APP DEVELOPMENT
Building Apps using problem, solving techniques on any app
development platform, Modeling, incremental and iterative,
reuse, modularization, algorithmic thinking, abstracting and
modularizing, decomposition, testing and debugging.

Activities: Sample App Developments for societal problems.

xii
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Content

S.No Title Pg.No


1 UNIT I – INTRODUCTION TO
COMPUTERS
1.1 Computers 1
1.1.1 Definition 2
1.1.2 Characteristics of Computers 3
1.1.3 History of Computers 5
1.2 Classification of Computers 11
1.3 Applications of Computers 17
1.4 Basic Organization of a Computer 20
1.5 Data Representation 24
1.6 Spreadsheets 29
1.6.1 Basic operations on data 30
1.6.2 Data visualization 35
1.7 Important Two Marks 43
2 UNIT II – COMPUTATIONAL
THINKING
2.1 Computational Thinking 47
2.1.1 Definition 47
2.1.2 Importance 47

xiii
CS25C03 - ESSENTIALS OF COMPUTING REG 25

2.2 Decomposition 49
2.3 Abstraction 50
2.4 Real-world Information to Computable 51
Data
2.5 Number Systems 53
2.5.1 Binary 54
2.5.2 Decimal 55
2.5.3 Octal 56
2.5.4 Hexadecimal 57
2.6 Conversions among Number Systems 57
2.7 Logic 72
2.8 Boolean Logic 73
2.9 Applications of Propositional Logic 82
2.10 Important Two Marks 83
3 UNIT III – PROBLEM SOLVING BASICS
3.1 Problem Definition 85
3.2 Logical Reasoning 89
3.3 Decomposition 93
3.4 Software Design Concepts 97
3.5 Algorithm 104
3.5.1 Concept of an Algorithm 104

xiv
CS25C03 - ESSENTIALS OF COMPUTING REG 25

3.5.2 Algorithm Representation 105


3.5.3 Algorithm Discovery 108
3.6 Algorithmic Structures 111
3.6.1 Iterative Structures 112
3.6.2 Recursive Structures 115
3.7 Efficiency and Correctness of Algorithms 118
3.7.1 efficiency of algorithms 119
3.7.2 correctness of algorithms 124
3.8 Implementation of Algorithms 128
3.9 Fundamental Algorithms 137
3.9.1 Exchanging values of two variables 137
3.9.2 Counting 138
3.9.3 Summation of a set of numbers 139
3.9.4 Factorial computation 141
3.9.5 Generation of Fibonacci sequence 142
3.9.6 Reversing the digits of an integer 144
3.9.7 Base Conversion 145
3.10 Important Two Marks 146
4 UNIT IV – PROGRAMMING
LANGUAGES
4.1 Program Development Life Cycle 150

xv
CS25C03 - ESSENTIALS OF COMPUTING REG 25

4.2 Program Design Tools 153


4.2.1 Algorithms 153
4.2.2 Flowcharts 157
4.2.3 Pseudocode 160
4.3 Role of Algorithms in Programming 163
4.4 Programming Languages 171
4.4.1 Types of Programming Languages 173
4.4.2 Importance of Programming Languages 174
4.5 Programming Paradigms 175
4.5.1 Imperative Programming Paradigms 176
4.5.2. Declarative Programming Paradigms 180
4.6 Traditional Programming Concepts 184
4.7 Procedural Units 189
4.8 Language Implementation 194
4.9 Declarative Programming Concepts 202
4.10 Important Two Marks 209
5 UNIT V – SCRATCH PROGRAMMING
AND APP DEVELOPMENT
SCRATCH PROGRAMMING
5.1 Scratch Programming Environment 213
5.2 Paint Editor 216

xvi
CS25C03 - ESSENTIALS OF COMPUTING REG 25

5.3 Scratch Blocks 220


5.4 Arithmetic Operators and Functions 222
5.5 Motion Commands 227
5.6 Pen Commands and Easy Draw 230
5.7 Looks Palette 235
5.8 Sound Palette 237
5.9 Repeat and Looping Structures 243
5.10 Data Types and Variables 250
5.11 User Input 256
5.12 Decision Structures 263
5.13 Comparison Operators 270
5.14 Logical Operators 274
5.15 Repetition and Loop Blocks 277
5.16 Stop Commands 281
5.17 Counters 287
5.18 Nested Loops 292
5.19 Recursion 297
5.20 String Processing and Manipulation 304
5.21 Lists 308
5.21.1 String Lists 313
5.21.2 Dynamic Lists 318

xvii
CS25C03 - ESSENTIALS OF COMPUTING REG 25

5.21.3 Numerical Lists 325


5.21.4 Searching and Sorting 331

APP DEVELOPMENT
5.22 Building Apps using problem-solving
techniques 337
5.23 Modeling and Design 342
5.24 Incremental and Iterative Development 346
5.25 Reuse and Modularization 349
5.26 Algorithmic Thinking in App
Development 353
5.27 Abstraction and Decomposition 357
5.28 Testing and Debugging 360
5.29 Important Two Marks 364

xviii
CS25C03 - ESSENTIALS OF COMPUTING REG 25

UNIT I INTRODUCTION TO COMPUTERS

SYLLABUS

Computers: Computer, Characteristics of Computers, History of


Computers, Classification of Computers, Applications of
Computers, Basic Organization of a Computer. Data
Representation, Using spread sheets for basic operations on data
and visualize the data.

1.1 INTRODUCTION TO COMPUTERS

Fig 1.1 Computer


The term “Computer” is often associated with the
acronym “Common Operating Machine Purposely Used for
Technological and Educational Research.”

1
CS25C03 - ESSENTIALS OF COMPUTING REG 25

A computer is an electronic device that accepts data as input,


processes it according to a set of instructions (programs), and
produces meaningful output. It can also store information for
future use. Computers have become an essential part of modern
life, playing a vital role in education, communication, business,
healthcare, research, and entertainment.

Computers are not just calculating machines; they are problem-


solving tools capable of performing complex operations with
speed and accuracy that far surpass human abilities. From
simple tasks like word processing to advanced fields such as
artificial intelligence, data science, and space exploration,
computers are at the core of technological advancement.

1.1.1 DEFINITION

A computer is an electronic machine, devised for


performing calculations and controlling operations that can be
expressed either in logical or numerical terms.

Applications : The applications domain of a computer depends


totally on human creativity and imagination it covers a huge
area of applications including education, industries, government
medicine, scientific research, low and even music and arts.

 Millions of complex calculations can be done in a mere


fraction of time.

 Difficult decisions can be made with unerring accuracy for


comparatively little cost

2
CS25C03 - ESSENTIALS OF COMPUTING REG 25

1.1.2 CHARACTERISTICS OF COMPUTER

a) Speed
Computer process data at an extremely fast rate – millions
of instructions per second in few seconds, a computer can
perform a huge task that a normal human being may take
days or even years to complete. The speed of a computer is
calculated in Mhz

b) Accuracy
Besides efficiency, computer are accurate as well. The level
of accuracy depends an the instructions and the type of
machine being used.

3
CS25C03 - ESSENTIALS OF COMPUTING REG 25

c) Diligence
Computer being a machine does not suffer form the human
trailts of tiredness and lack of concentration

d) Versatility
It can perform multiple taks simultaneously with great ease.
For example, at one moment it can be used to draft a letter,
another moment it can be used to play music an in between,
one can print a document as well. All this work is possible
by changing the program.

e) Resource sharing
It made the sharing of costly resources like printer possible.
Apart from device sharing data and information can also be
shared among group of computers, thus creating a large
information and knowledge base.

f) Storage capability
The main memory of the computer is relatively small and it
can hold only a certain amount of information, therefore,
the data is stored on secondary storage devices such as
magnetic tape or disks.

g) Reliability
Reliability is the measurement of performance of a
computer, which is measured against some predetermined
standard for operation without any failure.

4
CS25C03 - ESSENTIALS OF COMPUTING REG 25

1.1.3 HISTORY OF COMPUTERS

1.1.3.1 ORIGIN OF COMPUTERS

The origin of computers can be traced to the human need for


counting large numbers, leading to various systems of
numeration. The Indian system (0–9) became the universal
decimal system. Early devices and inventions include:

a. Abacus (3000 B.C., China): First known calculating tool


using beads.
b. Napier’s Bones (1617): Invented by John Napier for
multiplication using rods.
c. Slide Rule (17th Century): Developed by E. Gunter for
multiplication, division, addition, and subtraction.
d. Pascal’s Calculator (1642): Blaise Pascal’s machine for
addition and subtraction.
e. Leibniz’s Machine (1673): Performed multiplication and
division mechanically.
f. Difference Engine (1820s): Designed by Charles Babbage,
precursor to modern computers.
g. Analytical Engine: Also by Babbage, featured memory
(store) and processor (mill), similar to today’s computers.

5
CS25C03 - ESSENTIALS OF COMPUTING REG 25

h. Mechanical & Electrical Calculators (19th–20th


Century): Replaced manual effort; later powered by
electric motors.
i. Modern Electronic Calculators (1960s onwards):
Evolved from vacuum tubes to transistors, enabling
compact, fast, and advanced calculations

1.1.3.2. GENERATIONS OF COMPUTERS

Generation in computer terminology is a change in technology a


computer is/was being used. Initially, the generation term was
used to distinguish between varying hardware technologies.
Nowadays, generation includes both hardware and software,
which together make up an entire computer system.

There are five computer generations known till date. Each


generation has been discussed in detail along with their time
period and characteristics. In the following table, approximate
dates against each generation has been mentioned, which are
normally accepted.

Following are the main five generations of computers.

Generation Period Technology Used

First Generation 1946 – 1959 Vacuum tube based

Second Generation 1959 – 1965 Transistor based

Integrated Circuit
Third Generation 1965 – 1971
(IC) based

6
CS25C03 - ESSENTIALS OF COMPUTING REG 25

VLSI (Very Large


Scale Integration)
Fourth Generation 1971 – 1980
microprocessor
based

ULSI (Ultra Large


Scale Integration)
Fifth Generation 1980 – onwards
microprocessor
based

Fig 1.1.3.2 generations of Computer

7
CS25C03 - ESSENTIALS OF COMPUTING REG 25

First Generation (1946 – 1959)

The first generation computers used vacuum tubes as the main


technology. These computers were very large, expensive, and
consumed a lot of electricity. They produced excessive heat,
required air conditioning, and were unreliable. Machine
language was used for programming, and input/output was
through punch cards and paper tapes.

Features

 Based on vacuum tube technology


 Huge size and very costly
 Consumed a lot of electricity and produced heat
 Required air conditioning
 Non-portable and unreliable
 Used machine language only

Examples: ENIAC, EDVAC, UNIVAC, IBM-701

Second Generation (1959 – 1965)

This generation used transistors instead of vacuum tubes,


making computers smaller, faster, and more reliable. They
consumed less power and generated less heat. Assembly
language and high-level languages like FORTRAN and COBOL
were introduced.

Features

 Based on transistor technology


 More reliable and smaller than first generation

8
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 Consumed less power and produced less heat


 Faster and easier to maintain
 Used assembly and high-level languages

Examples: IBM 1620, IBM 7094, CDC 3600, UNIVAC 1108

Third Generation (1965 – 1971)

The third generation saw the use of Integrated Circuits (ICs),


which combined multiple transistors and components on a single
chip. Computers became more efficient, smaller, and cheaper.
High-level languages like BASIC, PASCAL, and ALGOL were
used.

Features

 Based on Integrated Circuit technology


 Smaller, faster, and more reliable
 Required less maintenance and electricity
 Supported high-level programming languages
 Introduced time-sharing and multiprogramming

Examples: IBM-360 series, Honeywell-6000, PDP series, IBM-


370/168

Fourth Generation (1971 – 1980)

This generation introduced microprocessors with VLSI (Very


Large Scale Integration) technology, where thousands of
components were placed on a single chip. It led to the
development of Personal Computers (PCs). Networking and the
concept of the internet also began in this era.

9
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Features

 Based on VLSI microprocessor technology


 Very small, portable, and reliable
 Much cheaper and easily available
 Supported high-level languages like C and C++
 Concept of internet and networking introduced

Examples: DEC 10, PDP 11, CRAY-1 (Supercomputer),


CRAY-X-MP

Fifth Generation (1980 – Present)

The fifth generation uses ULSI (Ultra Large Scale Integration)


and focuses on Artificial Intelligence (AI), parallel processing,
and natural language processing. Computers became compact,
powerful, and user-friendly with multimedia features.

Features

 Based on ULSI technology


 Development of AI and expert systems
 Parallel processing and superconductor technology
 More user-friendly with graphical interfaces and
multimedia
 Very powerful, compact, and affordable

Examples: Desktop, Laptop, Notebook, Ultrabook,


Chromebook

10
CS25C03 - ESSENTIALS OF COMPUTING REG 25

1.2 CLASSIFICATIONS OF COMPUTERS

1.2.1. BASED ON CAPACITY


This classification categorizes computers by their size,
processing power, and user support.
A) Microcomputer:
Size: Small and portable.
Examples: Laptops, desktops, mobile phones, notebooks.
Uses: Education, entertainment, research, healthcare, home
automation, e-commerce.
Key Feature: An essential part of modern life due to its impact
on society, business, and education.

11
CS25C03 - ESSENTIALS OF COMPUTING REG 25

fig1.2.1 Micro Computer


B)Minicomputer:
Size: Mid-size, larger than a microcomputer but smaller than a
mainframe.
Examples: PDP-11, IBM's AS/400e.
Uses: Scientific computations, engineering, business transaction
processing, database management.
Key Feature: A multi-processing system that can support up to
250 users simultaneously.

fig1.2.2 Mini Computer

C)Mainframe Computer:
Size: Very large, with size varying based on specifications.
Examples: IBM zSeries, Unisys ClearPath.
Uses: Finance, government, healthcare.

12
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Key Feature: Supports hundreds or thousands of users


simultaneously, processes a high volume of transactions. Its
capacity is measured in MIPS (million instructions per second).

fig1.2.3 Main Frame Computer

D)Supercomputer:
Size: Varies from small clusters to massive installations. Can
contain thousands of computers working together.
Examples: Fugaku, Google Sycamore, Sierra.
Uses: Scientific research, weather forecasting, scientific
simulations, nuclear energy research.
Key Feature: The most powerful type of computer, designed
for complex and intensive tasks. It can perform billions of
calculations per second using parallel processing with
specialized hardware like GPUs or TPUs.

fig1.2.4 Super Computer

13
CS25C03 - ESSENTIALS OF COMPUTING REG 25

1.2.2 BASED ON DATA HANDLING


This classification is based on how computers process and
represent data.
A)Analog Computer:
Data Handling: Uses continuous data and physical quantities
(like voltage or mechanical movement) instead of discrete
numbers.
Key Feature: Excellent at solving differential equations and
simulating dynamic systems. Data is processed as continuous
signals.

fig1.2.5 Analog Computer


B)Digital Computer:
Data Handling: Represents and processes data using discrete,
distinct values, specifically binary numbers (0s and 1s).
Key Feature: Designed for arithmetic calculations and complex
data manipulation. The main components are input, processing,
and output.

fig1.2.6 Digital Computer

14
CS25C03 - ESSENTIALS OF COMPUTING REG 25

C)Hybrid Computer:
Data Handling: Integrates features of both analog and digital
computers.
Components: Has an analog component to process real-world
data (voltage, temperature) and a digital component for
complex calculations and overall system control.
Key Feature: Combines the strengths of both technologies for
efficient task performance.

fig1.2.7 Hybrid Computer


1.2.3 BASED ON PURPOSE
This classification is based on the intended use or function of
the computer.
A)Special Purpose Computer (SPC):
Purpose: Designed and optimized for a single or limited set of
tasks.
Examples: Embedded systems (in cars or microwaves), ATMs,
MRI scanners, spacecraft computers.

15
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Key Feature: Excels at its specific function with high


efficiency, speed, and accuracy.

fig1.2.8 Special Purpose Computer


B)General Purpose Computer (GPC):
Purpose: Designed to perform a wide range of tasks by running
different software and applications.
Examples: Desktops, laptops (running operating systems like
Windows or macOS).
Key Feature: Versatile and programmable. It has a general-
purpose operating system and input/output capabilities that
allow users to interact with it for various purposes.

fig1.2.9 General Purpose Computer

16
CS25C03 - ESSENTIALS OF COMPUTING REG 25

1.3 APPLICATIONS OF COMPUTERS

fig1.3 Applications Of Computer

Communication
Computers and digital technologies play a vital role in
communication by enabling people to connect instantly across
the world. Emails, messaging apps, video calls, and social media
platforms help share information quickly and effectively. This
fosters collaboration in personal, educational, and professional
environments, bridging geographical and cultural barriers.

17
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Engineering
In engineering, computers are used for designing, testing, and
creating new products and systems. With tools like CAD
(Computer-Aided Design), CAM (Computer-Aided
Manufacturing), and simulation software, engineers can model
prototypes, run stress tests, and improve efficiency before actual
production. This reduces cost, saves time, and enhances
innovation.

Book Publishing
Computers streamline the entire book publishing process.
Authors can draft and edit manuscripts, designers can format
pages and covers using publishing software, and printers can
produce high-quality outputs. Digital publishing platforms also
allow e-books and audiobooks to reach global audiences
instantly, making publishing more accessible.

Personal Use
For individuals, computers assist in managing everyday
activities and hobbies. They are used for browsing the internet,
shopping online, maintaining digital calendars, listening to
music, watching movies, and even managing fitness or personal
finance apps. Computers also serve as a tool for creativity
through photography, blogging, or digital art.

Accounting
In the financial sector, computers are essential for recording,
analyzing, and managing transactions. Accounting software
automates processes such as payroll, tax calculation, auditing,
and generating financial reports. This ensures accuracy, reduces
human errors, and provides real-time insights into financial
performance.

18
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Scientific Research
Computers empower researchers to collect, process, and analyze
vast amounts of data. They are used in simulations, statistical
modeling, and complex calculations that would be impossible
manually. Fields like genetics, space exploration, and climate
science rely heavily on computer-based analysis to achieve
breakthroughs and discoveries.

Business Applications
Organizations use computers to manage their operations,
customer relations, supply chains, and decision-making. From e-
commerce platforms and customer service systems to enterprise
resource planning (ERP), computers help businesses stay
competitive, efficient, and innovative in a global market.

Education
In the education sector, computers support both teaching and
learning. Students use them for research, virtual classrooms, and
online assessments, while teachers employ them for lesson
planning, presentations, and interactive teaching methods. E-
learning platforms and digital libraries have expanded access to
education worldwide.

Entertainment & Games


Computers offer a wide range of entertainment options, from
streaming movies and music to creating immersive video games
with advanced graphics. They also provide creative outlets like
digital editing, animation, and music composition. The gaming
industry, in particular, has become one of the largest global
entertainment markets.

19
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Banks & Medicine


In banking, computers manage customer accounts, enable online
transactions, and ensure secure financial operations. ATMs,
mobile banking apps, and fraud detection systems all rely on
computer technologies. In medicine, computers are used for
storing patient records, running diagnostic tools, analyzing scans,
supporting telemedicine, and even assisting in robotic surgeries,
improving accuracy and patient care.

1.4 BASIC ORGANIZATION OF A COMPUTER

fig1.4 Organization Of Computer

A computer system is an electronic device that processes data


and produces meaningful information. To perform this task, a
computer follows a specific organization of different units,
commonly known as the computer architecture. The basic

20
CS25C03 - ESSENTIALS OF COMPUTING REG 25

structure of a computer consists of the Input Unit, Storage


Unit, Central Processing Unit (CPU), and Output Unit.

 The Input Unit is responsible for receiving instructions and


data.
 The Storage Unit holds data temporarily or permanently.
 The CPU, also called the "brain of the computer," processes
the data with the help of the Control Unit and Arithmetic
Logic Unit (ALU).
 Finally, the Output Unit presents the processed result to
the user in a readable form.

Have you ever wondered what goes on inside a computer when


you click a mouse, type on a keyboard, or watch a video? At its
heart, every computer, from the smallest smartphone to the
largest supercomputer, follows a simple, logical structure. This
chapter will explain the fundamental components of a computer
and how they work together to process information, much like
the different parts of a team working toward a single goal.
The basic design we'll explore is called the Von Neumann
architecture, a brilliant concept developed in the mid-20th
century that still forms the blueprint for nearly all modern
computers. It breaks the machine down into a few core units,
each with a specific job.
1.4.1. The Input Unit: Getting Data In
Think of the Input Unit as the computer’s eyes and ears. Its job
is to accept data and instructions from the outside world and
convert them into a language the computer can understand—
binary code (a series of 1s and 0s). Without this unit, the
computer would have no way of knowing what you want it to do.

21
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Common Examples: The keyboard you type on, the mouse you
click with, a microphone that captures your voice, or a scanner
that reads a document. Each of these devices takes your action
and turns it into digital information for the computer to use.
1.4.2. The Central Processing Unit (CPU): The Brain of the
Computer
The CPU is the most important component of the computer. It is
responsible for all the processing, calculations, and decision-
making. You can think of the CPU as a team of highly-skilled
workers who follow instructions to solve a problem. The CPU is
made up of three main parts:
 Arithmetic Logic Unit (ALU): This is the computer's
calculator. The ALU performs all the mathematical
operations (like addition and subtraction) and logical
comparisons (like determining if one number is greater than
another).
 Control Unit (CU): The Control Unit is the manager of the
entire computer. It fetches instructions from memory,
decodes them, and then directs all other parts of the
computer—the ALU, memory, and input/output units—to
perform their tasks in the correct order.
 Registers: These are tiny, lightning-fast storage locations
inside the CPU. They hold data and instructions that the
CPU needs to use immediately, like a worker's personal
notepad. They are the fastest memory in the entire system.
1.4.3. The Memory Unit: Storing Information
The Memory Unit is where the computer holds data and
instructions. It's like a workspace and a filing cabinet all in one.
There are two types of memory:

22
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 Primary Memory (RAM): This is the computer's short-


term, or "working," memory. Think of it as a workbench.
The CPU puts all the data and instructions it is currently
working on here because it’s much faster to access than
long-term storage. However, this memory is volatile,
meaning its contents are erased as soon as the computer is
turned off.
 Secondary Storage: This is the computer's long-term
memory. It acts like a filing cabinet where you save all
your files, documents, and programs permanently. Data in
secondary storage remains even when the power is off.
Examples include a hard disk drive (HDD), a solid-state
drive (SSD), or a USB flash drive.
1.4.4. The Output Unit: Sharing the Result
The Output Unit is how the computer communicates its results
back to the user. It takes the processed data and converts it into a
form that we can see, hear, or feel.
Common Examples: A monitor that displays an image, a
printer that produces a physical copy, or speakers that play
music.
1.4.5. The Bus System: The Information Highway
The Bus System is the set of electronic pathways or "highways"
that connect all the different components of the computer. It
allows data and control signals to travel between the CPU,
memory, and input/output devices. Without these pathways, the
components would be isolated and unable to communicate.
How It All Works Together: A Simple Example
Imagine you want to calculate 2 + 3 on a computer.

23
CS25C03 - ESSENTIALS OF COMPUTING REG 25

1. Input: You type "2 + 3" on the keyboard. The Input Unit
converts your keystrokes into binary code.
2. Processing: The Control Unit receives the instructions and
data. It first tells the Memory Unit to store the numbers "2"
and "3." Then, it directs the ALU to perform the addition.
3. Result: The ALU calculates the sum, which is "5." The
Control Unit then tells the Output Unit (your monitor) to
display the result.
4. Output: The number "5" appears on your screen.
This entire process happens in a fraction of a second, but it
perfectly demonstrates how all the core components of the
computer work together in a seamless cycle of input, processing,
and output.
1.5 DATA REPRESENTATION

fig1.5 Data Representation

24
CS25C03 - ESSENTIALS OF COMPUTING REG 25

A computer is a digital machine that works with data in the form


of binary digits (0s and 1s). Since it cannot understand human
language directly, all types of information—whether numbers,
characters, images, audio, or video—must be converted into a
binary form before processing. This process is known as data
representation.
Data can be represented in the following major forms:

1.5.1 Number Systems

Computers use different number systems to represent and


process numerical data. While humans are familiar with the
decimal system (base 10), computers primarily use binary
(base 2).The four commonly used number systems are:

1.Binary Number System (Base 2):

 Consists of only two digits: 0 and 1.


 Example: (10110010)₂ = 178₁₀
 This is the fundamental system used internally by all
computers

2.Octal Number System (Base 8):

 Consists of digits from 0 to 7.


 Example: (324017)₈ = 110415 in decimal.

3.Decimal Number System (Base 10):

 The system humans use in daily life (digits 0–9).


 Example: (875629)₁₀.

25
CS25C03 - ESSENTIALS OF COMPUTING REG 25

4.Hexadecimal Number System (Base 16):

 Consists of digits 0–9 and letters A–F.


 Example: (2F)₁₆ = 47₁₀, where A=10, B=11, … F=15.

Table: Summary of Number Systems

Number System Base Digits Used Example

Binary 2 0, 1 (1011)₂ = 11

Octal 8 0–7 (345)₈ = 229

Decimal 10 0–9 (245)₁₀

0–9,
Hexadecimal 16 (2F)₁₆ = 47
A–F (A=10…F=15)

1.5.2 Bits and Bytes

1. Bit (Binary Digit):


The smallest unit of data in a computer, represented as 0 or
1. All computations in digital systems are based on bits.
2. Nibble:
A group of 4 bits.
3. Byte:
A group of 8 bits. One byte can represent a single character,
number, or symbol using encoding methods such as ASCII
or Unicode.

26
CS25C03 - ESSENTIALS OF COMPUTING REG 25

4. Memory Measurement Units:


Bytes are used to measure storage capacity and file sizes.

Table: Conversion of Storage Units

Unit Equivalent Value

1 Byte 8 Bits

1 Kilobyte (KB) 1024 Bytes

1 Megabyte (MB) 1024 KB

1 Gigabyte (GB) 1024 MB

1 Terabyte (TB) 1024 GB

1 Petabyte (PB) 1024 TB

1 Exabyte (EB) 1024 PB

1 Zettabyte (ZB) 1024 EB

1 Yottabyte (YB) 1024 ZB

1 Brontobyte 1024 YB

1 Geopbyte 1024 Brontobytes

27
CS25C03 - ESSENTIALS OF COMPUTING REG 25

1.5.3 Text Representation (Character Encoding)


Computers cannot understand alphabets or symbols directly.
They are represented in binary using character encoding
standards.

1.EBCDIC (Extended Binary Coded Decimal Interchange


Code):

 Developed by IBM in the 1960s.


 Uses 8 bits to represent 256 characters.
 Mostly used in mainframes and commercial applications

2.ASCII (American Standard Code for Information


Interchange):

 A 7-bit code (128 characters) extended to 8 bits (256


characters).
 Represents English alphabets (uppercase & lowercase),
numbers, punctuation, and control codes.
 Example: A = 65 (01000001 in binary)

Character Decimal Value ASCII Code (Binary)

A 65 01000001

B 66 01000010

a 97 01100001

0 48 00110000

28
CS25C03 - ESSENTIALS OF COMPUTING REG 25

3.Extended ASCII:

 Expands ASCII to 8 bits.


 Provides 256 character representations including special
symbols, line-drawing characters, and international
characters.

4.Unicode:

 A universal character encoding standard.


 Uses 16 to 32 bits, covering characters from almost all
world languages.
 Supports alphabets, ideographs, symbols, and emojis.
 Example: Tamil letter "அ" → U+0B85.

1.6 SPREAD SHEETS

Spreadsheets are powerful software applications used to


organize, calculate, and analyze data in a tabular format. They
allow users to perform a wide range of basic operations such as
entering data, performing arithmetic calculations, applying
formulas, sorting, and filtering information.

These features make spreadsheets an essential tool for handling


financial records, academic tasks, business planning, and
scientific analysis.

In addition to data management, spreadsheets also provide data


visualization tools such as charts, graphs, and pivot tables.

29
CS25C03 - ESSENTIALS OF COMPUTING REG 25

These tools transform raw data into visual representations,


making it easier to identify patterns, trends, and insights for
decision-making.

1.6.1 USING SPREADSHEETS FOR BASIC


OPERATIONS ON DATA

Spreadsheets (such as Microsoft Excel, Google Sheets, and


LibreOffice Calc) are one of the most widely used tools for
handling data. They allow users to enter, organize, calculate, and
analyze information efficiently. A spreadsheet is arranged in
rows and columns, where each cell can hold text, numbers, or
formulas.

30
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Spreadsheets are commonly used in education (mark sheets,


attendance records), business (accounts, payroll), and research
(data analysis, reports).

Basic Operations in Spreadsheets

1.6.1.1.Data Entry and Editing

 Users can enter text, numbers, or formulas in a cell.


 Editing allows updating or modifying the contents easily.

Example:

A B

Student Marks

John 78

1.6.1.2 Arithmetic Operations

 Spreadsheets allow basic arithmetic using formulas.


 Operators: + (addition), - (subtraction), * (multiplication), /
(division).

Example:

31
CS25C03 - ESSENTIALS OF COMPUTING REG 25

A B C D

Student Sub1 Sub2 Total

John 78 82 =B2+C2

Anita 85 90 =B3+C3

David 92 88 =B4+C4

After applying formulas, the Total column will display:

 John → 160
 Anita → 175
 David → 180

1.6.1.3 Using Built-in Functions


Spreadsheets provide built-in functions to perform quick
calculations.

Formula Description Result

=SUM(B2:B4) Adds all values 255

=AVERAGE(B2:B4) Finds the average 85

=MAX(B2:B4) Highest value 92

32
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Formula Description Result

=MIN(B2:B4) Lowest value 78

1.6.1.4.Sorting and Filtering

 Sorting: Arranges data in ascending or descending order.


 Filtering: Displays only records that meet a condition

Example: Filtering for Marks > 80:

A B

Anita 85

David 92

1.6.1.5.Copying and AutoFill

 Formulas can be copied to other cells without retyping.


 AutoFill helps extend series such as dates, numbers, or
patterns.

Example: Typing 1, 2, 3 and dragging AutoFill will


continue the sequence 4, 5, 6 ….

33
CS25C03 - ESSENTIALS OF COMPUTING REG 25

1.6.1.6Cell Referencing

 Relative Reference: Adjusts automatically when copied


(e.g., =B2+C2).
 Absolute Reference: Fixed reference using $ (e.g.,
=$B$2+$C$2).

Example: Student Marksheet using Spreadsheet

A B C D E F

Avera
Student Sub1 Sub2 Total Grade
ge

=B2+ =IF(E2>=90,"A",IF(E2
John 78 82 =D2/2
C2 >=75,"B","C"))

=B3+ =IF(E3>=90,"A",IF(E3
Anita 85 90 =D3/2
C3 >=75,"B","C"))

=B4+ =IF(E4>=90,"A",IF(E4
David 92 88 =D4/2
C4 >=75,"B","C"))

34
CS25C03 - ESSENTIALS OF COMPUTING REG 25

After Applying Formulas

A B C D E F

Student Sub1 Sub2 Total Average Grade

John 78 82 160 80 B

Anita 85 90 175 87.5 B

David 92 88 180 90 A

Explanation of Formulas

 Total: =B2+C2 → Adds marks of Sub1 and Sub2.


 Average: =D2/2 → Divides total by number of subjects.
 Grade: =IF(E2>=90,"A",IF(E2>=75,"B","C")) → Assigns
grade based on average.

1.6.2 DATA VISUALIZATION IN EXCEL

Data visualization in Excel is a powerful way to transform


complex datasets into clear, interactive visuals that are easy to
understand and analyze. Whether you are presenting sales
performance, tracking project progress, or comparing trends,
using charts and graphs in Excel can make your data more
impactful and accessible.

35
CS25C03 - ESSENTIALS OF COMPUTING REG 25

In this guide, we will explore various examples of data


visualization in Excel, including column charts, how
to create and customize charts for specific data, format
chart areas, and create sparklines for quick data insights. By
the end of this article, you'll have the skills to create engaging
visuals that enhance your ability to interpret and present data
effectively.
How to Data Visualization in Excel
Learn how to create and customize various types of data
visualizations in Excel, including charts, sparklines, and other
visual tools to enhance data analysis.

Step 1: Open the Excel Spreadsheet


Open the Excel file containing the data you wish to visualize or
select the data you want to work with.

Step 2: Insert a Chart


Click on the Insert tab and select a chart from the available
options. Alternatively, you can quickly create a chart by
selecting a cell within your Excel data and pressing
the F11 function key.

Step 3: Customize Your Chart


A chart will be generated based on the data entered in the
Excel sheet. You can design and style your chart with various
styles and colors by selecting the Design tab. In Excel 2010,
the Design tab will appear when you click on the chart.

36
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Examples of Data Visualization in Excel


Here are some examples of data visualization techniques in
Excel to help you effectively represent and analyze your data.

Example 1: Column Chart

The Excel data is as follows:

The column chart obtained for the data by following the above
steps:

37
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Example 2: Creating and Customizing Charts for Specific


Data in Excel

Here’s an example of data visualization in Excel, showing how


to create and customize charts for specific data columns, adjust
data selection, and enhance the chart’s design.
Step 1: Select the Required Data Columns
When your Excel data contains multiple columns and you want
to create a chart for only specific columns, select the columns
you need.

38
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Step 2: Insert a Chart


After selecting the necessary columns, press the F11 function
key or click on the Insert tab and select a chart from the
available options.

Step 3: Adjust Data Selection


To modify the data used for the chart, right-click on the chart
and click the Select Data option. You can then add or remove
data for the chart.

Step 4: Swap Rows and Columns

39
CS25C03 - ESSENTIALS OF COMPUTING REG 25

If you need to swap the rows and columns in your chart, use
the Switch Row/Column option available in the Design tab.

Step 5: Change Chart Type


To experiment with different chart types, click on the Change
Chart Type option in the Design tab.

Step 6: Customize the Chart Using the Layout Tab


For further customization, go to the Layout tab. Here, you can
edit the chart title, add labels, include a legend, and add
horizontal or vertical grid lines to make your chart clearer.

Example 3: Formatting Chart Area

To format the chart area, right-click on the chart and select the
option 'Format chart Area'.

40
CS25C03 - ESSENTIALS OF COMPUTING REG 25

The format chart area provides various options for formatting


the chart like Filling the chart with patterns and solid colors,
Border colors, Styles for borders, the shadow effect for your
chart, and many more. Formatting makes the chart look more
attractive and colorful.

Example 4: Creating Sparklines

Sparklines in Excel are small charts that fit in the data cells of
the excel sheets.

Steps for Creating Spark Lines:

Step 1: Select the Excel Data Range


Highlight the range of data in your Excel sheet that you want
to use for sparklines, as shown in the figure below.

41
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Step 2: Insert Sparklines


Click on the Sparklines option in the Insert tab and choose
one of the three sparkline types available (Line, Column, or
Win/Loss).

Step 3: Define the Location and Data Range


Enter the Location Range (where you want the sparklines to
appear) and the Data Range (the data to be visualized) for the
sparklines. Then, click OK.
Step 4: View the Sparklines
The sparklines will be displayed in the F, G, H columns,
showing the respective line, column, and win/loss sparklines.

Step 5: Color the Sparklines


You can customize the color of the sparklines by selecting
the Design tab. From there, choose the desired color options to
enhance the appearance of the sparklines, as shown below.

42
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Step 6: Mark Data Points and Change Sparkline Color


You can mark specific data points in the sparklines and change
their color by selecting the options available in the Design tab.
This allows you to highlight key data points and customize the
sparkline color for better visualization.

1.7 IMPORTANT TWO MARKS

1) What is a computer?
A computer is an electronic device that accepts data as input,
processes it according to instructions, stores information,
and provides the output.

2) List any two characteristics of computers.


Computers are fast in processing data and provide accurate
results. They can also store large amounts of data.

3) Who is known as the Father of Computers?


Charles Babbage is known as the Father of Computers for
designing the Analytical Engine, the first mechanical
computer.

4) What are the main units of a computer system?


The main units are Input Unit, Central Processing Unit

43
CS25C03 - ESSENTIALS OF COMPUTING REG 25

(CPU), Output Unit, and Memory.

5) Name the technology used in first-generation computers.


First-generation computers used vacuum tubes for
processing and memory.

6) Which generation of computers used microprocessors?


Fourth-generation computers used microprocessors, which
integrated the CPU on a single chip.

7) Expand ENIAC.
ENIAC stands for Electronic Numerical Integrator and
Computer.
8) Which generation of computers used Artificial
Intelligence (AI)?
Fifth-generation computers focus on artificial intelligence
and use technologies like parallel processing.

9) Name two types of computers based on size.


Supercomputers and Microcomputers are classified based
on size and processing capacity.

10) Differentiate between Analog and Digital computers.


Analog computers process continuous data, while digital
computers process discrete or binary data.

11) Give two examples of microcomputers.


Desktop computers and laptops are examples of
microcomputers used for personal and office tasks.

12) Which type of computer is used for weather forecasting?


Supercomputers are used for complex calculations like

44
CS25C03 - ESSENTIALS OF COMPUTING REG 25

weather forecasting due to their high speed.

13) Mention two applications of computers in education.


Computers are used for online learning platforms and
managing digital library resources in education.

14) List any two uses of computers in business.


Computers are used for payroll processing and maintaining
business records efficiently.

15) How are computers used in healthcare?


Computers assist in patient record management, medical
imaging, and diagnostic procedures.
16) What is the binary number system?
The binary number system uses only two digits, 0 and 1, to
represent all data in computers.

17) How many bits make one byte?


One byte consists of 8 bits, which can represent 256
different values.

18) Convert the binary number 1010 into decimal.


The binary number 1010 equals 10 in decimal form.

19) Write any two basic arithmetic operators used in


spreadsheets.
Addition (+) and multiplication (*) are commonly used
arithmetic operators in spreadsheets

45
CS25C03 - ESSENTIALS OF COMPUTING REG 25

UNIT II COMPUTATIONAL THINKING

SYLLABUS

What is Computational Thinking, Decomposition, Abstraction,


Real World Information to Computable Data, Number Systems,
Conversions among Number systems, what is Logic, Boolean
Logic, Applications of Propositional Logic.

Computational Thinking (CT) is a systematic problem-solving


approach that takes inspiration from computer science principles but
is applicable in all disciplines. It allows humans to tackle complex,
ambiguous problems by breaking them into smaller, logical steps that
can be solved by people or machines.

46
CS25C03 - ESSENTIALS OF COMPUTING REG 25

2.1 COMPUTATIONAL THINKING


2.1.1 Definition
Computational thinking is a powerful problem-solving methodology
that draws from the fundamental concepts of computer science. It is
not about learning to code, but rather about developing a way of
thinking that allows you to formulate problems and their solutions in a
manner that is both clear and structured, making them understandable
to a computer. As defined by Wing (2006), it is "the thought processes
involved in formulating a problem and expressing its solution(s) in a
way that a computer... can effectively carry out."

The core of computational thinking lies in four key pillars:

1. Decomposition: Breaking down a complex problem into


smaller, more manageable parts.
2. Pattern Recognition: Identifying similarities or patterns
among smaller, decomposed problems.
3. Abstraction: Focusing on the essential information while
ignoring irrelevant details.
4. Algorithm Design: Developing a step-by-step solution to the
problem, or a set of rules to follow.

These four pillars work together to provide a systematic and logical


approach to problem-solving that is applicable to a wide range of
fields, not just computing.
2.1.2 Importance
In the modern digital age, computational thinking is an indispensable
skill for everyone. Its importance extends far beyond the realm of
computer science, influencing how we approach challenges in various
disciplines.

47
CS25C03 - ESSENTIALS OF COMPUTING REG 25

1. Enhances Problem-Solving Skills: By providing a structured


framework, computational thinking enables individuals to
tackle problems that seem too complex or overwhelming. It
fosters a systematic and logical mindset, moving from a vague
idea to a precise, actionable plan. This is a skill that is
valuable in all aspects of life, from organizing a project to
solving a scientific puzzle.
2. Promotes Automation and Efficiency: Understanding how
to decompose a task and design an algorithm allows us to
create solutions that can be automated. This is the foundation
of modern technology, where repetitive or data-intensive tasks
can be executed by computers, freeing up human time for
more creative and strategic endeavors.
3. Interdisciplinary Applicability: Computational thinking is
not limited to STEM fields. A journalist might use it to sort
and filter a large dataset of documents to find a story. An
artist might use it to design a fractal pattern for a piece of
digital art. A musician might use it to analyze and synthesize
complex harmonies. It is a universal skill that empowers
individuals to innovate in their respective fields.
4. Foundation for Digital Literacy: In a world increasingly
driven by technology, computational thinking serves as a form
of "meta-literacy." It helps individuals understand the
underlying logic of the software and applications they use
every day, making them more informed and capable
consumers and creators of technology.
5. more informed and capable consumers and creators of
technology.

48
CS25C03 - ESSENTIALS OF COMPUTING REG 25

2.2 DECOMPOSITION

Decomposition is the first and most critical step in computational


thinking. It is the process of breaking down a complex problem or
system into smaller, more manageable sub-problems. This strategy
transforms an intimidating challenge into a series of smaller, more
easily solvable tasks. By focusing on one small part at a time, we can
avoid feeling overwhelmed and can more effectively find solutions.

Example 1: Planning a Vacation

 Large Problem: Plan a family vacation.


 Decomposition:

 Choose a destination.
 Book transportation (flights, train tickets, etc.).
 Find and book accommodation (hotel, Airbnb).
 Create a daily itinerary of activities.
 Plan the budget and manage expenses.
 Pack the luggage.

 Each of these sub-problems can be further decomposed. For


example, "Book transportation" could be broken down into
"Research flight prices," "Choose airline," and "Purchase
tickets." This methodical approach ensures that no important
step is missed.

Example 2: Making a Sandwich

 Large Problem: Make a sandwich.


 Decomposition:

49
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 Get the bread.


 Get the fillings (meat, cheese, vegetables).
 Get the condiments (mayonnaise, mustard).
 Assemble the sandwich:

 Lay out two slices of bread.


 Spread condiments on one or both slices.
 Layer the fillings.
 Place the second slice of bread on top.

 Cut the sandwich (optional).


 Serve.

2.3 ABSTRACTION

Abstraction is the act of simplifying a problem by removing


unnecessary details and focusing only on the information that is
relevant to solving the problem. It allows us to create a generalized
model or representation of a problem that can be applied to many
different situations. This process helps us to manage complexity and
communicate our ideas more effectively.

Example 1: Using a GPS System

 The Real World (too complex): Every road, every house


number, every tree, every pothole, and every traffic light.
 The Abstract Model (the map): Only the crucial information
is shown: major roads, street names, intersections, and points
of interest.
 When you use a GPS, you don't need to know the detailed
geography of every street. The map provides an abstraction

50
CS25C03 - ESSENTIALS OF COMPUTING REG 25

that gives you just enough information to navigate from point


A to point B without being overwhelmed.

Example 2: Modeling a Student in a Program

 The Real-World Student (too complex): A student has a


name, age, height, hair color, social security number, favorite
food, etc.
 The Abstract Model (in a program): For a university's
course registration system, the only relevant information
about a student might be:
o studentID
o name
o enrolled_courses
o GPA
 The program doesn't need to know the student's eye color or
favorite food to function correctly. Abstraction simplifies the
problem by including only the necessary attributes.

2.4 REAL-WORLD INFORMATION TO COMPUTABLE


DATA

Computers, at their core, are designed to process and store data in a


specific, structured format. The world, however, is full of analog,
continuous information. The process of converting this real-world
information into a format that a computer can understand and
manipulate is called digitization. This is a foundational concept in all
digital technology.

51
CS25C03 - ESSENTIALS OF COMPUTING REG 25

1. Text

 Real-world: A handwritten letter or a printed book.


 Digitization: Each character (e.g., 'A', 'b', '!') is assigned a
unique numerical value, which is then represented in binary.
The most common standard for this is Unicode, which can
represent characters from virtually every writing system in the
world.
 For example, the character 'A' is represented by the decimal
value 6510​ , which is 010000012​ in binary.

2. Images

 Real-world: A photograph.
 Digitization: An image is divided into a fine grid of small
squares called pixels. Each pixel is assigned a numerical value
representing its color.
o For a grayscale image, a single number might
represent the brightness (e.g., 0 for black, 255 for
white).
o For a color image, a combination of numbers (e.g.,
RGB values) is used to represent the mix of red, green,
and blue light.
 Example: A pixel with the hexadecimal color
code #FF0000 is a computable representation of the color red.

3. Sound

 Real-world: A continuous sound wave.


 Digitization: The sound wave is measured at regular, high-
speed intervals. This process is called sampling. Each

52
CS25C03 - ESSENTIALS OF COMPUTING REG 25

measurement, or sample, is assigned a numerical value


representing the amplitude of the wave at that point in time.
 The number of samples per second is the sampling rate, and
the number of bits used for each sample is the bit depth.
Higher rates and depths result in higher fidelity audio.

4. Numbers

 Real-world: The temperature from a thermometer, the stock


price, or the population of a city.
 Digitization: Numerical data is often the easiest to convert, as
it is already discrete. It can be directly represented in the
number system a computer uses (e.g., binary).

2.5 NUMBER SYSTEMS

A number system is a way of expressing numbers using a set of


symbols (called digits) and rules. Every number system has its own
base (or radix), which denotes the number of unique digits it uses.
The base determines how numbers are represented and interpreted.

In computer science, different number systems play a crucial role.


While humans usually rely on the decimal system (base 10),
computers internally use the binary system (base 2). For
convenience and compact representation, octal (base 8) and
hexadecimal (base 16) are also used in computing.

53
CS25C03 - ESSENTIALS OF COMPUTING REG 25

2.5.1 Binary

Number System with base value 2 is termed as Binary number


system. It uses 2 digits i.e. 0 and 1 for the creation of numbers. The
numbers formed using these two digits are termed Binary Numbers.
The binary number system is very useful in electronic devices and
computer systems because it can be easily performed using just two
states ON and OFF i.e. 0 and 1.

 Decimal Numbers 0-9 are represented in binary as: 0, 1,


10, 11, 100, 101, 110, 111, 1000, and 1001

 For example, 14 can be written as (1110)2, 19 can be


written as (10011)2 and 50 can be written as (110010)2.

2.5.2 Decimal

In the decimal number system, the numbers are represented with


base 10. The way of denoting the decimal numbers with base 10 is
also termed as decimal notation. This number system is widely used in

54
CS25C03 - ESSENTIALS OF COMPUTING REG 25

computer applications. It is also called the base-10 number system


which consists of 10 digits, such as, 0,1,2,3,4,5,6,7,8,9. Each digit in
the decimal system has a position and every digit is ten times more
significant than the previous digit. Suppose, 25 is a decimal number,
then 2 is ten times more than 5.

Some examples of decimal numbers are:-

(12)10, (345)10, (119)10, (200)10, (313.9)10

A number system which uses digits from 0 to 9 to represent a number


with base 10 is the decimal system number. The number is expressed
in base-10 where each value is denoted by 0 or first nine positive
integers. Each value in this number system has the place value of
power 10. It means the digit at the tens place is ten times greater than
the digit at the unit place. Let us see some more examples:

55
CS25C03 - ESSENTIALS OF COMPUTING REG 25

(92)10 = 9×101+2×100

(200)10 = 2×102+0x101+0x100

The decimal numbers which have digits present on the right side of
the decimal (.) denote each digit with decreasing power of 10. Some
examples are:

(30.2)10= 30×101+0x100+2×10-1

(212.367)10 = 2×102+1×101+2×100+3×10-1+6×10-2+7×10-3

2.5.3 Octal

The octal number system is a base-8 system using digits 0 through 7.


It is often used in computer systems because it can easily represent
binary digits. Each octal digit corresponds to exactly three binary
digits. This makes it a compact way to represent binary data without
resorting to the complexity of hexadecimal.

For example: 228, 138, 178, etc., are octal numbers.

56
CS25C03 - ESSENTIALS OF COMPUTING REG 25

2.5.4 Hexadecimal

The hexadecimal number system is a base-16 system. It uses the


digits 0-9 and the letters A-F to represent the values 10 through 15.
Hexadecimal is widely used in computing, particularly for
representing memory addresses, color codes in web design
(e.g., #FFFFFF for white), and other binary data in a more human-
readable form. Each hexadecimal digit represents exactly four binary
digits.

Example: (AB12)16

Place value of each digit in (AB12)16 is,

= A×163 + B×162 + 1×161 + 2×160

2.6 CONVERSIONS AMONG NUMBER SYSTEMS

Mastering number system conversions is a fundamental skill. Here are


detailed, step-by-step methods and examples for converting between
the most common systems.

BINARY TO OCTAL CONVERSION

Binary to Octal conversion is the process of changing a number


from the binary system (base 2) into the octal system (base 8).
This conversion is very simple because one octal digit
corresponds exactly to three binary digits.

57
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Example: To convert (11101011)2 into a decimal number.

Thus, a binary number can be directly converted to octal by grouping

58
CS25C03 - ESSENTIALS OF COMPUTING REG 25

the binary digits into sets of three (from right to left) and then
writing the equivalent octal value for each group.

This method is widely used in computer science because it helps


to represent long binary numbers in a shorter and more
readable form.

Rule:

 Octal = Base 8 → digits are 0 to 7


 To convert binary to octal, group binary digits in 3s (from
right side).
 Each group of 3 binary digits = 1 octal digit.

Steps:

1. Write the binary number.


2. Group digits in sets of 3 from the right.
o Add extra zeros in the leftmost group if needed.
3. Convert each group of 3 binary digits into its decimal value
(0–7).
4. Write the octal digits together.

Example 1:

Convert 10112​ into octal.

Step 1: Binary number = 10112


Step 2: Group into 3 bits → 001 011
Step 3: Convert each group:

59
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 0012​ =1
 0112=3

Step 4: Combine → 138​

Answer: 10112​ =138​

Example 2:

Convert 1101012​ into octal.

Step 1: Binary = 1101012


Step 2: Group into 3 bits → 110 101
Step 3: Convert each group:

 1102=6
 1012=5

Step 4: Combine → 658

Answer: 1101012=658

60
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Example 3:

Convert 10011102​ into octal.


Step 1: Binary = 10011102​
Step 2: Group → 001 001 110
Step 3: Convert each group:

 0012=1
 0012=1
 1102=6
 Step 4: Combine → 1168

Answer: 10011102=1168​

BINARY TO HEXA DECIMAL CONVERSION

The binary number system (base 2) uses only two digits: 0


and 1.
The hexadecimal number system (base 16) uses 16 symbols:

0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F

Here, A = 10, B = 11, C = 12, D = 13, E = 14, F = 15.

For converting just group binary digits into sets of 4 and replace each
group with the corresponding hex digit.
Steps for Binary → Hexadecimal Conversion

1. Write the binary number.


2. Group digits into 4 bits (from right to left).
o Add extra zeros in the left group if needed.
3. Convert each 4-bit group into decimal.
61
CS25C03 - ESSENTIALS OF COMPUTING REG 25

4. Write the equivalent hex digit (0–9 or A–F).


5. Combine all hex digits.

Example 1:

Convert 1011012​ into hexadecimal.

Step 1: Binary = 101101


Step 2: Group into 4 bits → 0010 1101
Step 3: Convert each group:

 00102=2
 11012=13=D

Step 4: Write hex → 2D16

Answer: 1011012=2D16

Example 2:

Convert 1001110112​ into hexadecimal.

62
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Step 1: Binary = 100111011


Step 2: Group → 0001 0011 1011
Step 3: Convert:

 00012=1
 00112=3
 10112=11=B

Step 4: Write hex → 13B16​

Answer: 1001110112=13B16

DECIMAL TO BINARY CONVERSION

The decimal system (base 10) uses digits 0–9.


The binary system (base 2) uses only 0 and 1.

To convert decimal to binary, we repeatedly divide the decimal


number by 2 (the base of binary) and record the remainders.

Binary numbers use base-2. To convert a decimal number to


binary, follow the steps given below:
 Step 1: Divide the Decimal Number with the base of the
number system to be converted to. Here the conversion
is to binary, hence the divisor will be 2.

 Step 2: The remainder obtained from the division will


become the least significant digit of the new number.

 Step 3: The quotient obtained from the division will


become the next dividend and will be divided by the
base i.e. 2.

63
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 Step 4: The remainder obtained will become the second


least significant digit i.e. it will be added to the left of
the previously obtained digit.

Now, the steps 3 and 4 are repeated until the quotient obtained
becomes 0, and the remainders obtained after each iteration are
added to the left of the existing digits.
After all the iterations are over, the last obtained remainder
will be termed as the Most Significant digit.

DECIMAL TO OCTAL CONVERSION

Octal numbers use base-8. Here’s the process:


 Step 1: Divide the Decimal Number with the base of the
number system to be converted to. Here the conversion is to
octal, hence the divisor will be 8.

 Step 2: The remainder obtained from the division will


become the least significant digit of the new number.

 Step 3: The quotient obtained from the division will become


the next dividend and will be divided by base i.e. 8.

64
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 Step 4: The remainder obtained will become the second


least significant digit i.e. it will be added to the left of the
previously obtained digit.

Now, the steps 3 and 4 are repeated until the quotient obtained
becomes 0, and the remainders obtained after each iteration are
added to the left of the existing digits.

DECIMAL TO HEXADECIMAL CONVERSION

Hexadecimal uses base-16, with digits 0–9 and A–F (where A = 10,
B = 11, C = 12, D = 13, E = 14, F = 15). Follow these steps:

 Step 1: Divide the Decimal Number with the base of the


number system to be converted to. Here the conversion is to
Hex hence the divisor will be 16.

 Step 2: The remainder obtained from the division will


become the least significant digit of the new number.

 Step 3: The quotient obtained from the division will become


the next dividend and will be divided by base i.e. 16.

65
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 Step 4: The remainder obtained will become the second


least significant digit i.e. it will be added to the left of the
previously obtained digit.

Now, the steps 3 and 4 are repeated until the quotient obtained
becomes 0, and the remainders obtained after each iteration are
added to the left of the existing digits.

NOTE: If the remainder is 10–15, use A–F (e.g., A = 10, B = 11, C


= 12, D = 13, E = 14, F = 15).

OCTAL TO DECIMAL CONVERSION

Octal numbers are represented in base 8, but the decimal


numbers are of base 10. Hence, to convert an octal number to a
decimal number, the base of that number is to be changed.

Follow the steps given below:

 Step 1: Multiply each digit of the Octal number with the place
value of that digit, starting from right to left i.e. from LSB to
MSB.

66
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 Step 2: Add the result of this multiplication and the decimal


number will be formed.

OCTAL TO BINARY CONVERSION

Octal numbers are represented in base 8, but the binary


numbers are of base 2. Hence, to convert an octal number to a
binary number, the base of that number is to be changed.

Follow the steps given below:

 Step 1: Write each digit of the octal number separately.

 Step 2: Convert each digit into an equivalent group of


three binary digits.

 Step 3: Combine these groups to form the whole binary


number.

67
CS25C03 - ESSENTIALS OF COMPUTING REG 25

OCTAL TO HEXADECIMAL CONVERSION

Octal numbers are represented in base 8, but the hexadecimal


numbers are of base 16. Hence, to convert an octal number to a
hex number, the base of that number is to be changed.

Follow the steps given below:

 Step 1: We need to convert the Octal number to Binary


first. For that, follow the steps given in the above
conversion.

 Step 2: Now to convert the binary number to Hex


number, divide the binary digits into groups of four
digits starting from right to left i.e. from LSB to MSB.

 Step 3: Add zeros before MSB to make it a proper group


of four digits(if required)

 Step 4: Now convert these groups into their relevant


decimal values.

68
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 Step 5: For values from 10-15, convert it into Hex


symbols i.e from A-F

HEXADECIMAL TO DECIMAL CONVERSION:

To convert a hexadecimal number to decimal (base-10), multiply each


digit by its corresponding power of 16 and sum the results.

Follow the steps given below:

 Step 1: Write the decimal values of the symbols used in


the Hex number i.e. from A-F

 Step 2: Multiply each digit of the Hex number with its


place value. Starting from right to left i.e. LSB to MSB.

 Step 3: Add the result of multiplication and the final


sum will be the decimal number.

69
CS25C03 - ESSENTIALS OF COMPUTING REG 25

HEXADECIMAL TO BINARY CONVERSION

Each hexadecimal digit corresponds to a 4-bit binary sequence.


Convert each digit individually and combine.

Follow the steps given below:

 Step 1: Convert the Hex symbols into their equivalent


decimal values.

 Step 2: Write each digit of the Hexadecimal number


separately.

 Step 3: Convert each digit into an equivalent group of


four binary digits.

 Step 4: Combine these groups to form the whole binary


number.

70
CS25C03 - ESSENTIALS OF COMPUTING REG 25

HEXADECIMAL TO OCTAL CONVERSION:

Convert hexadecimal to binary, group the binary digits into


sets of three (right to left), and convert each group to its octal
equivalent.
Follow the steps given below:

 Step 1: We need to convert the Hexadecimal number to


Binary first. For that, follow the steps given in the above
conversion.

 Step 2: Now to convert the binary number to an Octal


number, divide the binary digits into groups of three
digits starting from right to left i.e. from LSB to MSB.

 Step 3: Add zeros before MSB to make it a proper group


of three digits(if required)

 Step 4: Now convert these groups into their relevant


decimal values.

71
CS25C03 - ESSENTIALS OF COMPUTING REG 25

2.7 LOGIC

Logic is the study of principles and methods of reasoning. In


computing, logic is the framework for all decision-making and control
flow. An algorithm is essentially a sequence of logical steps. A key
concept in logic is a proposition, which is a statement that can be
definitively classified as either true or false.

Example Propositions:

 "The Earth is round." (True)


 "The sun rises in the west." (False)
 "5+3=8." (True)
 "This sentence is false." (Paradoxical, and thus not a valid
proposition).

72
CS25C03 - ESSENTIALS OF COMPUTING REG 25

In programming, these propositions are represented by Boolean values


(true or false). A conditional statement like if (age > 18) is a logical
test that evaluates to either true or false, determining whether a block
of code will execute.

2.8 BOOLEAN LOGIC

Boolean Logic is a special kind of mathematics where the values


are only:

 1 = TRUE = ON
 0 = FALSE = OFF

Computers, mobile phones, calculators, and all digital devices


work using Boolean logic.
Every circuit inside a computer decides whether electricity
flows (1) or not (0) using these rules.

Think of it as yes/no decisions.

Boolean logic is a fundamental branch of logic that operates on binary


variables and values (true or false, 1 or 0). It is the language of digital
circuits and is used to create complex decisions from simple binary
inputs. The three basic logical operations are AND, OR, and NOT.

Boolean logic is a system of logic dealing with truth values, either


TRUE or FALSE, that forms the basis of digital circuits and search
algorithms. It uses operators like AND, OR, and NOT to combine or
manipulate these truth values to produce a result, with common
applications in computing, digital electronics, and database
searching.

73
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Core Concepts

 Truth Values:
The fundamental values in Boolean logic are TRUE and
FALSE, often represented as 1 and 0 in digital systems.
 Boolean Operators:

These are the logical connectives that manipulate truth


values:

 AND: The result is TRUE only if all conditions are


TRUE.
 OR: The result is TRUE if at least one of the
conditions is TRUE.
 NOT: The result is the opposite of the input; it flips
TRUE to FALSE and FALSE to TRUE.

How It Works

 Expressions:
You combine variables or conditions using the AND, OR,
and NOT operators to create a Boolean expression.
 Logic Gates:
In digital electronics, transistors are configured to perform
these Boolean operations, creating logic gates that control
electrical signals.
 Truth Tables:

74
CS25C03 - ESSENTIALS OF COMPUTING REG 25

These tables show all possible combinations of inputs and


their corresponding outputs for a given Boolean operation.

Logic Gates

75
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Logic operations are performed using basic electronic components


called logic gates. These gates include:

• AND Gate: Output is high (1) only if all inputs are


high.

• OR Gate: Output is high if at least one input is high.

• NOT Gate: Output is the inverse of the input.

• NAND Gate: Output is low only when all inputs are


high.

• NOR Gate: Output is high only if all inputs are low.

• XOR (Exclusive OR): Output is high only if inputs


are different.

• XNOR (Exclusive NOR): Output is high if inputs are


the same

AND Operation (·)

Rule: Output is 1 only if both inputs are 1.

 Symbol: A⋅ B or just AB
 Real life: A lamp connected to two switches in series.
Both switches must be ON for the lamp to glow.

76
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Truth Table (AND)

A B A·B

0 0 0

0 1 0

1 0 0

1 1 1

Examples:

 1⋅ 1=1 → Both ON → Lamp glows.


 1⋅ 0=0 → One OFF → Lamp doesn’t glow.

OR Operation (+)

Rule: Output is 1 if any input is 1.

 Symbol: A+B
 Real life: A lamp connected to two switches in parallel.
If any one switch is ON, the lamp glows.

Truth Table (OR)

A B A+B

77
CS25C03 - ESSENTIALS OF COMPUTING REG 25

A B A+B

0 0 0

0 1 1

1 0 1

1 1 1

Examples:

 1+0=1 → One ON → Lamp glows.


 0+0=0→ Both OFF → Lamp doesn’t glow.

NOT Operation (¬ or ′)

Rule: Output is the opposite of the input.

 Symbol: A′ or A
 Real life: A button that flips the result. If you press it ON,
it forces OFF, and vice versa.

Truth Table (NOT)

A A′

0 1

78
CS25C03 - ESSENTIALS OF COMPUTING REG 25

A A′

1 0

Examples:

 If input = 0 → output = 1
 If input = 1 → output = 0

DERIVED BOOLEAN OPERATIONS

These are combinations of the basic operations.

NAND (NOT AND)

 Formula: (A⋅ B)′


 Rule: Output is opposite of AND.

A B A·B (A · B)′

0 0 0 1

0 1 0 1

1 0 0 1

1 1 1 0

79
CS25C03 - ESSENTIALS OF COMPUTING REG 25

NOR (NOT OR)

 Formula: (A+B)′
 Rule: Output is opposite of OR.

A B A + B (A + B)′

0 0 0 1

0 1 1 0

1 0 1 0

1 1 1 0

XOR (Exclusive OR)

 Symbol: A⊕B
 Rule: Output is 1 if inputs are different, 0 if same.

A B A⊕B

0 0 0

0 1 1

1 0 1

80
CS25C03 - ESSENTIALS OF COMPUTING REG 25

A B A⊕B

1 1 0

Real life: A room light controlled by two different switches.


The light turns ON only if one switch is ON and the other is
OFF.

Boolean Algebra Laws (Simplification Rules)

1. Identity Law
o A+0=A
o A⋅ 1=A
2. Null Law
o A+1=1
o A⋅ 0=0
3. Idempotent Law
o A+A=A
o A⋅ A=A
4. Complement Law
o A+A′=1
o A⋅ A′=0
5. Double Negation
o (A′)′=A

These rules help to simplify Boolean expressions, which


reduces the size of digital circuits.

81
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Applications

 Digital Electronics:
Boolean logic is the foundation for designing digital circuits,
microprocessors, and other computer systems.
 Computer Programming:
Many programming languages use Boolean data types and
operators to make logical decisions and control program
flow.
 Database and Web Searching:

Search engines use Boolean operators to refine searches,


ensuring that retrieved results contain all specified terms
(AND) or at least one of them (OR).

2.9 APPLICATIONS OF PROPOSITIONAL LOGIC

Propositional logic is a cornerstone of computer science with


widespread applications.

1. Digital Circuit Design: The microchips inside a computer are


composed of millions of tiny electronic switches (transistors)
that act as logic gates. Boolean expressions are used to design
these circuits to perform arithmetic and control operations.
For example, a simple adder circuit uses AND and XOR gates
to add two binary numbers.
2. Database and Information Retrieval: Search engines and
database systems rely heavily on propositional logic. When
you use a search query like ( "computational thinking" AND
"definition" ) OR "problem solving", you are using Boolean

82
CS25C03 - ESSENTIALS OF COMPUTING REG 25

operators to filter and retrieve relevant information from a


vast dataset.
3. Artificial Intelligence and Expert Systems: In early AI
systems and rule-based expert systems, propositional logic
was used to represent knowledge and make inferences. For
example, a medical diagnosis system might use rules like: IF
(patient has fever) AND (patient has cough) THEN (consider
flu).
4. Programming and Software Engineering: Every time a
programmer uses an if statement, a while loop, or
a switch case, they are using logical expressions to control the
flow of the program. Complex expressions with
nested AND and OR operators allow for sophisticated
decision-making within an application.

2.10 IMPORTANT TWO MARKS

1) What is Computational Thinking?


Computational Thinking is a problem-solving approach that
involves breaking down problems, recognizing patterns, and
designing step-by-step solutions that can be implemented by
a computer.
2) What is decomposition in computational thinking?
Decomposition is the process of dividing a complex
problem into smaller, more manageable parts.
3) Define abstraction.
Abstraction is the process of hiding unnecessary details and
focusing only on the essential features of a problem.
4) What is meant by “real world information to
computable data”?
It refers to converting real-world problems and data into

83
CS25C03 - ESSENTIALS OF COMPUTING REG 25

formats (numbers, symbols, codes) that computers can


process.
5) What are number systems? Give examples.
Number systems are different ways of representing numbers.
Examples: Decimal (base 10), Binary (base 2), Octal (base
8), Hexadecimal (base 16).
6) Convert (1011)₂ to decimal.
(1011)₂ = 1×8 + 0×4 + 1×2 + 1×1 = 11 (decimal).
7) Convert (25)₁₀ to binary.
(25)₁₀ = (11001)₂.
8) What is logic?
Logic is the study of principles of valid reasoning and
making conclusions based on given facts.
9) What is Boolean Logic?
Boolean logic is a form of algebra where variables take
values TRUE (1) or FALSE (0) and are manipulated using
operators like AND, OR, and NOT.
10) Mention two applications of propositional logic.

 Used in designing digital circuits.


 Used in computer programming and automated reasoning.

84
CS25C03 - ESSENTIALS OF COMPUTING REG 25

UNIT III PROBLEM SOLVING BASICS

SYLLABUS

Problem Definition-Logical Reasoning-Decomposition-


Software Design Concepts-Algorithm: Concept, of an
Algorithm, Algorithm Representation, Algorithm Discovery-
Algorithmic Structures: Iterative Structures, Recursive
Structures- Efficiency and Correctness of Algorithms-
Implementation of Algorithms- Fundamental Algorithms:
Exchanging values of two variables, Counting, Summation of a
set of numbers, Factorial computation, Generation of Fibonacci
sequence, Reversing the digits of an integer, Base Conversion

3.1 PROBLEM DEFINITION

A problem in computing is a task that requires a solution


through logical reasoning, algorithm development, and
implementation. Defining the problem properly ensures clarity
in objectives, resources, and expected results.

 In programming, a problem is expressed as:

 Input(s): Information provided to the program.


 Process: Logical steps that transform input into
output.
 Output(s): Final result produced.

 Poorly defined problems → wasted time and incorrect


solutions.

85
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Step-by-Step Method

1. Identify the real-world challenge.


2. Analyze requirements → Inputs / Outputs.
3. Define scope and constraints.
4. Establish success criteria (how correctness will be
measured).
5. Break into smaller tasks.

Illustration Example

Problem: Find the largest number among three inputs.

 Input: Three numbers (a, b, c).


 Output: Largest number.
 Process: Compare numbers using conditional logic.

Pseudocode

Algorithm LargestOfThree

1. Input a, b, c

2. If a > b and a > c then

largest = a

Else if b > c then

largest = b

Else

86
CS25C03 - ESSENTIALS OF COMPUTING REG 25

largest = c

3. Print largest

End Algorithm

Flowchart Description

Program

#include <stdio.h>

int main() {

int a, b, c, largest;

printf("Enter first number: ");

87
CS25C03 - ESSENTIALS OF COMPUTING REG 25

scanf("%d", &a);

printf("Enter second number: ");

scanf("%d", &b);

printf("Enter third number: ");

scanf("%d", &c);

// Assume first number is largest

largest = a;

// Compare with second

if (b > largest) {

largest = b;

// Compare with third

if (c > largest) {

largest = c;

printf("Largest number is: %d\n", largest);

88
CS25C03 - ESSENTIALS OF COMPUTING REG 25

return 0;

Applications & Case Studies

Applications:

 Business: Find max profit among branches.


 Engineering: Max stress/strain values.
 Sports: Highest score from players.

Case Study: In election result systems, identifying the


candidate with maximum votes uses similar logic.

Comparisons / Notes / Tips

 Good problem definition saves 50% debugging time


later.
 Avoid vague statements like “find output” – specify
exact input/output.
 Problem definition in programming = Requirement
Analysis in software development.

3.2 LOGICAL REASONING

Logical reasoning is the ability to use structured thought


processes to arrive at conclusions. In computing, it is used to:

 Design algorithms.
 Debug errors.
 Ensure correctness of solutions.

89
CS25C03 - ESSENTIALS OF COMPUTING REG 25

It involves deductive reasoning (general → specific) and


inductive reasoning (specific → general).

Step-by-Step Method

1. Identify problem conditions.


2. Use rules to connect conditions.
3. Derive logical conclusions.
4. Apply decision-making in algorithms.

Example

Problem: Check if a year is a leap year.

Rule: Year divisible by 4 is leap, but divisible by 100 is not,


unless divisible by 400.

Pseudocode

Algorithm LeapYear
1. Input year
2. If (year % 400 == 0) then
print "Leap Year"
Else if (year % 100 == 0) then
print "Not Leap Year"
Else if (year % 4 == 0) then
print "Leap Year"
Else
print "Not Leap Year"
End Algorithm

90
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Flowchart Description

Program

#include <stdio.h>

int main() {

int year;

printf("Enter a year: ");

scanf("%d", &year);

if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0))


{

91
CS25C03 - ESSENTIALS OF COMPUTING REG 25

printf("Leap Year\n");

} else {

printf("Not a Leap Year\n");

return 0;

Applications & Case Studies

Applications:

 AI → Logical inference engines.


 Robotics → Conditional navigation.
 Banking → Transaction validation.

Case Study: Fraud detection uses logical rules (e.g., impossible


location/time combinations).

Notes / Tips

 Logical reasoning = backbone of if-else and loops in


coding.
 Always check all possible conditions (avoid missing
cases).

92
CS25C03 - ESSENTIALS OF COMPUTING REG 25

3.3 DECOMPOSITION

Decomposition is the process of breaking down a complex


problem into smaller, manageable sub-problems. This is a
fundamental principle in both computer science and
engineering problem solving. Instead of trying to solve a large
problem in one go, we divide it into modules or components that
can be solved independently and then combined to form the
complete solution.

 Also called “divide and conquer”.


 Leads to modularity, reusability, and simpler
debugging.
 Applied in algorithms, software design, data
structures, and even real-world engineering projects.

Step-by-Step Method of Decomposition

1. Understand the main problem – Identify the ultimate


goal.
2. Identify major tasks – Break the main problem into
core functional parts.
3. Subdivide further – Keep breaking down until each
subtask is simple enough.
4. Define interactions – Determine how subtasks
communicate or depend on each other.
5. Implement independently – Solve/test subtasks
separately.
6. Integrate – Combine the subtasks to solve the main
problem.

Illustration / Example

93
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Problem: Design a program to manage a student’s marks and


calculate their grade.

 Main Problem: Compute final grade of student.


 Decomposition:
 Input student details.
 Input subject marks.
 Compute total.
 Compute average.
 Assign grade.
 Print result.

Pseudocode

Algorithm StudentGrade
1. Input name, roll_no
2. Input marks for 5 subjects
3. total = sum(marks)
4. avg = total / 5
5. if avg >= 90 then grade = 'A'
6. else if avg >= 75 then grade = 'B'
7. else if avg >= 50 then grade = 'C'
8. else grade = 'F'
9. Print name, roll_no, total, avg, grade
End Algorithm

Flowchart Description

94
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Program

#include <stdio.h>

int main() {

char name[50], roll[20], grade;

int i, mark, total = 0;

float avg;

printf("Enter Student Name: ");

scanf("%s", name);

printf("Enter Roll Number: ");

95
CS25C03 - ESSENTIALS OF COMPUTING REG 25

scanf("%s", roll);

for(i = 1; i <= 5; i++) {

printf("Enter marks for subject %d: ", i);

scanf("%d", &mark);

total += mark;

avg = total / 5.0;

grade = (avg >= 90) ? 'A' : (avg >= 75) ? 'B' : (avg >= 50) ?
'C' : 'F';

printf("\n--- Student Report ---


\nName: %s\nRoll: %s\nTotal: %d\nAverage: %.2f\nGrade
: %c\n",

name, roll, total, avg, grade);

return 0;

Applications & Case Studies

 Software Engineering: Decomposing applications into


modules (e.g., login, database, UI).

96
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 Data Science: Breaking tasks into data collection,


preprocessing, model training, evaluation.
 Case Study: ATM System – decomposed into
authentication, transaction processing, balance inquiry,
withdrawal, deposit.

Comparisons / Notes / Tips

 Note: Each subtask should be independent but contribute to


solving the main problem.
 Tip: Stop decomposition when a subtask becomes simple
enough to be implemented as a function.
 Comparison: Decomposition in computing is similar to
work breakdown structure (WBS) in project management.

3.4 SOFTWARE DESIGN CONCEPTS

Software design is the process of transforming problem


requirements into a structured solution that can be
implemented in code. It focuses on how the system will work
internally, how components interact, and how to ensure
reliability, efficiency, and maintainability.

Software design concepts provide the principles and strategies


that guide developers when creating programs. Good design
ensures that:

 The solution is modular and easy to modify.

 The system is efficient and scalable.


 Code is reusable and reliable.
 The system can evolve with changing requirements.

97
CS25C03 - ESSENTIALS OF COMPUTING REG 25

3.4.2 Key Concepts of Software Design

1. Abstraction – Hiding unnecessary details and showing


only the essential features.
Example: A Car class might have start() and drive(),
while the complex engine workings are hidden.
2. Modularity – Dividing the program into independent
modules.
Example: Library management system with modules for
issue, return, and catalog search.
3. Encapsulation – Binding data and functions that operate
on the data into a single unit.
Example: A BankAccount class with private balance
and public deposit/withdraw methods.
4. Information Hiding – Exposing only what is necessary.
Example: APIs show only function names, not internal
implementation.
5. Reusability – Writing code that can be reused across
projects.
Example: Standard Python libraries like math and os.
6. Scalability – Ability of software to handle growing input,
users, or complexity.
7. Maintainability – Ease of fixing bugs or adding features
without breaking existing code.

3.4.5 Step-by-Step Method for Designing Software

1. Requirement Analysis – Understand what the system


should do.
2. System Design – Decide on the architecture (modules,
data flow, components).

98
CS25C03 - ESSENTIALS OF COMPUTING REG 25

3. Detailed Design – Describe algorithms, data structures,


and module interactions.
4. Implementation Plan – Assign coding tasks and plan
integration.
5. Testing & Verification – Ensure each module meets
requirements.

Illustration / Example

Problem: Online Food Ordering System

 Requirement: Customers should order food online.


 Decomposition into modules:
 Customer Registration
 Menu Display
 Order Placement
 Payment Processing
 Delivery Tracking
 Interaction: Each module communicates with a
database and user interface.

Pseudocode

Algorithm FoodOrderingSystem
1. Input user login details
2. Display menu items
3. User selects food items
4. Add items to cart
5. Process payment
6. Confirm order
7. Update delivery status
End Algorithm

99
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Flowchart Description

Program (Mini Example: Modular Design)

#include <stdio.h>

void display_menu() {

printf("1. Pizza - $10\n");

printf("2. Burger - $5\n");

printf("3. Pasta - $8\n");

int take_order(char *item) {

int choice;

100
CS25C03 - ESSENTIALS OF COMPUTING REG 25

printf("Enter your choice (1-3): ");

scanf("%d", &choice);

switch (choice) {

case 1:

sprintf(item, "Pizza");

return 10;

case 2:

sprintf(item, "Burger");

return 5;

case 3:

sprintf(item, "Pasta");

return 8;

default:

return 0; // invalid choice

101
CS25C03 - ESSENTIALS OF COMPUTING REG 25

int process_payment(int amount) {

int paid;

printf("Amount to pay: $%d\n", amount);

printf("Enter payment: ");

scanf("%d", &paid);

if (paid >= amount) {

printf("Payment Successful\n");

return 1; // success

} else {

printf("Payment Failed\n");

return 0; // fail

int main() {

char item[20];

102
CS25C03 - ESSENTIALS OF COMPUTING REG 25

int cost;

display_menu();

cost = take_order(item);

if (cost > 0) {

if (process_payment(cost)) {

printf("Order placed successfully for %s\n", item);

} else {

printf("Invalid choice.\n");

return 0;

Applications & Case Studies

 Application in Software Industry:


 Used in banking systems, hospital
management, e-commerce websites.
 Modular designs make cloud systems like AWS
and Google Cloud scalable.
 Case Study: ATM Software Design

103
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 Modules: Authentication, Transaction Processing,


Cash Dispensing.
 Modularity helps in upgrading only one module
(e.g., transaction limits) without affecting others.

Comparisons / Notes / Tips

 Note: Poor design leads to high maintenance costs.


 Tip: Always use modular, reusable code instead of
monolithic programs.
 Comparison:
 Procedural Design → Step-by-step functions.
 Object-Oriented Design → Classes and objects
encapsulating data + behavior.

3.5 ALGORITHM

3.5.1 CONCEPT OF AN ALGORITHM

An algorithm is a finite, step-by-step sequence of instructions


that provides a solution to a well-defined problem. In computer
science, algorithms form the foundation of all programming —
every task a computer performs, from sorting numbers to
driving a car autonomously, is guided by algorithms.

Key properties of algorithms:

1. Finiteness – The algorithm must terminate after a finite


number of steps.
2. Definiteness – Each step should be precisely defined.
3. Input – The algorithm may have zero or more inputs.
4. Output – At least one output must be produced.

104
CS25C03 - ESSENTIALS OF COMPUTING REG 25

5. Effectiveness – Each step should be basic enough to be


carried out in practice.

Step-by-Step Method for Algorithm Development

1. Understand the Problem – Identify the input and


expected output.
2. Plan the Approach – Think logically about how to
solve it.
3. Divide into Steps – Break into a sequence of clear
instructions.
4. Check Completeness – Ensure all cases are handled.
5. Write Algorithm/Pseudocode – Express in simple
structured form.
6. Test the Algorithm – Try with sample data to verify
correctness.

3.5.2 ALGORITHM REPRESENTATION

Explanation

Algorithms can be represented in multiple forms:

1. Natural Language – Using plain English.


o Example: “Add two numbers and print result.”
2. Pseudocode – Structured English resembling
programming.
3. Flowcharts – Visual representation using symbols
(ovals, rectangles, diamonds).
4. Code Implementation – Actual execution in a
programming language.

105
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Example

Problem: Check if a number is even or odd.

Pseudocode:

1. Input number n
2. If n mod 2 = 0 then print "Even"
3. Else print "Odd"

Flowchart Description:

106
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Program:

#include <stdio.h>

int main() {

int n;

printf("Enter a number: ");

scanf("%d", &n);

if (n % 2 == 0) {

printf("Even\n");

} else {

printf("Odd\n");

return 0;

107
CS25C03 - ESSENTIALS OF COMPUTING REG 25

3.5.3 ALGORITHM DISCOVERY

Explanation

Algorithm discovery is the process of finding or creating new


algorithms to solve problems efficiently. It requires logical
thinking, creativity, and optimization skills.

Methods for discovering algorithms:

1. Brute Force Method – Try all possible solutions


(simple but inefficient).
2. Greedy Method – Build solution step by step, choosing
the best option at each step.
3. Divide and Conquer – Break problem into smaller
subproblems (e.g., Merge Sort).
4. Dynamic Programming – Store solutions of
subproblems to avoid repetition.
5. Heuristic / AI Methods – Use intelligent guesses for
complex problems.

Example Problem: Finding Prime Numbers up to n

 Brute Force Algorithm: Check each number from 2 to


n by dividing with all numbers < n.
 Optimized Algorithm (Sieve of Eratosthenes):
Eliminate multiples of known primes.

C Program (Optimized):

#include <stdio.h>

108
CS25C03 - ESSENTIALS OF COMPUTING REG 25

#include <stdbool.h>

void sieve_of_eratosthenes(int n) {

bool primes[n+1];

int i, p;

// Initialize all entries as true

for (i = 0; i <= n; i++) {

primes[i] = true;

p = 2;

while (p * p <= n) {

if (primes[p]) {

// Mark multiples of p as not prime

for (i = p * p; i <= n; i += p) {

primes[i] = false;

109
CS25C03 - ESSENTIALS OF COMPUTING REG 25

p++;

// Print all prime numbers

for (i = 2; i <= n; i++) {

if (primes[i]) {

printf("%d ", i);

printf("\n");

int main() {

int n = 50;

sieve_of_eratosthenes(n);

return 0;

110
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Applications & Case Studies

 Case Study 1: Google Search uses algorithms for page


ranking (PageRank).
 Case Study 2: Cryptography uses algorithms for secure
data encryption.
 Case Study 3: Navigation apps (Google Maps) use
shortest path algorithms (Dijkstra’s).

Comparisons / Notes / Tips

 Note: One problem may have multiple algorithms —


choose the most efficient.
 Tip: Always analyze algorithm complexity (time &
space).
 Comparison:
 Brute Force → Easy but slow.
 Optimized Algorithms → Complex but efficient.

3.6 ALGORITHMIC STRUCTURES

Concept Explanation

Algorithmic structures are the basic building blocks used to


control the flow of an algorithm or program. They define how
instructions are executed — sequentially, conditionally,
repeatedly, or recursively.

The main categories of algorithmic structures include:

1. Sequential Structure – Instructions executed one after


another.

111
CS25C03 - ESSENTIALS OF COMPUTING REG 25

2. Conditional (Decision) Structure – Execution depends


on conditions.
3. Iterative (Looping) Structure – Repeating a block of
instructions until a condition is met.
4. Recursive Structure – A function calls itself to solve
subproblems.

In this section, we focus on Iterative and Recursive structures.

3.6.1 ITERATIVE STRUCTURES

Concept Explanation

Iteration means repeating a set of instructions multiple times


until a condition is satisfied. This is implemented using loops in
programming.

Types of loops in Python:

1. for loop – Repeats for a fixed number of times.


2. while loop – Repeats as long as a condition is true.
3. nested loops – A loop inside another loop.

Step-by-Step Method

1. Identify the part of the problem that repeats.


2. Determine the loop variable and termination condition.
3. Write the instructions inside the loop.
4. Update the loop variable (if needed).
5. Test the loop with edge cases.

Illustration / Example

112
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Problem: Print the first 5 natural numbers.

 Pseudocode:

1. Set i = 1
2. While i <= 5:
Print i
i=i+1

Flowchart :

Program

#include <stdio.h>

113
CS25C03 - ESSENTIALS OF COMPUTING REG 25

int main() {

int i;

// Using while loop

i = 1;

while (i <= 5) {

printf("%d\n", i);

i++;

printf("\n");

// Using for loop

for (i = 1; i <= 5; i++) {

printf("%d\n", i);

return 0;

Applications

114
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 Generating series (Fibonacci, primes).


 Searching & sorting algorithms.
 Repetitive tasks like file processing, simulations,
animations.

Notes & Tips

 Infinite loops occur if the termination condition is not


met.
 For definite repetition → use for.
 For indefinite repetition → use while.

3.6.2 RECURSIVE STRUCTURES

Concept Explanation

Recursion is a technique where a function calls itself to solve


smaller instances of a problem. It is widely used for problems
that can be broken down into similar subproblems.

Properties of recursion:

1. Base Case – Condition that stops recursion.


2. Recursive Case – Function calls itself with smaller input.

Step-by-Step Method

1. Define the problem in terms of smaller subproblems.


2. Identify the base case (simplest form).
3. Define the recursive call to handle reduced problems.
4. Ensure termination is guaranteed.

115
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Illustration / Example

Problem: Compute factorial of a number (n!).

 Pseudocode:

Algorithm Factorial(n)
1. If n == 0 then return 1
2. Else return n * Factorial(n-1)
End Algorithm

 Flowchart :

Program

#include <stdio.h>

116
CS25C03 - ESSENTIALS OF COMPUTING REG 25

// Recursive function for factorial

int factorial(int n) {

if (n == 0)

return 1;

else

return n * factorial(n - 1);

int main() {

int n = 5;

printf("Factorial of %d: %d\n", n, factorial(n));

return 0;

Applications of Recursion

 Mathematical Problems: Factorial, Fibonacci sequence,


GCD.
 Data Structures: Tree traversals, graph search (DFS).
 Algorithm Design: Divide and Conquer methods
(Merge Sort, Quick Sort).

117
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Case Study

Tower of Hanoi Problem – Classic recursive problem.

 Move n disks from source → destination using an


auxiliary peg.
 Recursive solution reduces n-disk problem to (n-1)-disk
problem.

Comparisons / Notes / Tips

 Iteration vs Recursion:
 Iteration uses loops, recursion uses function calls.
 Iteration is usually faster and memory efficient.
 Recursion is more elegant for problems with self-
similar structure (trees, graphs).
 Tip: Always define a base case, or recursion will lead to
infinite calls (stack overflow).

3.7 EFFICIENCY AND CORRECTNESS OF


ALGORITHMS

Concept Explanation

When we design an algorithm, it is not enough for it to just


solve the problem—it must also do so efficiently and correctly.

 Efficiency deals with how much time and memory an


algorithm consumes while solving a problem.
 Correctness ensures that the algorithm always
produces the right output for all valid inputs.

118
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Evaluating efficiency and correctness helps in selecting the best


algorithm among multiple options.

3.7.1 EFFICIENCY OF ALGORITHMS

Definition

Efficiency refers to the performance of an algorithm in terms of:

1. Time Complexity – How execution time grows with


input size.
2. Space Complexity – How much memory the algorithm
uses.

Step-by-Step Method to Analyze Efficiency

1. Identify the input size (n):


Example – number of elements in an array.
2. Count basic operations:
Example – comparisons in searching, swaps in sorting.
3. Express operations as a function of n.
4. Use Big-O, Big-Ω, and Big-Θ notations to represent
efficiency.

Illustrations / Examples

Example 1: Linear Search

 Search for an element in an array of size n.


 Worst case → element is at the end or not present.
 Time complexity = O(n).

119
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Example 2: Binary Search

 Requires sorted array.


 Repeatedly divides the array into halves.
 Time complexity = O(log n).

✅ Binary search is more efficient than linear search for large


datasets.

Pseudocode Example

Linear Search:

Algorithm LinearSearch(A, n, key)

1. For i = 0 to n-1 do

2. If A[i] == key then return i

3. End For

4. Return -1

End Algorithm

Binary Search:

Algorithm BinarySearch(A, low, high, key)

1. If low > high then return -1

2. mid = (low + high) / 2

120
CS25C03 - ESSENTIALS OF COMPUTING REG 25

3. If A[mid] == key then return mid

4. Else if A[mid] > key then return BinarySearch(A, low, mid-1,


key)

5. Else return BinarySearch(A, mid+1, high, key)

End Algorithm

C Implementation

#include <stdio.h>

// Linear Search Function

int linear_search(int arr[], int n, int key) {

for (int i = 0; i < n; i++) {

if (arr[i] == key)

return i; // return index

return -1; // not found

// Binary Search Function

int binary_search(int arr[], int n, int key) {

121
CS25C03 - ESSENTIALS OF COMPUTING REG 25

int low = 0, high = n - 1, mid;

while (low <= high) {

mid = (low + high) / 2;

if (arr[mid] == key)

return mid;

else if (arr[mid] < key)

low = mid + 1;

else

high = mid - 1;

return -1; // not found

int main() {

int arr[] = {10, 20, 30, 40, 50};

int n = sizeof(arr) / sizeof(arr[0]);

int key = 40;

122
CS25C03 - ESSENTIALS OF COMPUTING REG 25

int lin_result = linear_search(arr, n, key);

int bin_result = binary_search(arr, n, key);

if (lin_result != -1)

printf("Linear Search (%d): Found at index %d\n", key,


lin_result);

else

printf("Linear Search (%d): Not Found\n", key);

if (bin_result != -1)

printf("Binary Search (%d): Found at index %d\n", key,


bin_result);

else

printf("Binary Search (%d): Not Found\n", key);

return 0;

Applications

 Time efficiency critical in real-time systems (traffic


control, stock trading).
 Space efficiency critical in embedded systems, mobile
devices.

123
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 Used in selecting sorting/searching techniques


depending on dataset size.

3.7.2 CORRECTNESS OF ALGORITHMS

Definition

An algorithm is correct if it produces the expected output for


every valid input.

Correctness can be classified into:

1. Partial Correctness – If the algorithm terminates, it


gives the correct result.
2. Total Correctness – The algorithm terminates and
always gives the correct result.

Step-by-Step Method to Prove Correctness

1. Understand the problem specification (input, output).


2. Establish invariants – conditions that remain true
during execution.
3. Show base case correctness.
4. Show correctness for each step.
5. Show termination condition.

Illustration / Example

Problem: Checking if an array is sorted.

 Loop Invariant: At the end of each iteration, the first i


elements are in sorted order.

124
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 Termination: At the end of loop, if no violations are


found, the array is sorted.

Pseudocode

Algorithm CheckSorted(A, n)

1. For i = 0 to n-2 do

2. If A[i] > A[i+1] then return False

3. End For

4. Return True

End Algorithm

Program

#include <stdio.h>

#include <stdbool.h>

// Function to check if array is sorted in ascending order

bool is_sorted(int arr[], int n) {

for (int i = 0; i < n - 1; i++) {

if (arr[i] > arr[i + 1])

return false;

125
CS25C03 - ESSENTIALS OF COMPUTING REG 25

return true;

int main() {

int arr1[] = {1, 2, 3, 4, 5};

int arr2[] = {5, 3, 2, 1};

int n1 = sizeof(arr1) / sizeof(arr1[0]);

int n2 = sizeof(arr2) / sizeof(arr2[0]);

if (is_sorted(arr1, n1))

printf("arr1 is sorted: True\n");

else

printf("arr1 is sorted: False\n");

if (is_sorted(arr2, n2))

printf("arr2 is sorted: True\n");

else

126
CS25C03 - ESSENTIALS OF COMPUTING REG 25

printf("arr2 is sorted: False\n");

return 0;

Applications

 Verification of cryptographic algorithms (must always


be correct).
 Compiler correctness – ensuring generated code is
accurate.
 Financial systems – correctness ensures no calculation
errors.

Comparison of Efficiency vs Correctness

Feature Efficiency (Time/Space) Correctness (Accuracy)

Concern Performance Reliability

Measured
Big-O notation Logical proofs, testing
in

Faster code may be Correct code may be


Trade-off
complex slower

Merge Sort vs Bubble


Example Checking sorted arrays
Sort

127
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Notes & Tips

 A correct algorithm is useless if inefficient (too slow for


real-world use).
 An efficient algorithm is dangerous if incorrect (wrong
outputs).
 Always aim for a balance – correctness first, then
optimize efficiency.

3.8 IMPLEMENTATION OF ALGORITHMS

Concept Explanation

Once an algorithm is designed, the next step is to implement it


in a programming language so that it can be executed on a
computer. Implementation translates the logical design
(pseudocode/flowchart) into executable code.

 Algorithm = Logical steps (language-independent).


 Implementation = Actual code in Python, C, Java, etc.

Implementation is a crucial phase because:

1. It determines whether the designed algorithm works in


practice.
2. It exposes hidden flaws in logic.
3. It allows testing efficiency and correctness.

Step-by-Step Method for Implementation

1. Define the Problem Clearly


 Understand input, output, and constraints.

128
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 Example: “Find the sum of first n natural


numbers.”
2. Design the Algorithm
 Write pseudocode or draw a flowchart.
3. Select the Programming Language
 Choose Python for simplicity, C for performance,
Java for portability, etc.
4. Translate Algorithm into Code
 Implement step-by-step logic using syntax.
5. Test with Sample Data
 Try small cases to check correctness.
6. Debug Errors
 Fix syntax, logical, and runtime errors.
7. Optimize the Implementation
 Improve efficiency if needed.

Illustrations / Examples

Example 1: Summation of Numbers

Algorithm (Pseudocode):

Algorithm SumNumbers(n)
1. sum ← 0
2. For i = 1 to n do
3. sum ← sum + i
4. End For
5. Return sum
End Algorithm

Flowchart:

129
CS25C03 - ESSENTIALS OF COMPUTING REG 25

C Implementation:

#include <stdio.h>

// Function to calculate sum of first n numbers


int sum_numbers(int n) {
int total = 0;
for (int i = 1; i <= n; i++) {
total += i;
}
return total;
}

int main() {
int n = 10;
printf("Sum of first %d numbers: %d\n", n, sum_numbers(n));
return 0;
}

130
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Example 2: Factorial of a Number

Algorithm (Pseudocode):

Algorithm Factorial(n)
1. fact ← 1
2. For i = 1 to n do
3. fact ← fact * i
4. End For
5. Return fact
End Algorithm

C Implementation:

#include <stdio.h>

// Function to calculate factorial iteratively

int factorial(int n) {

int fact = 1;

for (int i = 1; i <= n; i++) {

fact *= i;

return fact;

131
CS25C03 - ESSENTIALS OF COMPUTING REG 25

int main() {

int n = 5;

printf("Factorial of %d: %d\n", n, factorial(n));

return 0;

Example 3: Fibonacci Sequence

Algorithm (Pseudocode):

Algorithm Fibonacci(n)
1. a ← 0, b ← 1
2. Print a, b
3. For i = 2 to n do
4. c ← a + b
5. Print c
6. a ← b
7. b ← c
8. End For
End Algorithm

C Implementation:

#include <stdio.h>

void fibonacci(int n) {
int a = 0, b = 1, c;

132
CS25C03 - ESSENTIALS OF COMPUTING REG 25

if (n >= 1) printf("%d ", a);


if (n >= 2) printf("%d ", b);

for (int i = 2; i < n; i++) {


c = a + b;
printf("%d ", c);
a = b;
b = c;
}

printf("\n");
}

int main() {
int n = 10;
fibonacci(n);
return 0;
}

Applications of Algorithm Implementation

 Scientific Computing: Implementing mathematical


models.
 Engineering: Simulations, automation, control systems.
 Data Science: Algorithms for sorting, searching,
machine learning.
 Cybersecurity: Implementing encryption algorithms.
 Daily Applications: Banking transactions, online
shopping, route-finding in maps.

Comparisons, Notes, and Tips

133
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Aspect Algorithm Design Implementation


Nature Theoretical Practical
Pseudocode,
Language Python, Java, C++
flowcharts
Purpose To define logic To execute logic
Errors Syntax + runtime + logical
Logical errors
Found errors
Bubble Sort
Example Python code for Bubble Sort
Algorithm

Tips for Implementation:

1. Start with small test cases.


2. Use print statements for debugging.
3. Write modular code (functions).
4. Compare outputs with manual calculations.
5. Use comments to explain steps.

Case Study: Sorting Student Marks

Problem: Given marks of students, sort them in ascending order.

Algorithm (Pseudocode):

Algorithm SortMarks(M, n)
1. For i = 0 to n-1 do
2. For j = 0 to n-i-1 do
3. If M[j] > M[j+1] then
4. Swap M[j], M[j+1]
5. End For

134
CS25C03 - ESSENTIALS OF COMPUTING REG 25

6. End For
7. Return M
End Algorithm

C Implementation:

#include <stdio.h>

// Function to perform bubble sort

void bubble_sort(int arr[], int n) {

int i, j, temp;

for (i = 0; i < n - 1; i++) {

for (j = 0; j < n - i - 1; j++) {

if (arr[j] > arr[j + 1]) {

// Swap arr[j] and arr[j+1]

temp = arr[j];

arr[j] = arr[j + 1];

arr[j + 1] = temp;

135
CS25C03 - ESSENTIALS OF COMPUTING REG 25

// Function to print array

void print_array(int arr[], int n) {

for (int i = 0; i < n; i++) {

printf("%d ", arr[i]);

printf("\n");

int main() {

int marks[] = {56, 89, 34, 90, 12};

int n = sizeof(marks) / sizeof(marks[0]);

bubble_sort(marks, n);

printf("Sorted Marks: ");

print_array(marks, n);

return 0;

136
CS25C03 - ESSENTIALS OF COMPUTING REG 25

3.9 FUNDAMENTAL ALGORITHMS

3.9.1 EXCHANGING VALUES OF TWO VARIABLES

Concept:
Often in programming, we need to swap the values of two
variables. For example, if A = 5 and B = 10, after swapping, A =
10 and B = 5. This is essential in sorting algorithms, memory
management, and data manipulation.

Methods:

1. Using a temporary variable (safe and standard).


2. Without temporary variable (using arithmetic or
XOR operation).

Pseudocode (with temporary variable):

START

Input A, B

TEMP ← A

A←B

B ← TEMP

Print A, B

137
CS25C03 - ESSENTIALS OF COMPUTING REG 25

STOP

Example:

 Input: A = 5, B = 10
 Output: A = 10, B = 5

Practical Use:

 Bubble sort and other sorting algorithms.


 Data shuffling.

3.9.2 COUNTING

Concept:
Counting is the process of iterating through a sequence of
numbers in order. It forms the basis of iteration and loop
constructs. For example, printing numbers 1 to 10.

Logic:

 Start with a counter variable.


 Repeat until a condition is met.
 Increment the counter.

Pseudocode:

START

Input N

SET i = 1

138
CS25C03 - ESSENTIALS OF COMPUTING REG 25

WHILE i ≤ N

Print i

i←i+1

END WHILE

STOP

Example:

 Input: N = 5
 Output: 1 2 3 4 5

Practical Use:

 Looping through datasets.


 Array traversal.
 Generating sequence numbers.

3.9.3 SUMMATION OF A SET OF NUMBERS

Concept:
Summation refers to adding a sequence of numbers. For
example, calculating the total marks of students or total sales in
a shop.

Logic:

 Initialize sum = 0.
 Add each number to sum.

139
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 Print final result.

Pseudocode:

START

Input N

SET sum = 0

FOR i = 1 to N

Input number

sum = sum + number

END FOR

Print sum

STOP

Example:

 Input: N = 5, numbers = 2, 4, 6, 8, 10
 Output: Sum = 30

Practical Use:

 Statistical calculations.
 Budgeting and accounting.
 Data aggregation in machine learning.

140
CS25C03 - ESSENTIALS OF COMPUTING REG 25

3.9.4 FACTORIAL COMPUTATION

Concept:
Factorial of a number n is the product of all positive integers up
to n.

 Formula: n! = n × (n-1) × (n-2) … × 1


 Example: 5! = 5 × 4 × 3 × 2 × 1 = 120

Methods:

1. Iterative method (loop).


2. Recursive method (function calls itself).

Pseudocode (Iterative):

START

Input n

SET fact = 1

FOR i = 1 to n

fact = fact * i

END FOR

Print fact

STOP

Pseudocode (Recursive):

141
CS25C03 - ESSENTIALS OF COMPUTING REG 25

FUNCTION Factorial(n)

IF n == 0 OR n == 1 THEN

RETURN 1

ELSE

RETURN n * Factorial(n-1)

END FUNCTION

Practical Use:

 Permutations and combinations.


 Probability and statistics.
 Algorithms in mathematics and computer science.

3.9.5 GENERATION OF FIBONACCI SEQUENCE

Concept:
The Fibonacci sequence is a series where each number is the
sum of the two preceding ones.

 Formula: Fn = Fn-1 + Fn-2


 Example: 0, 1, 1, 2, 3, 5, 8, 13…

Logic:

 Start with two numbers (0 and 1).


 Keep adding them to generate the next number.

142
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Pseudocode:

START

Input N

SET a = 0, b = 1

Print a, b

FOR i = 3 to N

c=a+b

Print c

a=b

b=c

END FOR

STOP

Practical Use:

 Recursive programming.
 Growth models in nature (like rabbit population).
 Used in computer algorithms (e.g., Fibonacci search).

143
CS25C03 - ESSENTIALS OF COMPUTING REG 25

3.9.6 REVERSING THE DIGITS OF AN INTEGER

Concept:
Reversing digits means rearranging the digits of a number in
reverse order.

 Example: Input 1234 → Output 4321.

Logic:

 Extract the last digit using modulus %.


 Add it to the reversed number.
 Remove last digit by dividing by 10.
 Repeat until number becomes 0.

Pseudocode:

START

Input num

SET rev = 0

WHILE num > 0

digit = num % 10

rev = rev * 10 + digit

num = num / 10

END WHILE

144
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Print rev

STOP

Practical Use:

 Checking for palindrome numbers.


 Data encryption and manipulation.
 Digital signal processing.

3.9.7 BASE CONVERSION

Concept:
Base conversion means changing numbers from one number
system to another.

 Decimal (Base 10) → Binary (Base 2), Octal (Base 8),


Hexadecimal (Base 16).
 Example: Decimal 10 → Binary 1010 → Octal 12 →
Hexadecimal A.

Logic (Decimal to Binary):

 Divide number by 2.
 Record remainder.
 Repeat until quotient = 0.
 Read remainders in reverse order.

Pseudocode:

START

145
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Input decimal_number

SET binary = ""

WHILE decimal_number > 0

remainder = decimal_number % 2

binary = remainder + binary

decimal_number = decimal_number / 2

END WHILE

Print binary

STOP

Practical Use:

 Computer systems use binary, octal, hexadecimal


representations.
 Low-level programming and networking.
 Cryptography and data encoding.

3.10 IMPORTANT TWO MARKS

1) Define an algorithm.
An algorithm is a step-by-step procedure or set of rules for
solving a problem in a finite number of steps.
2) What is problem decomposition?
Problem decomposition is dividing a complex problem into
smaller sub-problems that are easier to solve.

146
CS25C03 - ESSENTIALS OF COMPUTING REG 25

3) What is logical reasoning?


Logical reasoning is the process of applying structured
thinking to derive conclusions or solutions.
4) List two characteristics of a good algorithm.

 Finiteness (must terminate after a finite number of steps).


 Definiteness (each step must be clear and unambiguous).

5) Differentiate between iterative and recursive structures.

 Iterative structure uses loops (for, while).


 Recursive structure involves a function calling itself.

6) Define correctness of an algorithm.


An algorithm is correct if it produces the expected output
for all valid inputs.
7) What is efficiency of an algorithm?
Efficiency refers to how effectively an algorithm uses
resources such as time and memory.
8) Write the steps to exchange two variables?

temp = a

a=b

b = temp

9) What are the first two numbers of the Fibonacci


sequence?
The first two numbers are 0 and 1.

147
CS25C03 - ESSENTIALS OF COMPUTING REG 25

UNIT IV PROGRAMMING LANGUAGES

SYLLABUS

Program Development Life Cycle, Program Design Tools,


Algorithms, Flowcharts, Pseudocodes, Role of Algorithms,
Programming Languages, Programming Paradigms Traditional
Programming Concepts, Procedural Units, Language
Implementation, Declarative Programming.

PROGRAMMING LANGUAGES

A programming language is a set of instructions and syntax


used to create software programs. Some of the key features of
programming languages include:

148
CS25C03 - ESSENTIALS OF COMPUTING REG 25

1. Syntax: The specific rules and structure used to write code


in a programming language.
2. Data Types: The type of values that can be stored in a
program, such as numbers, strings, and booleans.
3. Variables: Named memory locations that can store values.
4. Operators: Symbols used to perform operations on values,
such as addition, subtraction, and comparison.
5. Control Structures: Statements used to control the flow of
a program, such as if-else statements, loops, and function
calls.
6. Libraries and Frameworks: Collections of pre-written code
that can be used to perform common tasks and speed up
development.
7. Paradigms: The programming style or philosophy used in
the language, such as procedural, object-oriented, or
functional.

Examples of popular programming languages include Python,


Java, C++, JavaScript, and Ruby. Each language has its own
strengths and weaknesses and is suited for different types of
projects.
A programming language is a formal language that specifies a
set of instructions for a computer to perform specific tasks. It's
used to write software programs and applications, and to
control and manipulate computer systems. There are many
different programming languages, each with its own syntax,
structure, and set of commands. Some of the most commonly
used programming languages include Java, Python, C++,
JavaScript, and C#. The choice of programming language
depends on the specific requirements of a project, including the
platform being used, the intended audience, and the desired
outcome. Programming languages continue to evolve and

149
CS25C03 - ESSENTIALS OF COMPUTING REG 25

change over time, with new languages being developed and


older ones being updated to meet changing needs.
4.1 PROGRAM DEVELOPMENT LIFE CYCLE

When we want to develop a program using any programming


language, we follow a sequence of steps. These steps are called
phases in program development. The program development life
cycle is a set of steps or phases that are used to develop a
program in any programming language. Generally, the program
development life

150
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Cycle Contains 6 Phases, They Are As Follows:

 Problem Definition

 Problem Analysis

 Algorithm Development

 Coding & Documentation

 Testing & Debugging

 Maintenance

1. Problem Definition
In this phase, we define the problem statement and we decide
the boundaries of the problem. In this phase we need to
understand the problem statement, what is our requirement,
what should be the output of the problem solution. These are
defined in this first phase of the program development life cycle.

2. Problem Analysis
In phase 2, we determine the requirements like variables,
functions, etc. to solve the problem. That means we gather the
required resources to solve the problem defined in the problem
definition phase. We also determine the bounds of the solution.

3. Algorithm Development
During this phase, we develop a step by step procedure to solve

151
CS25C03 - ESSENTIALS OF COMPUTING REG 25

the problem using the specification given in the previous phase.


This phase is very important for program development. That
means we write the solution in step by step statements.

4. Coding & Documentation


This phase uses a programming language to write or implement
the actual programming instructions for the steps defined in the
previous phase. In this phase, we construct the actual program.
That means we write the program to solve the given problem
using programming languages like C, C++, Java, etc.

5. Testing & Debugging


During this phase, we check whether the code written in the
previous step is solving the specified problem or not. That
means we test the program whether it is solving the problem for
various input data values or not.
We also test whether it is providing the desired output or not.

6. Maintenance
During this phase, the program is actively used by the users. If
any enhancements found in this phase, all the phases are to be
repeated to make the enhancements. That means in this phase,
the solution (program) is used by the end-user. If the user
encounters any problem or wants any enhancement, then we
need to repeat all the phases from the starting, so that the
encountered problem is solved or enhancement is added.

152
CS25C03 - ESSENTIALS OF COMPUTING REG 25

4.2 PROGRAM DESIGN TOOLS

Program design tools are essential for planning, organizing,


and visualizing the steps needed to solve a problem using a
computer program. These tools ensure that the logic is
correct before actual coding begins, thereby reducing errors
and making programming more structured and efficient.

4.2.1. ALGORITHM

Definition of Algorithm

An algorithm is a finite set of instructions for performing a


particular task. The instructions are nothing but the statements in
simple English language.

In computing, we focus on the type of problems categorically


known as algorithmic problems, where their solutions are
expressible in the form of algorithms. The term “algorithm” was
derived from the name of Mohammed al-Khowarizmi, a Persian
mathematician in the ninth century.

Al-Khowarizmi → Algorismus (in Latin) → Algorithm.

An algorithm is a well-defined computational procedure


consisting of a set of instructions that takes some value or set
of values, as input, and produces some value or set of values,
as output.

153
CS25C03 - ESSENTIALS OF COMPUTING REG 25

In other word, an algorithm is a procedure that accepts data;


manipulate them following the prescribed steps, so as to
eventually fill the required unknown with the desired value(s).

INPUT ALGORITHM OUTPUT

People in various professions follow specific procedures in their


work, each referred to by a different name. For example, a cook
uses a method known as a recipe, which transforms ingredients
(input) into a finished dish (output) through a series of steps.

Characteristics of a good algorithm

1.Precision – Every step in the algorithm must be clearly and


accurately defined.
2.Uniqueness – Each step should yield a unique result,
depending solely on the given input and the result of
previous steps.
3.Finiteness – The algorithm must terminate after a limited
number of steps.
4.Effectiveness – Among all possible approaches, the
algorithm should provide the most efficient solution to
the problem.
5.Input – It should accept one or more inputs to begin the
process.
6.Output – It must generate at least one output as the result.

154
CS25C03 - ESSENTIALS OF COMPUTING REG 25

7.Generality – The algorithm should be applicable to a wide


range of input values, not just specific cases.

Example 4.1: Algorithm to Check if a Number is Even or


Odd
Algorithm Steps:

Step 1 : Start
Step 2 : Take a number as input
Step 3 : If the number is divisible by 2, it is even
Step 4 : Else, it is odd
Step 5 : Display the result
Step 6 : Stop

Example 4.2: Algorithm to Find the Largest of Two


Numbers
Algorithm Steps:

Step 1 : Start
Step 2 : Get two numbers as input
Step 3 : Compare the two numbers
Step 4 : If the first number is greater, it is the largest
Step 5 : Else, the second number is the largest
Step 6 : Display the result
Step 7 : Stop

FLOW CHART AND PSEUDOCODE

155
CS25C03 - ESSENTIALS OF COMPUTING REG 25

4.2.2 FLOW CHARTS

 Flowcharts are the graphical representation of the


algorithms.
 The algorithms and flowcharts are the final steps in
organizing the solutions.

 Using the algorithms and flowcharts the programmers


can find out the bugs in the programming logic and then
can go for coding.
 Flowcharts can show errors in the logic and set of data
can be easily tested using flowcharts

Flow chart symbols

S. Name of Symbol Type Description


No symbol

1. Terminal Oval Represent the start


Symbol and stop of the
program.

2. Input/ Parallelogram Denotes either input


Output or output operation.
symbol

156
CS25C03 - ESSENTIALS OF COMPUTING REG 25

3. Process Rectangle Denotes the process


symbol to be carried

4. Decision Diamond Represents decision


symbol Making and
branching

5. Flow lines Arrow lines Represents the


sequence of steps
and direction of
flow. Used to
connect symbols.

6. Connector Circle A connector symbol


is represented by a
circle and a letter or
digit is placed in the
circle to specify the
link. This symbol is
used to Connect
flow charts.

157
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Rules for drawing flow chart

1. In drawing a proper flowchart, all necessary


requirements should be listed out in logical order.
2. The flow chart should be clear, neat and easy to
follow. There should not be any room for ambiguity
in understanding the flowchart.

3. The usual directions of the flow of a procedure or


system are from left to right or top to bottom. Only
one flow line should come out from a process symbol.

4. Only one flow line should enter a decision symbol,


but two or three flow lines, one for each possible
answer, cap leave the decision symbol.

158
CS25C03 - ESSENTIALS OF COMPUTING REG 25

5. Only one flow line is used in conjunction with


terminal symbol.

6. If flow chart becomes complex, it is better to use


connect or symbols to reduce the number of flow
lines.
7. Ensure that flow chart has logical start and stop.

Advantages of flow chart

1. Communication: Flow charts are better way of


communicating the logic of the system.
2. Effective Analysis: With the help of flow chart, a problem
can be analyzed in more effective way.
3. Proper Documentation: Flow charts are used for good
program documentation, which is needed for various
purposes.
4. Efficient Coding: The flowcharts act as a guide or blue
print during the system analysis and program development
phase.
5. Systematic Testing and Debugging: The flow chart helps
in testing and debugging the program
6. Efficient Program Maintenance: The maintenance of
operating program becomes easy with the help of flowchart.

159
CS25C03 - ESSENTIALS OF COMPUTING REG 25

It helps the programmer to put efforts more efficiently on


that part.

Disadvantages of flowchart

1. Complex Logic: Sometimes, the program logic is quite


complicated. In that case flow chart becomes complex and
difficult to use.

2. Alteration and Modification: If alterations are required the


flowchart may require re- drawing completely.

3. Reproduction: As the flowchart symbols cannot be typed,


reproduction becomes problematic.

4.2.3 PSEUDO CODE

Pseudocode is an informal high-level description of the


operating principle of a computer program or algorithm. It uses
the basic structure of a normal programming language, but is
intended for human reading rather than machine reading. It is
text based detail design tool. Pseudo means false and code refers
to instructions written in programming language.

Pseudocode cannot be compiled nor executed, and there are no


real formatting or syntax rules. The pseudocode is written in
normal English language which cannot be understood by the
computer.

160
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Example 4.2.1 : Pseudocode: To find sum of two numbers

READ num1, num2

Sum = num1+num2

PRINT sum

Basic rules to write pseudocode:

1. Only one statement per line. Statements represents single


action is written on same line. For example to read the
input, all the inputs must be read using single statement.
2. Capitalized initial keywords The keywords should be
written in capital letters. Eg: READ, WRITE, IF, ELSE,
ENDIF, WHILE, REPEAT, UNTIL

Example 4.2.2 : Pseudocode: Find the total and average of


three subjects

READ name, department, mark1, mark2, mark3

Total=mark1+mark2+mark3

Average=Total/3

WRITE name, department, mark1, mark2, mark3

1. Indent to show hierarchy Indentation is a process of


showing the boundaries of the structure.
2. End multi-line structures each structure must be ended
properly, which provides more clarity.

161
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Example 4.2..3 : Pseudocode: Find greatest of two


numbers

READ a, b

IF a>b then

PRINT a is greater

ELSE

PRINT b is greater

END IF

Advantages of Pseudocode

 Can be done easily on a word processor


 Easily modified
 Implements structured concepts well
 It can be written easily
 It can be read and understood easily
 Converting pseudocode to programming language is
easy as compared with flowchart

Disadvantages of Pseudocode

 It is not visual
 There is no standardized style or format

162
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Differences between algorithm and flowchart

The Differences between algorithm and flowchart are:

Algorithm Flowchart

1. Algorithm is the well- 1. Flowchart is a graphical


defined steps for performing representation of the logical
a task or solving a problem. sequence of steps involved in
programming.

2. Algorithm is written in 2. Flowchart is shown in the figure.


different steps.

3. Algorithm is more 3. Flowchart is easier to understand


difficult to understand than than the algorithm.
the flowchart.

4.3 ROLE OF ALGORITHMS IN PROGRAMMING

1. Problem Solving

What it means:
Algorithms break down a complex or difficult problem into
smaller, simpler steps that are easier to understand and execute.

163
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Why it’s important:

 Complex problems can be overwhelming if tackled all at


once.

164
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 Dividing the problem into smaller parts helps in


identifying what needs to be done first, next, and last.

 Structured thinking prevents overlooking important steps


and ensures that each part is addressed.

Example:
Consider a problem like sorting a list of thousands of student
names alphabetically. Instead of trying to sort the whole list in
one go, the algorithm breaks it down:

1. Compare two names at a time.

2. Decide which one should come first.

3. Repeat this process until the entire list is sorted.

Real-life analogy:
Imagine baking a cake. Instead of trying to bake it in one step,
you:

 Measure ingredients.

 Mix them properly.

 Preheat the oven.

 Bake at the correct temperature.


Each of these steps is like a part of the algorithm.

165
CS25C03 - ESSENTIALS OF COMPUTING REG 25

2. Efficiency

What it means:
Efficiency refers to how well an algorithm uses system
resources like processing time and memory. An efficient
algorithm solves the problem faster and consumes less energy
and memory.

Why it’s important:

 Programs that use too much time or memory can slow


down or crash.

 Efficient algorithms make better use of computing


resources.

 Optimizing algorithms helps in improving the overall


performance of applications.

Example:

 A search algorithm can either check every item one by


one (slow) or use a more efficient method like binary
search to quickly find the required element.

Real-life analogy:
If you want to find a word in a dictionary, flipping pages one by
one is slow. But if you know the alphabetical order, you can
jump to the section directly, saving time.

166
CS25C03 - ESSENTIALS OF COMPUTING REG 25

3. Reusability

What it means:
Once an algorithm is created and tested, it can be used multiple
times in different programs without needing to be rewritten.

Why it’s important:

 Saves time in development.

 Ensures consistency in solving similar problems.

 Helps in building libraries or modules that can be reused


across applications.

Example:
A sorting algorithm like “merge sort” can be used in:

 Sorting user names.

 Sorting product prices.

 Sorting customer orders.

All of these problems require sorting, so the same algorithm can


be reused.

Real-life analogy:
A recipe for making pasta can be reused anytime you want to
cook pasta, whether it’s for lunch, dinner, or a party.

167
CS25C03 - ESSENTIALS OF COMPUTING REG 25

4. Debugging and Testing

What it means:
Algorithms make it easier to trace the logic of a program,
identify where errors occur, and correct them.

Why it’s important:

 A clear, step-by-step algorithm helps programmers


pinpoint mistakes quickly.

 Structured logic allows testing at each step, ensuring that


all parts of the program work as expected.

 It makes it easier to handle unexpected inputs or


conditions (edge cases).

Example:
If you have an algorithm to calculate the total price of items,
testing it by using different quantities and prices helps ensure it
works in every scenario.

Real-life analogy:
Following step-by-step instructions to assemble furniture helps
you figure out exactly where things went wrong if something
doesn't fit properly.

168
CS25C03 - ESSENTIALS OF COMPUTING REG 25

5. Scalability

What it means:
Scalability refers to an algorithm’s ability to handle more data or
complex problems without needing major changes in its
structure.

Why it’s important:

 Programs should not fail when the amount of data grows.

 Scalable algorithms are future-proof and adaptable.

 They allow programmers to extend the program’s


functionality without redesigning it from scratch.

Example:
A search algorithm that works for 100 items should still work
efficiently if the list increases to 10,000 items, provided it's
designed to scale.

Real-life analogy:
A city’s road system that can handle more traffic with simple
expansions is scalable, while a poorly designed road that clogs
when more vehicles are added is not.

169
CS25C03 - ESSENTIALS OF COMPUTING REG 25

6. Improved Communication

What it means:
Algorithms help programmers clearly describe their problem-
solving process, making it easier for teams to collaborate and
share ideas.

Why it’s important:

 Complex logic can be explained in simple steps.

 Everyone involved can understand how the program


works, even if they speak different programming
languages.

 It reduces misunderstandings and improves teamwork.

Example:
A team working on a banking application can discuss the
transaction algorithm by explaining the steps, like verifying the
account, checking the balance, and processing the payment.

Real-life analogy:
When planning a trip, creating a checklist of tasks (book flight,
reserve hotel, pack luggage) helps everyone coordinate easily.

170
CS25C03 - ESSENTIALS OF COMPUTING REG 25

4.4 PROGRAMMING LANGUAGES

1.Syntax and Semantics

 Syntax: The set of rules that defines how statements should


be written.

 Semantics: The meaning behind each statement or


instruction.

 For example, in Python, writing print("Hello") follows


correct syntax, whereas missing parentheses would cause an
error.

171
CS25C03 - ESSENTIALS OF COMPUTING REG 25

2.Abstraction

 Programming languages allow programmers to work at


different levels of complexity.

 They provide built-in functions, libraries, and modules to


perform common tasks without needing to write detailed
instructions from scratch.

3.Control Structures

 Programming languages include mechanisms like loops,


conditionals, and functions to control the flow of execution.

 These structures make it possible to handle different


situations dynamically.

4.Data Types and Variables

 Variables store information like numbers, text, and more


complex data structures.

 Data types define the kind of data a variable can hold, such
as integers, strings, or lists.

5.Portability

 Some languages allow programs to run on different


hardware or operating systems without major modifications.

 This ensures software can be used by a wider audience.

172
CS25C03 - ESSENTIALS OF COMPUTING REG 25

4.4.1 TYPES OF PROGRAMMING LANGUAGES

1. Low-Level Languages
These are closer to the machine’s hardware.

Examples:
Machine Language: Binary code executed directly by the
computer’s processor.
Assembly Language: Uses symbolic representations of
machine instructions.

2. High-Level Languages
Easier for humans to understand and write.
Abstract away the complexities of hardware.

Examples:
Python, Java, C++, JavaScript

173
CS25C03 - ESSENTIALS OF COMPUTING REG 25

3. Procedural Programming Languages


Focus on step-by-step procedures and functions.
Example: C, Pascal

4. Object-Oriented Programming Languages


Organize code into “objects” that contain both data and
methods.
Example: Java, C++, Python

5. Functional Programming Languages


Focus on mathematical functions and immutability.
Example: Haskell, Lisp

4.4.2.IMPORTANCE OF PROGRAMMING LANGUAGES

1. Automation
Programming languages enable the automation of repetitive
tasks, saving time and effort.

174
CS25C03 - ESSENTIALS OF COMPUTING REG 25

2. Problem Solving
They help break down complex problems into manageable
pieces and write efficient solutions.

3. Innovation
Programming languages power technologies like artificial
intelligence, data analytics, and the internet.

4. Global Communication
Programmers from around the world can work together
using standardized languages and conventions.

5. Career Opportunities
Knowledge of programming languages opens doors to
careers in software development, cybersecurity, game
development, and more.

4.5 PROGRAMMING PARADIGMS

A paradigm can be understood as a way or method to solve a


problem or accomplish a task. A programming paradigm is
essentially an approach to problem-solving using a specific
programming language and its features. It is a methodology that

175
CS25C03 - ESSENTIALS OF COMPUTING REG 25

guides how problems are broken down and how solutions are
implemented using the available tools and techniques.

Although there are numerous programming languages, each


language generally supports one or more paradigms that define
its style of coding. These paradigms provide structure, clarity,
and reusability in software development.

Programming paradigms are broadly divided into:

1. Imperative Paradigm
2. Declarative Paradigm

Each of these has further classifications, advantages,


disadvantages, and use cases.

4.5.1. IMPERATIVE PROGRAMMING PARADIGM

The imperative paradigm is one of the oldest approaches in


programming. It is closely related to machine architecture and is
based on the Von Neumann architecture. This paradigm works
by changing the program state through assignment
statements.

The focus here is on how to achieve the desired result by


executing a series of step-by-step instructions.

Advantage

 Simple to implement and understand


 Provides constructs like loops, variables, and conditionals
 Efficient for small-scale problems

176
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Disadvantages

 Complex problems are hard to manage


 Less productive for large-scale applications
 Limited parallelism support

Example

 C (Dennis Ritchie, Ken Thompson)


 Fortran (John Backus for IBM)
 BASIC (John G. Kemeny, Thomas E. Kurtz)

Example Code (C – Average of Numbers)

#include <stdio.h>int main() {

int marks[5] = { 12, 32, 45, 13, 19 };

int sum = 0;

float average = 0.0;

for (int i = 0; i < 5; i++) {

sum = sum + marks[i];

average = (float)sum / 5.0;

177
CS25C03 - ESSENTIALS OF COMPUTING REG 25

printf("Average of five numbers: %.2f\n", average);

return 0;

Output:

Average of five numbers: 24.2

a. Procedural programming paradigm

Procedural programming is a subset of imperative programming.


It emphasizes breaking the problem into procedures
(functions/methods).

Advantages

 Supports modularization and reusability


 Easy debugging and maintenance
 Good for structured programming

Disadvantages

 Not well-suited for real-world modeling


 Less secure (data not hidden properly)
 Large programs become hard to manage

Examples

 C (Dennis Ritchie, Ken Thompson)


 C++ (Bjarne Stroustrup)

178
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 Java (James Gosling)


 Pascal (Niklaus Wirth)

b. Object-Oriented Programming (OOP) Paradigm

OOP organizes code into classes and objects. Computations are


performed on objects, making it closer to real-world modeling.

Advantages

 Encapsulation ensures data security


 Supports inheritance and polymorphism
 Promotes code reusability
 Better abstraction and flexibility

Disadvantages

 More complex compared to procedural approach


 Slower execution due to abstraction layers
 Requires careful design before implementation

Examples

 Simula (First OOP language)


 Java (James Gosling)
 C++ (Bjarne Stroustrup)
 Python (Guido van Rossum)
 Ruby (Yukihiro Matsumoto)

c. Parallel processing paradigm

179
CS25C03 - ESSENTIALS OF COMPUTING REG 25

This paradigm divides tasks into sub-tasks executed


simultaneously across multiple processors. It follows the divide
and conquer approach.

Advantages

 Faster execution by utilizing multiple processors


 Efficient for large-scale computations
 Supports real-time systems

Disadvantages

 Difficult to design and debug


 Requires specialized hardware/software
 Not suitable for all problems

Examples

 NESL
 C/C++ with parallel libraries (e.g., OpenMP, MPI)

4.5.2. DECLARATIVE PROGRAMMING PARADIGM

Declarative programming focuses on what needs to be done


rather than how it should be done. Unlike imperative
programming, it hides control flow and directly expresses logic.

Advantages

 Simplifies programming by abstracting control flow


 Easier to write parallel and distributed programs
 Improves readability and maintainability

180
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Disadvantages

 Less control over execution flow


 Sometimes less efficient than imperative approaches
 Harder to debug for beginners

Declarative paradigm has three major categories:

A. Logic Programming Paradigm

Logic programming uses a knowledge base and inference rules


to solve problems, often resembling mathematical proofs.

Advantages

 Effective for symbolic reasoning and AI applications


 Provides a high level of abstraction
 Suitable for rule-based problem solving

Disadvantages

 Not efficient for general-purpose computing


 Requires large knowledge bases
 Limited performance in real-time application

Example Language

 Prolog

B. Functional Programming Paradigm

181
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Functional programming is rooted in mathematics. Programs are


written as a collection of functions without mutable state.

Advantages

 Easy debugging due to stateless design


 Encourages modular, reusable code
 Suitable for concurrent/parallel systems

Disadvantages

 Steeper learning curve for beginners


 Sometimes slower due to immutability overhead
 Less intuitive for problems requiring state management

Examples

 Haskell
 Lisp
 Scala
 Erlang
 Clojure

C. Database/Data-Driven Paradigm

Here, programs are defined based on data and its movement,


often interacting with databases.

Advantages

 Optimized for managing and querying large datasets


 Simplifies CRUD operations (Create, Read, Update, Delete)

182
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 Essential in business and enterprise applications

Disadvantages

 Limited scope outside data-driven systems


 Performance depends on database engine
 Requires strong schema design

Example Language

SQL

CREATE DATABASE databaseAddress;CREATE TABLE


Addr (

PersonID int,

LastName varchar(200),

FirstName varchar(200),

Address varchar(200),

City varchar(200),

State varchar(200)

);

183
CS25C03 - ESSENTIALS OF COMPUTING REG 25

4.6 TRADITIONAL PROGRAMMING CONCEPTS


Traditional programming concepts form the foundation of
computer programming. They provide the logical and
structural principles required to design, develop, and execute
programs effectively. Every programming language, whether
procedural, object-oriented, or modern high-level, is built upon
these basic concepts. Understanding them is essential for
beginners and advanced learners alike, as they enable the
creation of structured, efficient, and error-free programs.

The key traditional programming concepts include:

4.6.1 Sequence

The sequence refers to the step-by-step execution of


instructions in the order they are written. It is the simplest form
of program control, ensuring that each statement runs one after
another.

Importance: Maintains logical flow and order of operations.

Example:

int a = 5;

184
CS25C03 - ESSENTIALS OF COMPUTING REG 25

int b = 10;

int sum = a + b;

printf("Sum = %d", sum);

Here, the program first assigns values, then calculates, and


finally displays the result.

4.6.2 Selection (Decision Making)

Selection allows the program to choose different paths based


on conditions. It enables flexibility by executing different sets of
instructions depending on the situation.

Importance: Helps the program respond to varying inputs.

Example:

if (marks >= 50) {

printf("Pass");

} else {

printf("Fail");

4.6.3 Iteration (Looping)

185
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Iteration means repeating a block of instructions until a


condition is satisfied. It prevents code duplication and makes
programs concise.

Importance: Useful for repetitive tasks like printing numbers,


processing lists, etc.

Example:

for (int i = 1; i <= 5; i++) {

printf("Iteration %d\n", i);

4.6.4 Variables

Variables are named storage locations used to hold data that


can change during program execution. They make programs
dynamic and interactive.

Importance: Store user inputs, intermediate results, and outputs.

Example:

int age;

scanf("%d", &age);

186
CS25C03 - ESSENTIALS OF COMPUTING REG 25

printf("You are %d years old", age);

4.6.5 Constants

Constants are fixed values that remain unchanged throughout


the execution of a program. They improve readability and
reduce errors caused by repeated values.

Importance: Define permanent values like π, interest rates, or


conversion factors.

Example:

#define PI 3.14

float area = PI * radius * radius;

4.6.6 Functions/Procedures

Functions (or procedures) are reusable blocks of code designed


to perform specific tasks. They divide complex programs into
smaller, manageable parts.

Importance:

 Promote modularity and reusability.


 Simplify debugging and maintenance.
 Encourage logical program structure

Example:

187
CS25C03 - ESSENTIALS OF COMPUTING REG 25

int add(int x, int y

return x + y;

4.6.7 Importance of Traditional Programming Concepts

 Foundation for Advanced Programming: They serve as


the building blocks for structured, object-oriented, and
modern programming paradigms.
 Efficient Code Design: Concepts like sequence, selection,
and iteration ensure structured and logical programs.
 Reusability: Functions and procedures reduce redundancy
and promote modularity.
 Error Reduction: Use of variables, constants, and loops
makes programs easier to debug and maintain.
 Adaptability: Decision-making structures allow programs
to handle real-world scenarios dynamically.

4.6.8 Real-Life Analogies

 Sequence: Following steps in a recipe.


 Selection: Choosing between two roads depending on
traffic.
 Iteration: Practicing a song until memorized.
 Variables: Containers holding ingredients while cooking.
 Constants: Oven temperature required for baking.
 Functions: A mixer used repeatedly for different dishes.

188
CS25C03 - ESSENTIALS OF COMPUTING REG 25

4.7 PROCEDURAL UNITS

What are Procedural Units?

Procedural units are blocks of code that perform specific tasks


within a program. They are also known as functions, subroutines,
or procedures, depending on the programming language.
Procedural units help in dividing a program into smaller,
manageable parts, making the development process structured
and easier to maintain.

These units are an essential part of structured or procedural


programming and form the building blocks for writing reusable,
organized, and efficient code.

4.7.1 Key Characteristics of Procedural Units

1. Modularity

189
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 Procedural units break a program into separate parts.

 Each unit is responsible for a specific task, making it easier


to understand and manage.

2. Reusability

 Once written, a procedural unit can be used multiple times


in the program without rewriting the code.

3. Abstraction

 Complex tasks can be hidden inside a procedural unit,


allowing programmers to use it without knowing its internal
details.

4. Parameter Passing

 Data can be sent into the procedural unit and results can be
sent back to the calling program.

5. Return Values

 Many procedural units return a value after execution, which


can be used in further computations.

6. Improved Debugging

 Errors can be identified and corrected within a small part of


the program, rather than searching the entire codebase.

190
CS25C03 - ESSENTIALS OF COMPUTING REG 25

4.7.2 Structure of Procedural Units

A typical procedural unit consists of the following:

1. Header
Defines the name, parameters, and sometimes the return
type of the unit.

2. Body
Contains the actual statements and computations to be
executed.

3. Return Statement (Optional)


Sends the result back to the calling program.

4.7.3 Types of Procedural Units

1. Functions
A block that performs a task and returns a value.

Example in C:

int add(int a, int b) {

return a + b;

2. Procedures (Subroutines)
Performs a task but does not necessarily return a value.

Example in Pascal:

191
CS25C03 - ESSENTIALS OF COMPUTING REG 25

procedure DisplayMessage;

begin

writeln('Hello, World!');

end;

3. Methods (in Object-Oriented languages)


Similar to functions but associated with objects and
classes.

Example of Procedural Units

Problem: Write a program to calculate the area of a circle using


procedural units.

Code Example in C:

#include <stdio.h>

#define PI 3.14

// Function to calculate area

float calculateArea(float radius) {

return PI * radius * radius;

192
CS25C03 - ESSENTIALS OF COMPUTING REG 25

int main() {

float radius, area;

printf("Enter the radius of the circle: ");

scanf("%f", &radius);

area = calculateArea(radius);

printf("Area = %.2f\n", area);

return 0;

Explanation:

 calculateArea() is a procedural unit that performs the task of


calculating the area.

 The main() function calls this unit and passes the radius as
input.

 The result is returned and printed.

4.7.4 Advantages of Procedural Units

1. Simplifies Complex Programs


By dividing programs into smaller units, complex tasks
become easier to solve.

193
CS25C03 - ESSENTIALS OF COMPUTING REG 25

2. Enhances Code Reusability


Once written, functions or procedures can be reused
wherever needed.

3. Improves Maintainability
If a bug occurs, it can be traced and corrected within the
procedural unit without affecting the entire program.

4. Facilitates Teamwork
Different teams can work on separate procedural units
and integrate them into a complete program.

5. Promotes Readability
Programs with procedural units are easier to read,
understand, and document.

4.7.5 Real-Life Analogy

Think of procedural units like departments in a company:

 The HR department handles hiring.

 The finance department handles payroll.

 The IT department handles technical support.

Each department is responsible for specific tasks but works


together to achieve the overall goals of the company. Similarly,
procedural units divide the program into tasks and work together
to solve problems.

4.8 LANGUAGE IMPLEMENTATION

194
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Language implementation refers to the process of converting


code written in a programming language into a form that a
computer can execute. A programming language provides the
rules and syntax for writing programs, but these instructions
must be translated into machine-readable commands so that the
computer’s processor can understand and perform the tasks.

The implementation of a language involves several steps,


including translation, optimization, and execution. It is a crucial
part of software development and determines how efficiently
and effectively a program runs on hardware.

4.8.1 Key Steps in Language Implementation

1. Writing the Source Code

Definition:
The programmer writes instructions using the programming

195
CS25C03 - ESSENTIALS OF COMPUTING REG 25

language’s syntax and semantics. This source code is human-


readable but cannot be directly executed by a computer.

Example:

print("Hello, World!")

The above Python code instructs the computer to display the


text “Hello, World!”.

2. Lexical Analysis (Scanning)

Definition:
This is the process of breaking down the source code into
smaller elements called tokens, such as keywords, identifiers,
literals, and operators.

Why it’s important:

 Helps in identifying the structure of the code.

 Removes unnecessary whitespace and comments.

Example:
The code print("Hello") is broken down into tokens:

print → keyword

( → symbol

"Hello" → string literal

) → symbol

196
CS25C03 - ESSENTIALS OF COMPUTING REG 25

3. Syntax Analysis (Parsing)

Definition:
During parsing, the tokens are grouped into a hierarchical
structure called the parse tree or syntax tree, which represents
the grammatical structure of the code according to the
language’s rules.

Why it’s important:

 Ensures the code follows correct grammar.

 Helps in identifying errors like missing parentheses or


incorrect command structures.

Example:
For the statement if (x > 0) { y = 2; }, the parser identifies:

Condition: x > 0

Statement block: y = 2

4. Semantic Analysis

Definition:
This step checks whether the meaning of the program is correct,
such as verifying data types, ensuring variables are declared
before use, and confirming function calls are valid.

197
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Why it’s important:

 Detects logical errors.

 Ensures proper usage of functions and variables.

Example:
If you try to add a number to a string, semantic analysis will
throw an error because it’s a type mismatch.

5. Intermediate Code Generation

Definition:
The compiler translates the parsed code into an intermediate
code, which is simpler than the source code but not yet machine-
specific.

Why it’s important:

 Makes the process of optimization easier.

 Allows the same intermediate code to be used across


different hardware platforms.

Example:
For a = b + c, the intermediate code might be:

t1 = b + c

a = t1

6. Code Optimization

198
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Definition:
Optimizing the code involves improving its performance by
reducing memory usage, eliminating unnecessary instructions,
and increasing execution speed.

Why it’s important:

 Ensures the program runs faster and more efficiently.

 Reduces resource consumption.

Example:
Removing redundant calculations or simplifying loops to
execute fewer iterations.

7. Code Generation

Definition:
The intermediate code is converted into machine code, which
consists of binary instructions that the computer’s processor can
execute.
Why it’s important:

 Translates the program into a format the hardware


understands.

 Enables the program to be run on the actual system.

Example:
A high-level statement like print("Hello") might be converted

199
CS25C03 - ESSENTIALS OF COMPUTING REG 25

into machine instructions to access memory and output the text


to the screen.

8. Linking and Loading

Definition:

 Linking involves combining multiple code files or libraries


into one executable program.

 Loading is the process of placing the executable code into


memory and preparing it for execution.

Why it’s important:

 Ensures that all program parts and libraries are available.

 Allows the program to start running on the computer.

4.8.2 Types of Language Implementation

1. Compilation

 The entire program is translated into machine code before


execution.

 Example languages: C, C++, Go

 Pros: Fast execution.

 Cons: Longer compilation time.

2. Interpretation

200
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 The program is executed line-by-line during runtime.

 Example languages: Python, Ruby, JavaScript

 Pros: Easier debugging and testing.

 Cons: Slower execution.

3. Hybrid (Just-In-Time Compilation)

 Combines both compilation and interpretation.

 Example: Java Virtual Machine (JVM), .NET CLR

 Pros: Balances execution speed and flexibility.

Real-Life Analogy

Think of language implementation like translating a recipe from


a foreign language into a language you understand and then
executing it step by step:

 Writing the recipe → source code.

 Identifying ingredients and tools → lexical analysis.

 Understanding the recipe steps → parsing.

 Checking measurements and combinations → semantic


analysis.

 Simplifying steps for efficiency → optimization.

 Cooking the dish → code generation and execution.


201
CS25C03 - ESSENTIALS OF COMPUTING REG 25

4.8.3 Importance of Language Implementation

1. Bridges Human Logic and Machine Execution


Allows programmers to communicate effectively with
computers.

2. Error Checking and Debugging


Provides mechanisms to catch syntax and semantic
errors early.

3. Performance Optimization
Ensures programs are efficient and resource-friendly.

4. Platform Independence
Intermediate code or virtual machines allow programs to
run on different hardware.

5. Supports Innovation
Enables new software, applications, and technologies by
simplifying programming processes.

4.9 DECLARATIVE PROGRAMMING CONCEPTS

Declarative programming is a programming paradigm where the


programmer specifies what the program should accomplish
rather than how to accomplish it. In other words, the focus is on
defining the desired outcome or logic without explicitly
describing the control flow or step-by-step procedures.

202
CS25C03 - ESSENTIALS OF COMPUTING REG 25

This contrasts with imperative programming, where you instruct


the computer on how to perform tasks through loops,
conditionals, and sequences.

Declarative programming is widely used in fields like database


querying, configuration management, and functional
programming.

4.9.1 Key Features of Declarative Programming

1. Focus on What, Not How

 Programmers describe the desired result rather than


the steps to achieve it.

Example: Writing a query to retrieve data from a database


without specifying how the database engine should search for it.

2. Abstraction

 The underlying implementation details are hidden.

 Programmers can focus on the problem logic instead


of technical operations.

3. Immutability

203
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 Many declarative languages avoid changing state or


mutable variables, making programs more predictable
and easier to debug.

4. Side-Effect Free

 Declarative code minimizes or eliminates side effects,


making programs easier to understand and reason
about.

5. Readable and Expressive

 Declarative programs are often closer to natural


language, making them more intuitive.

4.9.2 Types of Declarative Programming

1. Functional Programming

 Based on mathematical functions.

 Avoids mutable data and side effects.

 Examples: Haskell, Lisp, Erlang.

2. Logic Programming

 Uses facts and rules to describe relationships.

 The program derives conclusions from rules.

 Example: Prolog.

204
CS25C03 - ESSENTIALS OF COMPUTING REG 25

3. Database Query Languages

 Used for querying and manipulating databases


without specifying how to search.

 Example: SQL.

4. Markup Languages

 Used to describe structured content.

 Example: HTML, XML.

Examples of Declarative Programming

1. SQL – Structured Query Language

Example Query:

SELECT name FROM employees WHERE department = 'Sales';

Explanation:

 This query specifies what data is needed (names from


employees in the Sales department).

 It doesn’t explain how to search or retrieve it; the


database engine handles those details.

2. Functional Programming Example (Haskell)

sumList :: [Int] -> Int

sumList xs = foldl (+) 0 xs


205
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Explanation:

 This program defines how to sum the elements of a list


using a higher-order function foldl.

 It focuses on what to calculate rather than how to iterate


over the list

4.9.3 Declarative vs Imperative Programmin

Feature Declarative Imperative


Programming Programming

Focus What to do How to do it

Control Abstracted Explicit


Flow

State Immutable Mutable

Examples SQL, HTML, C, Java, Python


Prolog

Readability Higher Lower in complex


cases

Debugging Easier Can be harder due to


side effects

Advantages of Declarative Programming

206
CS25C03 - ESSENTIALS OF COMPUTING REG 25

1. Easier to Read and Maintain


Code is concise and closer to the problem domain.

2. Less Prone to Errors


Reduced complexity and side effects make debugging
easier.

3. Higher Abstraction
Programmers can work at a higher conceptual level.

4. Parallel Execution Friendly


Since data is immutable and state changes are minimized,
declarative programs are easier to parallelize.

5. Reusability
Declarative components can be reused in different
contexts without modification.

Disadvantages of Declarative Programming

1. Limited Control
Programmers cannot fine-tune performance-critical
details.

2. Learning Curve
Abstract concepts can be difficult for beginners.

3. Performance Overhead
Since the underlying process is hidden, it may not be as
optimized as imperative solutions in some cases.

207
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Real-Life Analogies

Recipe vs Cooking Instructions

 Declarative: “Prepare a chocolate cake with frosting.”

 Imperative: “Mix ingredients in this order, bake for 30


minutes at 180°C, then apply frosting.”

Database Query

 Declarative: “Find all books written by 'Agatha


Christie'.”

 Imperative: “Loop through every book, check the author,


and collect matches.”

Where is Declarative Programming Used?

1. Database Management Systems


SQL queries for data retrieval and manipulation.

2. Web Development
HTML for webpage structure.

3. Data Science and Analytics


Frameworks like TensorFlow that describe models
declaratively.

4. Configuration Tools
Infrastructure as Code tools like Ansible or Terraform.

208
CS25C03 - ESSENTIALS OF COMPUTING REG 25

5. Artificial Intelligence
Rule-based systems and expert systems using logic
programming.

4.10 IMPORTANT TWO MARKS

1. What is Program Development Life Cycle (PDLC)?


PDLC is the process of developing a program in stages like
requirement analysis, design, coding, testing,
implementation, and maintenance.
(Anna University – asked in PDLC units)
2. List any two program design tools.
The two common program design tools are flowcharts and
pseudocode.
(Anna University – asked in C Programming 2 marks)
3. Define an algorithm.
An algorithm is a finite, step-by-step procedure to solve a
problem in an efficient and unambiguous way.
(Anna University – frequently asked)
4. What is a flowchart?
A flowchart is a graphical representation of an algorithm
using symbols like rectangles, diamonds, and arrows.
5. What is pseudocode?
Pseudocode is an informal description of a program’s logic
written in plain English using structured statements.
6. What is the role of algorithms in programming?
Algorithms provide a clear and systematic method to solve
problems, ensuring correctness and efficiency in program
execution.
7. What is a programming language?
A programming language is a formal system of rules and

209
CS25C03 - ESSENTIALS OF COMPUTING REG 25

syntax that allows programmers to write instructions for


computers.
8. What is a programming paradigm?
A programming paradigm is a style of programming, such
as procedural, declarative, or object-oriented, that defines
how problems are solved.
(Anna University – asked in CS3251 “Programming in C”)
9. What are traditional programming concepts?
Sequence, selection, iteration, variables, constants, and
functions are the traditional concepts used in programming.
10. What is a procedural unit?
A procedural unit is a self-contained block of code (function
or procedure) that performs a specific task and promotes
modularity.
11. What is meant by language implementation?
Language implementation is the way programming
languages are executed, typically using compilers,
interpreters, or hybrid methods.
12. Define declarative programming.
Declarative programming is a paradigm where the
programmer specifies what needs to be done, not how it
should be done.
13. What is an interpreter?
An interpreter executes program code line by line, making it
easier to debug but slower in execution.
(Anna University – asked in multiple exams)
14. What is a compiler?
A compiler translates the entire source code into machine
code before execution, leading to faster runtime
performance.
(Anna University – frequently asked)

210
CS25C03 - ESSENTIALS OF COMPUTING REG 25

15. Differentiate between procedural and declarative


programming.
Procedural programming explains how to solve a problem
step by step, while declarative programming specifies only
what the result should be.
16. State two advantages of flowcharts.
Flowcharts clearly visualize the program logic and help in
detecting logical errors during design.
17. State two advantages of pseudocode.
Pseudocode is simple, language-independent, and easy to
understand, making it helpful for planning program logic.
18. What is maintenance in PDLC?
Maintenance is the phase where software is updated,
debugged, or enhanced after deployment to meet new
requirements.
19. List the characteristics of a good algorithm.
A good algorithm must be finite, unambiguous, correct, and
efficient.
(Anna University – often asked 2-mark)
20. What is a module in programming?
A module is a self-contained program unit that groups
related functions or procedures, improving reusability and
clarity.

211
CS25C03 - ESSENTIALS OF COMPUTING REG 25

UNIT V SCRATCH PROGRAMMING AND APP


DEVELOPMENT
SYLLABUS

SCRATCH PROGRAMMING

What is Scratch, Scratch Programming Environment, Paint


Editor, Scratch Blocks, Arithmetic Operators and Functions,
Use Motion Commands, Pen Commands and Easy Draw, Looks
Palette, Sound Palette, Power of Repeat, Data Types, Variables,
Getting Input from Users. Making Decisions, Comparison
Operators, Decision Structures, Logical Operators, Repetition,
Loop Blocks, Stop Commands, Counters, Nested Loops,
Recursion, String Processing, String Manipulation, Lists,
Dynamic Lists, Numerical Lists, Searching and Sorting Lists.

APP DEVELOPMENT
Building Apps using problem, solving techniques on any app
development platform, Modeling, incremental and iterative,
reuse, modularization, algorithmic thinking, abstracting and
modularizing, decomposition, testing and debugging.

212
CS25C03 - ESSENTIALS OF COMPUTING REG 25

5.1 SCRATCH PROGRAMMING ENVIRONMENT

The Scratch programming environment is a visual platform designed


to help beginners, especially children, learn coding by connecting
blocks to create interactive stories, games, and animations. The
interface is organized into several key components, each with a
distinct role in building programs.

Main Components of the Scratch Environment

 Stage Area: The stage displays the running program, including all
animations, sprites, and interactions. It uses an X, Y coordinate
system centered at (0, 0) and can be resized or made full-screen
for presentations.

 Sprites: Sprites are graphical objects that perform actions in the


program. The user can select, create, draw, or import new sprites.
Each sprite can have unique costumes (appearances) and sounds.

 Block Palette (Programming Palette): This is the section where


all the command blocks are stored, sorted by categories such as
Motion, Looks, Sound, Events, Control, Sensing, Operators,
Variables, and My Blocks (for custom blocks). Each block is
color-coded for easy identification and fits together like puzzle
pieces, making coding intuitive and error-free.

 Script Area: The workspace where blocks are dragged and


assembled to create scripts for each sprite. Scripts define how
sprites behave and respond to events.

 Costume and Sound Tabs: These provide editing tools for


changing a sprite’s appearance (using vector or bitmap editors)
and for adding or editing sounds linked to the sprite.

213
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 Menu and Controls: Includes options for saving, loading, starting,


and stopping programs, as well as sprite and backdrop
management.

Major Block Categories

Category Color Function

Motion Blue Movement/positioning

Looks Purple Appearance changes

Playing and
Sound Magenta controlling audio

Handling
user/events/starting
Events Yellow code

Conditionals, loops,
Control Orange script management

Sensing Light Blue Detecting interactions

Math, logic,
Operators Green comparisons

Variables Dark Orange Storing project data

Custom code blocks


My Blocks Red (functions)

214
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Each block type has a unique shape indicating its role (hat, stack,
Boolean, reporter, C, cap), and blocks snap together vertically in
scripts.

Building a Scratch Project

 Users start by adding sprites to the stage and then use the block
palette to drag blocks into the script area, forming sequences of
actions.

 Event blocks often begin scripts (e.g., “When green flag clicked”)
and trigger the action.

 Motion, looks, and sound blocks make sprites perform visible and
audible actions.

 Control and sensing blocks allow for interactive and responsive


programs, enabling loops, decisions, and responses to user input.

Visual Representation

 The interface is designed to be user-friendly and visually intuitive,


with block categories and workspace clearly separated for easy
access and navigation.

 Diagrams and screenshots commonly label the stage, sprite list,


script area, and tabs, giving a clear overview for beginners.

Scratch enables learners to develop logic and creativity by providing a


simple, visual method for building programs step by step with instant
visual feedback.

215
CS25C03 - ESSENTIALS OF COMPUTING REG 25

5.2 PAINT EDITOR

The Paint Editor in Scratch is a built-in tool that allows users to create
and edit sprites, costumes, and backdrops using either vector mode or
bitmap mode. It provides a variety of drawing, coloring, and shaping
tools to make unique graphics for projects and animations.

Modes of the Paint Editor

 Vector Mode: Lets users draw smooth shapes using lines,


curves, and points. Objects can be resized and colors, outlines,
and positions can be modified easily. Vector graphics stay
smooth when zoomed or resized.

 Bitmap Mode: Allows pixel-level editing for photos or


detailed artwork, similar to painting in pixel art. Images here
can lose quality when scaled up but allow for nuanced
brush/texture effects.

216
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Users can switch between these modes with a “Convert to Bitmap” or


“Convert to Vector” button.

Main Tools and Features

 Brush/Freehand Tool: Draws freeform shapes and lines.

 Line Tool: Creates straight lines, which can be reshaped or


curved in vector mode.

 Shape Tools: Draws predefined shapes such as rectangles,


circles, and ellipses. Shapes can be modified with the Reshape
tool by adding, moving, or deleting points.

 Fill Tool: Colors areas or shapes with gradients, solid colors,


or transparency.

 Text Tool: Adds text elements that can become part of


costumes, sprites, or backdrops.

 Reshape Tool: Alters vector shapes by dragging, adding, or


removing points for custom designs.

 Select Tool: Selects, moves, rotates, shrinks, expands, flips,


and groups objects for manipulation.

 Color Picker: Provides an expanded palette with gradients and


shades, including transparency options.

 Import: Allows uploading external images or editing defaults


for more elaborate graphics.

 Undo/Redo: Standard editing features for creative flexibility.

217
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Using the Paint Editor

 To create a new sprite, click “Paint” in the sprite menu to


launch the editor in vector mode (recommended for flexibility
and clean shapes).

 Combine basic shapes (circle, rectangle) and use reshape and


color tools to customize appearances (e.g., turning a square
into a triangle for a cat ear).

 Add costumes or backdrops by switching tabs and drawing


with similar tools for background designs, giving scenes
unique visual identity.

 Multiple costumes can be made for a single sprite to create


animations, swaps, and varied visual effects.

The Paint Editor empowers project creators in Scratch to design their


own assets, animate characters, and create diverse, engaging
experiences.

Feature Vector Mode (Default) Bitmap Mode

Graphics Smooth, scalable Pixel-based

Editing Shapes, curves, nodes Pixels, brush-like

Best for Logos, characters Detailed art, pixel effects

Switch Convert option Convert option

218
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Advantages

 Encourages creativity by letting learners design their own


characters.

 No need for external software—everything is built-in.

 Supports both simple art (kids) and complex designs


(advanced users).

 Editable anytime, directly inside the Scratch project.

219
CS25C03 - ESSENTIALS OF COMPUTING REG 25

5.3 SCRATCH BLOCKS

Scratch blocks are the core coding elements in the Scratch


programming language, organized into color-coded categories and
unique shapes that determine their connection and function. Each
block type allows users to build interactive scripts for stories, games,
and animations by snapping blocks together vertically like puzzle
pieces.

Main Block Categories and Functions

Category Color Purpose

Move or rotate
Motion Blue sprites

Change sprite’s
Looks Purple appearance

Play sounds and add


Sound Pink music

Start scripts on
Events Yellow triggers

Loops and program


Control Tangerine flow

Detect input and


Sensing Teal sprite status

Math, logic, value


Operators Green comparisons

220
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Block Shapes and Their Roles

 Hat blocks: Rounded tops, start scripts (e.g., “when green flag
clicked”)

 Stack blocks: Notch at the top, bump at the bottom; common


command blocks that stack

 Boolean blocks: Stretched hexagon shape, return true/false


(used in conditions)

 Reporter blocks: Round edges, return values


(numbers/strings), fit inside other blocks

 C blocks: Wrap shape, loop or wrap other blocks (found in


Control)

 Cap blocks: Notch at top, flat bottom; end a script (e.g., “stop
all”)

How Scratch Blocks Are Used

 Blocks connect vertically in the script area, producing


sequences of actions for sprites.

 Blocks from different categories are snapped together to form


logic, respond to events, move characters, change appearances,
play sounds, and store scores or variables.

 Hat blocks always start scripts; stack blocks fill in the steps;
Boolean/Reporter blocks plug into sockets for logic; C blocks
enclose repeated or conditional actions.

221
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Example Block Stack

A typical beginner script might start with a yellow Event Hat Block
(“When green flag clicked”), move a sprite with a blue Motion Stack
Block (“move 10 steps”), and conditionally play a sound using a pink
Sound Block inside a Control C Block (“if touching edge then…”).

Visual Representation

Scratch’s block palette is designed with clearly separated categories


and distinctive shapes/colors to help users select, organize, and
connect blocks correctly for error-free programming.

5.4 ARITHMETIC OPERATORS AND FUNCTIONS

Arithmetic operators and functions are used to perform mathematical


calculations in Scratch programming.

222
CS25C03 - ESSENTIALS OF COMPUTING REG 25

They are available in the Operators category (green blocks). These


blocks are reporter blocks (oval-shaped) that return a value and can be
used inside other blocks such as motion, control, sensing, or variables.

1. Arithmetic Operators

These are the basic mathematical operators:

Operator Scratch Description Example


Example Output

Addition (+) (5 + 3) Adds two numbers 8

Subtraction (-) (10 - 4) Subtracts the second 6


value from the first

Multiplication (6 * 2) Multiplies two 12


(*) numbers

Division (/) (8 / 2) Divides the first 4


number by the second

2. Comparison Operators

Comparison operators compare values and return a Boolean


result (true/false):

Operator Scratch Description Output


Example

Less than < (5 < 10) True if first value is true


smaller

223
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Greater (7 > 3) True if first value is larger true


than >

Equal to = (4 = 4) True if both values are true


equal

3. Arithmetic Functions

Scratch also provides built-in math functions using the block:

(function of (value))

Available Functions

1. Rounding and Absolute Value

 round (number) → Rounds to nearest integer.

 Example: round (4.7) → 5.

 abs (number) → Absolute value (ignores negative


sign).

 Example: abs (-9) → 9.

2. Square Root

 sqrt (number) → Square root.

 Example: sqrt (16) → 4.

3. Trigonometric Functions (degrees)

 sin (angle) → Sine of angle.

224
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 cos (angle) → Cosine of angle.

 tan (angle) → Tangent of angle.

 asin (value) → Inverse sine.

 acos (value) → Inverse cosine.

 atan (value) → Inverse tangent.

Example: sin (90) → 1.

4. Logarithmic and Exponential Functions

 ln (number) → Natural log (base e).

 log (number) → Base-10 log.

 e ^ (number) → Exponential function.

Example: log (100) → 2.

4. Random Function

 pick random (a to b) → Generates a random number between


two given values.

Examples:

 pick random (1 to 6) → Simulates a dice roll.

 pick random (-240 to 240) → Places sprite at random x-


position on the stage.

225
CS25C03 - ESSENTIALS OF COMPUTING REG 25

5. Shapes of Arithmetic Blocks

 Reporter blocks (oval-shaped) → Return numbers or values.

o Example: (5 + 3), (sqrt (25)).

 Boolean blocks (hexagon-shaped) → Return true or false.

o Example: (score = 100).

226
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Advantages

 The intuitive block interface decreases programming errors.

 Math blocks help learners merge computation and creativity.

 Complex expressions can be built visually without syntax.

 Suitable for educational apps, games, and interactive stories.

5.5 MOTION COMMANDS

Motion commands in Scratch programming are specific blocks used to


control the movement, position, and direction of sprites (characters or
objects) on the stage. These motion blocks are color-coded blue in the
Scratch interface and are fundamental to creating animations, games,
and interactive stories by moving sprites in various ways.

Key Motion Commands in Scratch

 Move (10) Steps: Moves the sprite forward by a specified


number of steps in the direction it is currently facing.
Negative values move it backward.

 Turn Right (15 degrees) / Turn Left (15 degrees): Rotates the
sprite clockwise or counterclockwise by a given angle.

 Point in Direction (90): Sets the sprite’s direction to a specific


angle (e.g., 90 points right).

 Point Towards (Sprite or Mouse Pointer): Rotates the sprite to


face another sprite or the mouse pointer.

227
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 Go to (x, y): Instantly moves the sprite to a specific coordinate


on the stage grid, where (0,0) is the center.

 Glide (seconds) to (x, y): Smoothly moves the sprite over a


specified time to a target coordinate.

 Change x by (number) / Change y by (number): Moves the


sprite horizontally or vertically by a specified number of
pixels.

 Set x to (number) / Set y to (number): Sets the sprite’s exact x


or y coordinate on the stage.

 If on Edge, Bounce: Makes the sprite bounce back when it


touches the screen edge.

 Set Rotation Style: Controls how the sprite rotates visually


(all around, left-right, or no rotation).

Functional Use in Scratch App Development

These motion commands allow programmers to script sprite behaviors,


such as walking, jumping, rotating, and chasing. For example,
pressing arrow keys can move a character left or right using "change x
by" blocks, combined with costume changes to simulate walking.
Glide commands enable smooth animations to specific locations,
enhancing storytelling or gameplay flow. The "if on edge, bounce"
block helps create boundary interactions to keep sprites visible on
screen.

Motion commands form the backbone of dynamic and interactive


Scratch projects, enabling creators to build complex sequences of

228
CS25C03 - ESSENTIALS OF COMPUTING REG 25

movements and rotations for sprites in an intuitive, visual coding


environment.

This detailed explanation covers the essence and practical uses of


Scratch motion commands in programming and app development.

229
CS25C03 - ESSENTIALS OF COMPUTING REG 25

5.6 PEN COMMANDS AND EASY DRAW

Pen commands in Scratch programming are part of an extension that


allows sprites to draw on the stage by leaving marks as they move,
similar to how a pen works. This tool enables creating drawings,
patterns, and graphical effects by controlling the pen's behavior during
sprite movement.

Pen Commands in Scratch

 Pen Down: Activates the pen so the sprite begins drawing


lines as it moves.

 Pen Up: Lifts the pen off the stage, stopping any drawing
while the sprite moves.

 Set Pen Color to [color/number]: Changes the pen's color,


allowing colorful drawings.

 Change Pen Color by [number]: Modifies the current pen


color to create gradients or special effects.

 Set Pen Size to [size]: Sets the thickness of the drawn lines.

 Change Pen Size by [size]: Adjusts the pen thickness by a


relative amount.

 Stamp: Copies the current sprite image onto the stage as a


static drawing.

 Erase All: Clears all pen drawings from the stage without
affecting sprites or backdrops.

230
CS25C03 - ESSENTIALS OF COMPUTING REG 25

These commands work together to enable a range of artistic


programming projects, from simple line drawings to complex
geometric patterns.

Easy Draw in Scratch

Easy Draw is a concept or style often used with the Pen commands to
create simple drawing applications or games in Scratch. It usually
involves scripting the sprite to respond to mouse or keyboard inputs to
control when and how the pen draws on the screen. Typical features
include:

 Drawing only when the mouse button is pressed.

 Changing pen color and size dynamically.

 Erasing or clearing drawings.

 Allowing freehand or shape-based drawing using loops and


pen commands.

Together, Pen commands and easy draw techniques transform Scratch


projects into interactive art tools where users can create visual designs
seamlessly.

This combination helps teach programming logic, conditionals, loops,


and event handling in a creative context, making coding engaging and
visually rewarding for learners.

With motion + pen commands, we can easily draw shapes:

231
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Example 1: Draw a Line

pen down

move 100 steps

pen up

Example 2: Draw a Square

repeat 4

move 100 steps

turn 90 degrees

end

Example 3: Draw a Circle

repeat 36

move 10 steps

turn 10 degrees

end

Example 4: Random Pattern

repeat 50

set pen color to (pick random 1 to 200)

move 50 steps

232
CS25C03 - ESSENTIALS OF COMPUTING REG 25

turn (pick random 1 to 360) degrees

end

Applications in App/Game Development

1. Art & Design Apps

Digital drawing apps where users draw with mouse/sprite.

2. Games

Snake game leaves trails using pen down.

Racing games can track paths drawn with pen.

3. Education Apps

Teaching geometry (shapes, angles, coordinates).

Drawing graphs with pen commands.

4. Interactive Stories

Characters can leave marks or signatures.

Advantages of Pen Commands

 Helps students learn geometry and math visually.

 Enhances creativity through art-based programming.

 Makes game visuals dynamic.

 Very simple and intuitive (like drawing on paper).

233
CS25C03 - ESSENTIALS OF COMPUTING REG 25

234
CS25C03 - ESSENTIALS OF COMPUTING REG 25

5.7 LOOKS PALETTE

1. Introduction

In Scratch, the Looks Palette (purple blocks) controls the appearance


of sprites and the stage.
These blocks allow you to:

 Change sprite costumes (different appearances).

 Control visibility (show/hide).

 Add text (say/think bubbles).

 Apply graphical effects (color, fisheye, whirl, etc.).

 Manipulate the stage background.

They are essential for making animations, storytelling projects, games,


and interactive apps.

2. Applications of Looks Palette in App/Game Development

 Storytelling Apps → Speech/thought bubbles for dialogues.

 Games → Costumes for character animation (walking,


running).

 Educational Apps → Background changes to represent


levels/scenes.

 Animations → Graphical effects (glow, transparency).

 Interactive Apps → Hide/show sprites based on user input.

235
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Functional Use

The Looks palette empowers animators and game developers using


Scratch to make projects more engaging through rich visual
expressions. By integrating costume changes, visual effects, and
speech bubbles, sprites can interact, tell stories, and respond visually
to events in dynamic ways. The layering commands help manage
overlapping sprites for complex scene compositions.

This category is essential for creative, interactive, and visually


compelling Scratch projects where appearance is central to the
experience.

236
CS25C03 - ESSENTIALS OF COMPUTING REG 25

5.8 SOUND PALETTE

The Sound Palette (pink blocks) in Scratch is used to add, play, and
control sounds in a project.
Sounds can make projects more realistic, interactive, and engaging,
especially in:

 Games (background music, collision sounds).

 Animations (character voices, effects).

 Educational apps (pronunciations, feedback tones).

Sprites and the stage can both use sound blocks if sounds are added to
them.

2. Categories of Sound Blocks

A. Play and Control Sound

1. play sound (sound name) until done

o Plays the entire sound and waits until it finishes


before moving to the next block.

o Example: play sound "meow" until done.

2. start sound (sound name)

o Starts playing the sound immediately but doesn’t wait;


next blocks run at the same time.

o Example: start sound "drum beat".

 Used for background music, effects, and continuous sound.

237
CS25C03 - ESSENTIALS OF COMPUTING REG 25

B. Stop Sounds

3. stop all sounds

o Stops every sound currently playing in the project.

 Useful in games when changing background music or


resetting levels.

C. Sound Effects

4. change (pitch v) effect by (10)

o Alters the sound pitch up or down.

o Example: +10 makes sound higher, -10 makes it


deeper.

5. set (pitch v) effect to (0)

o Sets sound effect (pitch or pan left/right) to a specific


value.

6. clear sound effects

o Removes all applied effects, returning sounds to


normal.

 Used to make voices funnier, create echo effects, or balance


stereo sound.

D. Volume Control

238
CS25C03 - ESSENTIALS OF COMPUTING REG 25

7. change volume by ( -10 )

o Increases or decreases current volume.

8. set volume to ( 100 ) %

o Fixes sound volume to a specific percentage (0% =


mute, 100% = full).

9. volume (reporter block)

o Reports the current volume value.

 Used for fading sounds, background music control, or muting


effects.

3. Adding Sounds in Scratch

 You can add sounds to a sprite or stage from:

1. Scratch Sound Library (inbuilt).

2. Recording using microphone.

3. Uploading audio files (MP3, WAV).

4. Applications of Sound Palette in Scratch

A. Games

 Background music using start sound.

 Collision sound effect using play sound until done.

 Stopping sounds when game ends (stop all sounds).

239
CS25C03 - ESSENTIALS OF COMPUTING REG 25

B. Animations & Storytelling

 Characters speaking with say + play sound.

 Sound effects like applause, footsteps, rain.

C. Educational Apps

 Pronunciation of words (recorded sounds).

 Sound feedback when answers are correct/wrong.

D. Music Apps

 Play instruments, beats, or generate sound effects.

 Alter sound with pitch and pan effects.

5. Example Scratch Programs

1. Sprite with Voice

when green flag clicked

play sound [meow v] until done

say "Hello!" for 2 seconds

2. Background Music in Game

when green flag clicked

forever

240
CS25C03 - ESSENTIALS OF COMPUTING REG 25

start sound [background music v]

end

3. Volume Control

when [space v] key pressed

change volume by -10

4. Funny Voice Effect

when this sprite clicked

set pitch effect to 100

start sound [recorded voice v]

clear sound effects

Key Sound Commands in Scratch

 Start Sound [sound]: Plays the specified sound without


waiting for it to finish, allowing other blocks to execute
simultaneously.

 Play Sound [sound] Until Done: Plays the sound and pauses
the script until the sound completes, useful for sequential
sound effects.

 Stop All Sounds: Stops all currently playing sounds


immediately.

 Change Volume By [number]: Adjusts the overall volume


incrementally.

241
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 Set Volume To [number] %: Sets the volume to a specific


percentage.

 Change Pitch Effect By [number]: Alters the pitch of the


sound up or down.

 Set Pitch Effect To [number]: Sets a specific pitch for the


sound.

 Change Pan Effect By [number]: Controls left-right audio


balance.

 Set Pan Effect To [number]: Sets specific left-right balance


in sound output.

 Clear Sound Effects: Resets pitch and pan effects to default.

 Volume Reporter: Reports the current volume level.

 Play Drum [instrument] for [beats] and Play Note [note]


for [beats]: These blocks are used for creating music by
playing musical notes and drum beats (available through
extensions).

 Record and Upload Sounds: Users can record their own


audio or upload sound files (WAV and MP3 formats) to use in
projects.

Functional Uses

The Sound palette is crucial for adding interactive audio elements


such as background music, sound effects for actions (like collisions or
button clicks), character voices, and musical compositions. Sound
commands control when and how sounds are played, adjust their

242
CS25C03 - ESSENTIALS OF COMPUTING REG 25

properties like pitch and volume for creative effects, and integrate
seamless auditory feedback into games and stories.

By combining sound blocks in scripts, Scratch programmers can build


immersive and engaging experiences that go beyond visuals,
enhancing user interaction through sound.

This comprehensive overview covers the sound commands and their


applications in Scratch programming.

5.9 REPEAT AND LOOPING STRUCTURES

1. Introduction

243
CS25C03 - ESSENTIALS OF COMPUTING REG 25

In programming, loops are used to repeat actions multiple times


without writing the same code again.
In Scratch, looping is done using Control blocks (orange blocks).

These looping blocks allow sprites to:

 Move continuously.

 Animate costumes.

 Play sounds repeatedly.

 Run background tasks like timers, score counters, etc.

2. Looping Blocks in Scratch

A. Repeat Loop

1. repeat (10)

o Runs the set of blocks inside it a fixed number of


times.

o Example:

repeat (4)

move 100 steps

turn 90 degrees

end

Draws a square (because it repeats 4 times).

244
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 Best for drawing shapes, running an action for a known


number of times.

B. Forever Loop

2. forever

 Runs the blocks inside it endlessly (until program stops).

forever if <key (space) pressed?>

change y by 10

end Sprite keeps bouncing forever.

 Used for continuous movement, animations, background


music.

C. Repeat Until Loop

3. repeat until <condition>

 Keeps repeating until the condition becomes true.

Example:

repeat until <touching edge?>

move 10 steps

end

Sprite keeps moving until it touches the edge.

245
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 Useful for event-based repetition, like moving until a goal is


reached.

D. Forever If Loop

4. forever if <condition>

o Repeats blocks continuously as long as the condition


is true.

Example:

forever if <key (space) pressed?>

change y by 10

end

Sprite keeps jumping upwards as long as the space key is pressed.

 Used in games for continuous checks (key presses, collisions).

3. Uses of Repeat and Looping Structures

1. Games

o Player movement (forever + key press check).

o Enemies chasing player (repeat until touching player).

o Background animation (clouds moving forever).

2. Animations

o Walking cycle (repeat costume changes).

246
CS25C03 - ESSENTIALS OF COMPUTING REG 25

o Flying bird flapping wings forever.

3. Drawing/Art

o Using repeat loops to make geometric shapes (squares,


circles, spirals).

4. Music

o Looping beats and rhythms using forever.

4. Example Programs

Example 1: Draw a Circle

repeat (36)

move 10 steps

turn 10 degrees

end

Example 2: Continuous Background Music

forever

start sound [music v]

end

Example 3: Move Until Goal

repeat until <touching [goal v] ?>

move 5 steps

247
CS25C03 - ESSENTIALS OF COMPUTING REG 25

end

Example 4: Continuous Character Control

forever

if <key [right arrow v] pressed?>

change x by 10

end

end

Functional Use of Loops in Scratch

 Loops reduce repetitive coding by automating repeated


actions, like moving a character multiple steps or animating a
sprite through costumes.

 The Repeat loop is great for tasks with a predetermined


number of repetitions like drawing shapes or performing a
fixed number of jumps.

 The Forever loop is used for continuous behaviors, such as


keeping background music playing or checking for user inputs.

 The Repeat Until loop is effective for conditional tasks, like


moving a sprite until it reaches the edge of the stage or a game
condition is met.

Using loops efficiently makes Scratch projects more manageable and


dynamic by automating repeated instructions and enabling complex
interaction flows.

248
CS25C03 - ESSENTIALS OF COMPUTING REG 25

This explanation draws from current Scratch programming practices


for repeat and looping constructs.

249
CS25C03 - ESSENTIALS OF COMPUTING REG 25

5.10 DATA TYPES AND VARIABLES

In Scratch, data is used to store, process, and control information


during program execution.
Unlike traditional languages (Python, Java, C++), Scratch is block-
based, so data types are simpler and managed automatically.

Variables in Scratch are containers that hold values like numbers or


text. They can be created by the user and used in scripts for
calculations, control, and display.

250
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Data Types in Scratch

Scratch doesn’t have explicit data type declarations, but values can
belong to these categories:

A. Numeric Data

 Whole numbers (integers) → e.g., 5, 100, -7

 Decimal numbers (floating point) → e.g., 3.14, 0.5, -2.7

 Used for: movement steps, scores, timers, calculations.

B. Text (Strings)

 Any sequence of letters, digits, or symbols inside a variable.

 Example: "Hello", "Game Over", "Player1".

 Used for: names, messages, instructions, user input.

C. Boolean Values

 Only true or false.

 Generated by conditions like <key pressed?>, <touching


sprite?>.

 Used for decision making in if/else or repeat until blocks.

 Scratch doesn’t explicitly say "Boolean type", but conditional


blocks act as Boolean expressions.

251
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Variables in Scratch

A variable is a named storage that can hold numbers or text.


In Scratch, variables can:

 Be created by clicking Make a Variable in the Variables


palette.

 Be shown/hidden on the stage.

 Be updated during program execution.

Types of Variables

1. For all sprites (global variables)

 Accessible by every sprite in the project.

 Example: Score, HighScore, Timer.

2. For this sprite only (local variables)

 Accessible only by the sprite where it was created.

 Example: Speed of car, Health of player.

Variable Blocks in Scratch (Orange Category)

A. Setter & Getter

 set [variable] to (value) → assigns a value.

 change [variable] by (value) → increases/decreases value.

252
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 [variable] → reports the variable’s current value.

B. Visibility

 show variable [variable] → displays variable value on stage.

 hide variable [variable] → hides variable from stage.

Uses of Data & Variables in Scratch

1. Games

 Score increases when sprite collects coins.

 Lives decrease when sprite hits enemy.

 Timer counts down game time.

253
CS25C03 - ESSENTIALS OF COMPUTING REG 25

2. Animations

 Character speed control with variable.

 Position values stored in variables.

3. Mathematics / Education Apps

 Store user input answers.

 Track correct vs. wrong answers.

4. Interactive Stories

 Store player’s name as text.

 Control branching storyline with Boolean conditions.

6. Example Programs

Example 1: Score Counter

when green flag clicked

set [Score v] to 0

forever

if <touching [coin v] ?> then

change [Score v] by 1

end

end

254
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Example 2: Timer

when green flag clicked

set [Time v] to 60

repeat until <(Time) = 0>

wait 1 seconds

change [Time v] by -1

end

say "Game Over!"

Example 3: Storing Player Name

ask [What is your name?] and wait

set [PlayerName v] to (answer)

say (join [Welcome, ] (PlayerName)) for 2 seconds

255
CS25C03 - ESSENTIALS OF COMPUTING REG 25

5.11 USER INPUT

User input means allowing the user (player/learner) to provide data to


the program.
In Scratch, this is done through:

 Ask and Answer blocks (direct text input).

 Key press events (keyboard input).

 Mouse/touch interaction (click, drag, pointer position).

 Sensors (microphone, video motion) in advanced projects.

 User input makes projects interactive, customizable, and


engaging.

Methods of User Input in Scratch

A. Ask and Answer Block (Direct Text Input)

 ask [What's your name?] and wait

256
CS25C03 - ESSENTIALS OF COMPUTING REG 25

o Displays a text box for the user to type an answer.

o Program pauses until input is entered.

 answer

o Stores the user’s typed response.

o Can be assigned to a variable or used in conditions.

Example:

ask [What is your name?] and wait

say (join [Hello, ] (answer)) for 2 seconds

Keyboard Input

Scratch allows sprites to react when specific keys are pressed.

 when [space] key pressed → Event starts when user presses a


key.

 <key [up arrow] pressed?> → Boolean block to check if a key


is pressed.

Example: Character movement in a game.

when [right arrow] key pressed

change x by 10

Mouse Input

The mouse can be used for clicks, pointer position, or dragging.

257
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 when this sprite clicked → Runs script when sprite is clicked.

 mouse x and mouse y → Report mouse pointer position.

 <mouse down?> → Boolean block that checks if mouse


button is pressed.

Example:

forever

go to [mouse pointer v]

end

(Sets sprite to follow mouse pointer).

Touch/Drag Input (in Scratch App/Tablet)

 Sprites can be dragged with touch.

 Projects can be designed with draggable buttons, sliders, or


characters.

Advanced User Input (Optional Sensors)

Scratch also supports extensions:

 Video Motion sensing (camera detects movement).

 Sound sensing (microphone input, e.g., clap to start).

Using User Input with Variables

User input can be stored in variables for further use.

258
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Example: Storing a player’s name.

ask [Enter your name:] and wait

set [PlayerName v] to (answer)

say (join [Welcome, ] (PlayerName))

Example: Quiz program.

ask [What is 5 + 3?] and wait

if <(answer) = 8> then

say [Correct!] for 2 seconds

else

say [Try again!] for 2 seconds

end

Applications of User Input in Scratch

1. Games

 Move characters with arrow keys.

 Enter name/choose difficulty at the start.

 Clicking sprites as buttons.

2. Quizzes & Learning Apps

 Ask math or science questions.

259
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 Collect answers and give feedback.

3. Animations & Stories

 Ask user for their name to personalize characters.

 User decides story paths with input.

4. Music & Art Apps

 Use keyboard to play piano sounds.

 Drag mouse to draw with pen extension.

5. Example Projects

Example 1: Greeting the User

when green flag clicked

ask [What is your name?] and wait

say (join [Hello, ] (answer)) for 2 seconds

Example 2: Simple Quiz

when green flag clicked

ask [What is 10 - 4?] and wait

if <(answer) = 6> then

say [Correct!] for 2 seconds

260
CS25C03 - ESSENTIALS OF COMPUTING REG 25

else

say [Wrong, Try again!] for 2 seconds

end

Example 3: Game Movement

forever

if <key [right arrow] pressed?> then

change x by 5

end

if <key [left arrow] pressed?> then

change x by -5

end

end

Key Concepts of User Input in Scratch

 Ask [question] and Wait: This block displays a question,


typically in a speech bubble from the sprite, and pauses the
script until the user types a response in the input box shown
below the stage.

 Answer Block: This block holds the user's latest typed


response. It updates automatically with each new input. The
answer can be a number or text.

261
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 Using the Answer: The stored response can be used for


decision making (conditional blocks), variable assignment, or
further responses. For example, asking the user’s name,
storing it in a variable, then making the sprite greet the user
by name.

 Examples of Use: Inputting numbers to control sprite


movements (e.g., "How many steps to move?"), collecting
quiz answers, or customizing story elements.

How User Input Works

When the program runs an "ask" block, the question shows on the
screen, and Scratch stops further script execution until the user types
and submits input. This input is then stored in the "answer" block,
which can be referenced anytime after.

This mechanism enables interactive projects where users directly


influence outcomes through text input, adding conversational,
responsive, or personalized features to Scratch creations.

This detailed explanation covers the key blocks for user input and how
they function within Scratch programming.

262
CS25C03 - ESSENTIALS OF COMPUTING REG 25

5.12 DECISION STRUCTURES

Decision Structures in Scratch Programming

1. Introduction

 In programming, a decision structure allows the program to


choose between different actions based on conditions.

 In Scratch, decision-making is controlled using Control


Blocks (orange blocks) with conditions (Boolean expressions).

263
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 These structures make programs dynamic and interactive —


e.g., checking if a key is pressed, if a sprite touches another
sprite, or if a score is above a certain value.

2. Types of Decision Structures in Scratch

A. Simple If Structure

 Block:

 if <condition> then

 // actions

 end

 Executes the actions only if the condition is true.

 If the condition is false, nothing happens.

Example:

if <touching [edge v] ?> then

say [I touched the edge!] for 2 seconds

end

B. If-Else Structure

 Block:

 if <condition> then

 // actions if true

264
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 else

 // actions if false

 end

 Provides two possible paths: one when the condition is true,


and another when it is false.

Example:

if <score > 50> then

say [You Win!] for 2 seconds

else

say [Try Again!] for 2 seconds

End

265
CS25C03 - ESSENTIALS OF COMPUTING REG 25

C. Nested If Structure

 Placing one if block inside another to check multiple


conditions.

Example:

if <score > 80> then

say [Excellent!] for 2 seconds

else

if <score > 50> then

say [Good Job!] for 2 seconds

else

say [Keep Trying!] for 2 seconds

end

end

 Allows multi-level decisions, like grading or multiple game


outcomes.

3. Boolean Conditions in Scratch

Conditions in Scratch are represented by Boolean blocks (green


hexagonal blocks).
Examples:

266
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 <key [space] pressed?>

 <touching [sprite v]?>

 <score > 10>

 <answer = "yes">

These are used inside if / if-else blocks.

4. Applications of Decision Structures

1. Games

o Check if the player scored enough points.

o Decide what happens if sprite collides with enemy.

o Detect if key is pressed for movement.

2. Quizzes & Education

o Check if the user’s answer is correct.

o Provide feedback (Correct/Wrong).

3. Animations & Stories

o Characters react differently based on user input.

o Story branches depending on choices.

4. Simulations

o Control physics (if on ground → stop falling).

267
CS25C03 - ESSENTIALS OF COMPUTING REG 25

o Detect win/lose conditions.

5. Example Programs

Example 1: Collision Detection

forever

if <touching [enemy v] ?> then

say [Ouch!] for 2 seconds

end

end

Example 2: Win or Lose

when green flag clicked

if <score > 100> then

say [You Win!] for 2 seconds

else

say [You Lose!] for 2 seconds

end

Example 3: Grading System

when green flag clicked

ask [Enter your marks:] and wait

268
CS25C03 - ESSENTIALS OF COMPUTING REG 25

if <(answer) > 80> then

say [Grade A]

else

if <(answer) > 60> then

say [Grade B]

else

say [Grade C]

end

end

269
CS25C03 - ESSENTIALS OF COMPUTING REG 25

5.13 COMPARISON OPERATORS

Scratch uses three main comparison operators—"equals to", "greater


than", and "less than"—to compare values and make decisions in code,
returning either true or false (Boolean) results in scripts.

What Are Comparison Operators?

Comparison operators in Scratch, also called relational operators, are


special blocks used to compare two values (numbers, strings, or
variables). They produce a result that is either true or false, which is
used in decision-making blocks like "if" and "if/else" to decide
program behavior. These blocks have a distinctive hexagonal shape
and are colored light-green in Scratch.

Types of Comparison Operators

 Equals to (=)

 Checks if two values are equal.

 For example: 5=55=5 returns


true, “cat”=“dog”“cat”=“dog” returns false.

 Greater Than (>)

 Checks if the first value is greater than the second.

 For example: 7>37>3 returns


true, “zebra”>“ant”“zebra”>“ant” returns true
(because in Scratch, string comparison follows
alphabetical order).

 Less Than (<)

270
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 Checks if the first value is less than the second.

 For example: 2<82<8 returns


true, “apple”<“orange”“apple”<“orange” returns true.

How Comparison Operators Work

Each comparison operator block outputs a Boolean value ("true" or


"false") after evaluating the relationship. These outputs are essential
for controlling program flow in decision structures. For instance, in a
menu-driven Scratch project, a sprite might do something only
if score>50score>50, which means the code inside "if" only runs if the
statement is true.

Using Comparison Operators with Strings

Comparison operators not only work with numbers but also strings
(text). The alphabetic order determines whether a string is considered
"less" or "greater" than another.

Typical Use in Scratch

 They are often found inside "if", "if/else", or "repeat until"


blocks to control when scripts run in projects.

 For example: “If (age < 13), then display ‘Child’; else display
‘Adult’.”

Visual Features

 Operator blocks are hexagonal and light-green, visually


distinguishing them from other Scratch blocks.

 They fit directly into condition slots of if-based blocks.

271
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Summary Table

Operator Symbol Function Example

Checks if values
Equals to = are equal 4 = 4 → True

Checks if 1st
Greater Than > value is greater 5 > 2 → True

Checks if 1st
Less Than < value is less 2 < 3 → True

Comparison operators enable Scratch programs to make decisions,


compare data, and handle different outcomes based on inputs, serving
as a critical foundation for all conditional statements in Scratch.

Example 1: Checking User Input

if <(answer) = [Scratch]> then

say [Correct!] for 2 secs

else

say [Try again!] for 2 secs

end

Here, the program checks if the user typed “Scratch”.

Example 2: Game Over Condition

if <(timer) < (1)> then

272
CS25C03 - ESSENTIALS OF COMPUTING REG 25

say [Game Over] for 2 secs

stop [all v]

end

The program ends the game when time is less than 1.

Example 3: Updating High Score

if <(score) > (high score)> then

set [high score v] to (score)

end

The program updates the high score if the player beats it.

273
CS25C03 - ESSENTIALS OF COMPUTING REG 25

5.14 LOGICAL OPERATORS

Logical operators in Scratch allow programs to make decisions based


on multiple conditions, combining or modifying Boolean values to
control the flow of scripts.

What Are Logical Operators?

Logical operators are blocks that combine or alter truth values


resulting from other conditions, enabling more sophisticated decision-
making in projects. These operators are found in the green
"Operators" section in Scratch and usually have a hexagonal (Boolean)
input area for each condition.

Types of Logical Operators

 AND Operator

 The "AND" block returns true only if both input


conditions are true.

 Example: “score > 50 AND timer < 10” is true only if


both 'score > 50' and 'timer < 10' are true.

 Used when several criteria must be met before


running code.

 OR Operator

 The "OR" block returns true if at least one of the


input conditions is true.

 Example: “lives = 0 OR time_up = true” lets a game


end if either lives run out or time is up.

274
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 Useful when any among several criteria should trigger


code.

 NOT Operator

 The "NOT" block reverses a single Boolean value:


true becomes false, and false becomes true.

 Example: “NOT gameOver” returns true when


'gameOver' is false, continuing game actions.

 Used to check for the opposite of a condition.

How Logical Operators Work

 These blocks process one or two Boolean expressions and


output a single Boolean result.

 Logical operators are essential for constructing complex


conditional statements, such as nesting multiple checks in an
"if" block.

 They often combine results from comparison operators,


forming advanced rules for games, quizzes, and interactive
projects.

Visual Features

 They are light-green blocks typically shaped to fit into


hexagonal Boolean inputs for control statements.

 The “AND” and “OR” blocks have two input slots; “NOT”
has one input slot.

275
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Usage Examples

 “If (age > 13 AND age < 18): display ‘Teen’.”

 “If (score > 50 OR bonusCollected): unlock level.”

 “If (NOT paused): keep moving sprite.”

Summary Table

Logical operators empower Scratch programmers to build complex,


dynamic logic structures that respond intelligently to multiple game or
user conditions.

Operator Inputs Returns True Example


When...

Both temp > 25


conditions are AND raining =
AND 2 true true

At least one coins > 100 OR


condition is doublePoints =
OR 2 true true

Condition is NOT
NOT 1 false playerDead

276
CS25C03 - ESSENTIALS OF COMPUTING REG 25

5.15 REPETITION AND LOOP BLOCKS

Repetition and loop blocks are fundamental programming constructs


in Scratch that allow actions to be repeated automatically without
writing the same instructions multiple times, making code more
efficient and reducing repetition.

What Are Loop Blocks?

Loop blocks are control structures found in the orange "Control"


section of Scratch that enable sprites to repeat actions multiple times
or indefinitely. These blocks save time, reduce code complexity, and
add animation and interactivity to projects.

Types of Loop Blocks

Forever Loop

The "Forever" loop runs indefinitely and only stops when the program
is manually interrupted or stopped. This loop is perfect for:
277
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 Background animations that should continue throughout the


project

 Repetitive actions that don't have a specific end point

 Game mechanics that need to run continuously

Example Use Case: Making a character walk continuously across the


screen or keeping background music playing.

Repeat (X Times) Loop

The "Repeat" loop executes a set of instructions a fixed number of


times, where you specify exactly how many repetitions are needed.
This loop is ideal when:

 You know the exact number of repetitions required

 Creating specific patterns or shapes

 Performing actions a predetermined number of times

Example Use Case: Making a character jump exactly 5 times or


drawing a square (repeat 4 times: move and turn).

Repeat Until Loop

The "Repeat Until" loop continues running until a specific condition


becomes true. This loop is useful when:

 You don't know how many iterations are needed

 The stopping point depends on a changing condition

278
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 Creating interactive behaviors that respond to user input or


game states

Example Use Case: Moving a sprite until it touches the edge of the
screen or continuing a game until the player runs out of lives.

How Loop Blocks Work

Loop blocks process instructions in a cyclical manner. Each complete


execution of the code inside a loop is called an iteration. The loop
continues based on its type:

 Forever loops never stop (until manually interrupted)

 Repeat loops count down from the specified number

 Repeat Until loops check their condition after each iteration

Advanced Loop Concepts

Nested Loops

A nested loop occurs when one loop is placed inside another loop. The
inner loop completes all its iterations before the outer loop moves to
its next iteration. This technique is useful for:

 Creating complex patterns or grids

 Handling two-dimensional operations

 Performing multiple simultaneous actions

Loop Optimization

To improve performance in Scratch projects:

279
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 Minimize operations inside loops

 Use "run without screen refresh" for custom blocks when


appropriate

 Reduce unnecessary code and avoid overly complex nested


structures

 Consider using built-in Scratch optimizations

Practical Applications

Loop blocks enable creators to build:

 Animation Effects: Smooth character movement and visual


effects

 Game Mechanics: Continuous collision detection, scoring


systems

 Interactive Stories: Repeating dialogue or character


behaviors

 Pattern Creation: Drawing geometric shapes, spirals, or


artistic designs

Loop Type Duration Best Used For Example

Continuous
actions, Character
background walking
Forever Indefinite processes endlessly

280
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Known Drawing
Repeat X repetitions, shapes,
Times Fixed number patterns counting

Variable
duration,
Condition- interactive Moving until
Repeat Until based responses edge touched

5.16 STOP COMMANDS

Stop commands in Scratch are essential control blocks that allow


programmers to halt script execution at specific points, providing
precise control over when and how programs terminate.

What Are Stop Commands?

Stop commands are control blocks found in the orange "Control"


section of Scratch that terminate the execution of scripts. The stop
block is unique because it changes its shape depending on the selected
option, making it either a cap block or stack block.

281
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Types of Stop Commands

Stop All

The "stop all" option terminates every script running in the entire
project, effectively functioning like clicking the red stop button. This
command:

 Stops all scripts across all sprites simultaneously

 Has the same effect as manually pressing the stop sign

 Is useful for ending games when certain conditions are met


(like game over scenarios)

Example Use Case: Ending a project when all lives are lost or when a
game completion condition is reached.

Stop This Script

The "stop this script" option terminates only the specific script
containing the stop block. Key characteristics include:

 Only affects the current script where the block is placed

 Other scripts in the same sprite continue running

 Can be used inside loops to break out of repetitive actions

 When used inside custom blocks, it resumes the script that


called the custom block

Example Use Case: Stopping a character's movement script when


reaching a boundary while keeping other scripts (like animation)
running.

282
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Stop Other Scripts in Sprite

This option stops all scripts in the current sprite except the one
containing the stop block. Important features:

 Changes the block from a cap block to a stack block

 Allows the current script to continue while stopping others

 Useful for disabling certain behaviors while maintaining


control

Example Use Case: Stopping movement and sound scripts when a


sprite is hit, while keeping the collision detection script active.

How Stop Commands Work

Stop commands provide immediate termination of script execution


without waiting for current blocks to complete. The behavior varies by
type:

283
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 Stop All: Instantly halts everything, similar to emergency


brakes

 Stop This Script: Cleanly exits the current script stack

 Stop Other Scripts in Sprite: Selective termination while


preserving the controlling script

Advanced Usage Patterns

Conditional Stopping

Stop commands are frequently used within conditional statements to


create dynamic stopping conditions:

 Using variables to control when scripts should stop

 Implementing game over conditions

 Creating pause-like functionality through selective stopping

Workarounds for Specific Script Stopping

Since Scratch doesn't provide direct "stop specific script" functionality,


programmers use several techniques:

 Using variables as flags within loops to control execution

 Broadcasting messages to trigger stop conditions

 Creating separate sprites for scripts that need independent


control

Integration with Broadcasting

284
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Stop commands work effectively with Scratch's messaging system:

 Broadcasting a message can trigger scripts containing stop


commands

 Allows for coordinated stopping across multiple sprites

 Enables complex game state management

Common Implementation Examples

Game Over Scenario:

text

when green flag clicked

forever

if <lives = 0> then

stop [all v]

end

Boundary Detection:

text

when green flag clicked

forever

if <x position > 240> then

stop [this script v]

285
CS25C03 - ESSENTIALS OF COMPUTING REG 25

end

change x by 10

Collision Response:

text

when green flag clicked

forever

if <touching [missile v]?> then

stop [other scripts in sprite v]

play sound [explosion v]

end

Best Practices

 Use "stop all" sparingly, typically for major game state


changes

 Prefer "stop this script" for local control within individual


scripts

 Consider using variables and conditional logic before


resorting to stop commands

 Test stop commands thoroughly, as they can create


unexpected behavior if misused

286
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Stop commands are fundamental tools for creating responsive, well-


controlled Scratch programs that can gracefully handle different
execution scenarios and user interactions.

5.17 COUNTERS

Counters in Scratch are mechanisms that track, increment, or


decrement numerical values during a project’s execution. They are
typically implemented using variables and are essential for features
like scorekeeping, lap counting, timing, and event tracking.

What Is a Counter?

A counter is a variable that represents a running total or tally. It can


increase (increment) or decrease (decrement) based on events in the
program, such as user actions, sprite interactions, or timer ticks.
Scratch provides two fundamental blocks for manipulating counters:

 set [variable] to [value]: Initializes or resets the counter to a


specific value.

 change [variable] by [amount]: Adds (or subtracts, if the


amount is negative) a number to the current value of the
counter.

Creating and Using Counters

1. Defining the Counter Variable

1. In the Variables palette, click Make a Variable.

2. Name your variable (e.g., Score, Lives, Counter).

287
CS25C03 - ESSENTIALS OF COMPUTING REG 25

3. Choose For all sprites or For this sprite only, depending on


whether multiple sprites share the counter.

2. Initializing the Counter

 Use when green flag clicked → set [Counter] to to reset the


counter at the start of the project.

 For lap counters, you might initialize near a starting line


broadcast.

3. Incrementing the Counter

 Attach change [Counter] by blocks to events that increase


the count (e.g., sprite clicks, broadcasts, collisions).

 To decrement, use a negative value: change [Counter] by [-


1].

4. Displaying the Counter

 Ensure your variable is visible on stage by checking its name


in the Variables palette.

 For custom visual counters, create a single-sprite number


counter using clones and costume switching, as detailed in
tutorials on number counters.

Common Counter Patterns

Scorekeeping

text

when green flag clicked

288
CS25C03 - ESSENTIALS OF COMPUTING REG 25

set [Score v] to [0]

when this sprite clicked

change [Score v] by [1]

Lap Counter in Race Game

text

when green flag clicked

set [Lap v] to [0]

when I receive [crossed finish line v]

change [Lap v] by [1]

Timer Counter (Countdown)

text

when green flag clicked

set [Timer v] to [30]

repeat until <Timer < 1>

wait [1] seconds

289
CS25C03 - ESSENTIALS OF COMPUTING REG 25

change [Timer v] by [-1]

end

broadcast [time up v]

This loop counts down from 30 to 0, decrementing once per second.

Advanced Counter Techniques

Custom Number Display

Rather than using the default variable graphic, you can create a visual
counter with custom fonts:

1. Create a sprite with costumes for digits 0–9.

2. Use a digits variable (for this sprite only) to manage each


digit’s position.

3. Clone the sprite multiple times to display multi-digit numbers.

4. Switch each clone’s costume to the correct digit using letter


(digits) of [Counter] and position clones based on digit
indices.

Multi-Sprite Counters

When multiple sprites modify the same counter (e.g., enemy kills),
ensure the variable is set for all sprites. If simultaneous changes
happen unintentionally (e.g., two sprites listening to the same event),
consider:

 Using separate sprite-only variables

290
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 Implementing flags to control when increments occur.

Best Practices

 Reset counters at the start to avoid leftover values.

 Limit counter updates within loops to prevent rapid


unintentional increments; include wait blocks or conditional
guards.

 Use broadcasts for cross-sprite counter events, ensuring


centralized control.

 For visual polish, implement custom counters with number


sprites for a cohesive UI.

Counters are indispensable for interactive Scratch projects, enabling


scoreboards, timers, and dynamic feedback by leveraging variable
manipulation and event-driven increments or decrements.

291
CS25C03 - ESSENTIALS OF COMPUTING REG 25

5.18 NESTED LOOPS

Nested loops in Scratch involve placing one loop block inside another
loop, enabling the creation of two-dimensional patterns, grids, and
complex repeated behaviors by combining multiple levels of
repetition.

What Are Nested Loops?

A nested loop occurs when the body of one loop (the “inner loop”) is
placed within another loop (the “outer loop”). Each time the outer
loop iterates once, the inner loop completes all its iterations, resulting
in repeated execution of the inner loop’s actions for each cycle of the
outer loop.

Types of Loop Blocks for Nesting

 Repeat (X Times) Loop

 Repeat Until Loop

 Forever Loop (used carefully to avoid infinite nesting)

Most commonly, Repeat loops are nested to draw patterns or process


grid-like structures.

How Nested Loops Work

1. Outer Loop Initialization


The outer loop sets a broader repetition count—e.g., the
number of rows to draw in a grid.

292
CS25C03 - ESSENTIALS OF COMPUTING REG 25

2. Inner Loop Execution


Inside each iteration of the outer loop, the inner loop runs
completely—e.g., drawing one row’s columns.

3. Loop Completion
After the inner loop finishes, control returns to the outer loop
to proceed to its next iteration.

Execution Flow

text

Repeat outerCount times

Repeat innerCount times

<Inner Actions>

End Repeat

<Outer Actions>

End Repeat

Use Cases

Grid Drawing

text

when green flag clicked

set [rows v] to [5]

set [cols v] to [5]

293
CS25C03 - ESSENTIALS OF COMPUTING REG 25

pen down

repeat (rows)

repeat (cols)

move (50) steps

turn cw (90) degrees

move (50) steps

turn cw (90) degrees

move (50) steps

turn cw (90) degrees

move (50) steps

turn cw (90) degrees

end

move (0) steps // reposition for next row

end

pen up

This double loop draws 5×5 squares in a grid.

Multiplication Table Generator

text

294
CS25C03 - ESSENTIALS OF COMPUTING REG 25

when green flag clicked

set [i v] to [1]

set [j v] to [1]

repeat (10)

repeat (10)

say (join (join (i) "×") (j)) for (1) secs

change [j v] by [1]

end

change [i v] by [1]

set [j v] to [1]

end

This nested loop displays multiplication facts from 1×1 through 10×10.

Best Practices

 Avoid Infinite Nesting: Combining two Forever loops


without exit conditions will freeze projects.

 Limit Iteration Counts: Use moderate iteration counts to


prevent performance issues.

 Use Broadcasts for Complex Patterns: Break nested actions


into custom blocks and use broadcasts to manage complexity.

295
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 Optimize Positioning: Calculate sprite positioning before


inner loops to streamline drawing routines.

Nested loops open up powerful pattern generation and multi-


dimensional iteration capabilities in Scratch, enabling advanced
projects such as grid art, algorithmic animations, and educational
demonstrations of multiplication and arrays.

296
CS25C03 - ESSENTIALS OF COMPUTING REG 25

5.19 RECURSION

Recursion in Scratch is an advanced technique whereby a custom


block calls itself within its own definition, allowing complex
problems to be solved by breaking them into smaller, similar
subproblems. Although Scratch is primarily designed for iterative
control (loops), its support for custom blocks enables recursive
designs such as fractal drawings, factorial calculations, and the
Fibonacci sequence.

Core Concepts

1. Custom Blocks for Recursion


Scratch’s “My Blocks” palette lets you define new blocks
with parameters. Recursion is implemented by having the
block’s script include a call to itself with updated arguments,
forming a self-referential loop.

297
CS25C03 - ESSENTIALS OF COMPUTING REG 25

2. Base Case
Every recursive procedure requires a termination
condition—the base case—that stops further self-calls.
Without a proper base case, the script would recurse
indefinitely until Stack Overflow occurs or Scratch halts the
project.

3. Recursive Case
The part of the custom block after the base-case check where
the block calls itself with modified parameters (e.g., reduced
size, decremented counter). Each recursive call progresses
closer to the base case.

Typical Recursive Patterns

1. Fractal Tree

text

define drawBranch(length)

if <(length) < (10)> then

stop [this script v]

end

pen down

move (length) steps

turn cw (30) degrees

drawBranch ((length) * (0.7))

298
CS25C03 - ESSENTIALS OF COMPUTING REG 25

turn ccw (60) degrees

drawBranch ((length) * (0.7))

turn cw (30) degrees

pen up

end

when green flag clicked

clear

pen up

go to x: (0) y: (-100)

set pen color to [#654321]

drawBranch (100)

This block draws a branching fractal: each branch spawns two smaller
branches until length < 10, the base case aborts further recursion.

2. Factorial Calculation

text

define factorial(n)

if <(n) = (0)> then

set [result v] to [1]

299
CS25C03 - ESSENTIALS OF COMPUTING REG 25

else

factorial ((n) - (1))

set [result v] to ((n) * (result))

end

end

when green flag clicked

set [result v] to [0]

factorial (5)

say (join (”5! = ”) (result))

Here, factorial calls itself with n–1 until n = 0, then unwinds,


multiplying results back up the call stack.

3. Fibonacci Sequence

text

define fib(n)

if <(n) < (2)> then

set [result v] to [n]

else

fib ((n) - (1))

300
CS25C03 - ESSENTIALS OF COMPUTING REG 25

set [a v] to (result)

fib ((n) - (2))

set [result v] to ((a) + (result))

end

end

when green flag clicked

set [result v] to [0]

fib (7)

say (result)

The block computes fib(n) by calling itself for n–1 and n–2 until
reaching the base case n < 2.

How Scratch Manages Recursion

 Stack Frames: Scratch tracks each custom block call on an


internal stack. Each recursive invocation pushes a new frame.

 Performance Considerations: Deep recursion can be slow or


hit Scratch’s stack limit. Use recursion judiciously, favoring
small depths (e.g., fractals with limited depth or numeric
computations with memoization via lists).

301
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 Debugging: Use say or show variable blocks inside the


recursive block to trace parameter values and ensure the base
case is reached.

When to Use Recursion

 Self-Similar Patterns: Fractals (trees, Sierpinski triangles)


where the same shape repeats at smaller scales.

 Divide-and-Conquer Algorithms: Problems naturally


splitting into subproblems (factorial, Fibonacci).

 Educational Demonstrations: Teaching recursion concepts


visually with turtle graphics-style drawing.

Best Practices

 Always Define a Clear Base Case to avoid infinite recursion.

 Limit Depth by choosing appropriate thresholds (e.g.,


maximum recursion depth or minimum length).

 Combine with Iterative Constructs when performance is


critical; sometimes loops are more efficient for simple
repetition.

 Use Variables Sparingly to store intermediate results if


needed to prevent redundant recalculations (e.g., memoizing
Fibonacci results in a list).

Recursion in Scratch unlocks powerful creative possibilities beyond


standard loops, enabling learners to explore fundamental computer
science concepts through visual programming and custom block
design.

302
CS25C03 - ESSENTIALS OF COMPUTING REG 25

303
CS25C03 - ESSENTIALS OF COMPUTING REG 25

5.20 STRING PROCESSING AND MANIPULATION

Scratch provides a set of string (text) processing blocks in the green


“Operators” category that allow you to combine, inspect, and analyze
text values. These capabilities enable creation of interactive text-based
games, quizzes, and dynamic messages.

304
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Core String Blocks

Join

 Block: join (text1) (text2) or extended versions that join up to


six items.

 Purpose: Concatenates two or more strings, numbers, or


variable values into one continuous text.

 Note: Does not insert spaces automatically; include spaces in


inputs as needed.

Letter of

 Block: letter (index) of (text)

 Returns the character at the specified position (1-based)


within the text. For “apple”, letter 3 of “apple” reports “p”.

Length of

 Block: length of (text)

 Reports the number of characters in the text. For “scratch”, it


returns 7.

Contains

 Block: (text1) contains (text2)?

 Returns true if the second string appears anywhere within the


first, false otherwise. E.g., "hello world" contains
"world" yields true.

305
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Advanced String Techniques

Extracting Substrings

To get a substring of length n starting at position i:

1. Use a loop repeating n times.

2. In each iteration, use letter (i) of (text) and append it to a


result variable via join.

Reversing Text

1. Initialize an empty result variable.

2. Loop from 1 to length of (text).

3. In each iteration, prepend letter (i) of (text) to result,


effectively building the reversed string.

Iterating Over Characters

Create a variable i as an index, then:

text

set [i v] to [1]

repeat (length of [text])

set [char v] to (letter (i) of [text])

// process char

change [i v] by [1]

306
CS25C03 - ESSENTIALS OF COMPUTING REG 25

end

This lets you inspect or transform each character sequentially.

Case-Insensitive Checks

Scratch automatically treats uppercase and lowercase letters equally in


comparison blocks, so "A" = "a" evaluates true.

Detecting Specific Characters

Use contains in loops to check for any of a set of target characters. For
example, to detect letters in user input, iterate through a list or text of
all letters and test each with contains.

Practical Applications

 Quiz Games: Combine ask/answer with join to form


questions and feedback messages.

 Text Art: Use letter of and length of to animate or stylize


individual characters.

 Input Validation: Check contains to ensure responses include


required keywords.

 Dynamic UI: Display changing text like player names, scores,


or status updates.

307
CS25C03 - ESSENTIALS OF COMPUTING REG 25

5.21 LISTS

Lists in Scratch are variable structures that store ordered collections


of items (numbers or text), enabling management of multiple related
values under a single name. They are essential for tasks such as data
storage, dynamic content management, and implementing algorithms
like queues, stacks, and arrays.

Creating and Viewing Lists

 Make a List
In the Variables palette, click “Make a List” and provide a
name (e.g., Scores, Inventory, Names) and scope (For all
sprites or For this sprite only).

 Show/Hide List
Use “show list [ListName]” or “hide list
[ListName]” blocks to control visibility on stage.

Core List Operations

308
CS25C03 - ESSENTIALS OF COMPUTING REG 25

1. Adding and Deleting Items

 add [item] to [List]


Appends an item to the end of the list.

 delete [index] of [List]


Removes the item at the specified position. Use “last” to
delete the final item or “all” to clear the list.

2. Inserting and Replacing

 insert [item] at [index] of [List]


Inserts an item at the given position, shifting subsequent items
right.

 replace item [index] of [List] with [item]


Updates the value at the specified index.

3. Retrieving Information

 item [index] of [List]


Returns the element at that position.

 length of [List]
Reports the total number of items.

 [List] contains [item]?


Returns true if the list includes the specified
item, false otherwise.

 item # of [item] in [List]


Gives the index of the first occurrence, or 0 if not found.

Common Patterns

309
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Looping Through a List

text

set [i v] to [1]

repeat (length of [MyList])

say (item (i) of [MyList])

change [i v] by [1]

end

This pattern processes each list item sequentially.

Using Lists as Queues

 enqueue: add [newItem] to [Queue]

 dequeue:
set [value v] to (item (1) of [Queue])
delete (1) of [Queue]

Using Lists as Stacks

 push: add [newItem] to [Stack]

 pop:
set [value v] to (item (length of [Stack]) of [Stack])
delete (length of [Stack]) of [Stack]

Practical Examples

High Scores Table:

310
CS25C03 - ESSENTIALS OF COMPUTING REG 25

text

when green flag clicked

delete [all v] of [HighScores]

add [500] to [HighScores]

add [750] to [HighScores]

add [300] to [HighScores]

Inventory System:

text

when I receive [picked item v]

add ([item name]) to [Inventory]

Filtering List Items:

text

set [filtered v] to [ ]

set [i v] to [1]

repeat (length of [OriginalList])

if <(item (i) of [OriginalList]) > (10)> then

add (item (i) of [OriginalList]) to [filtered]

end

311
CS25C03 - ESSENTIALS OF COMPUTING REG 25

change [i v] by [1]

end

Lists greatly expand Scratch’s capabilities by enabling storage and


manipulation of multiple data elements, supporting algorithms,
dynamic interfaces, and complex state management in projects.

312
CS25C03 - ESSENTIALS OF COMPUTING REG 25

5.21.1 STRING LISTS

String Lists in Scratch Programming

A string list in Scratch is a list whose items are text values rather than
numbers. String lists are invaluable for managing collections of words,
messages, sentences, or any textual data. They enable projects such as
word games, chatbots, quiz question banks, and text-based animations.

Creating and Managing String Lists

 Make a List
In the Variables palette, select Make a List, name it
(e.g., Words, Questions, Dialogue), and choose For all
sprites or For this sprite only.

 Show/Hide List
Use show list [ListName] or hide list [ListName] to control
on-stage display.

Common String List Operations

1. Adding Items

 add [“apple”] to [Words]


Appends the string “apple” to the end of the list.

2. Inserting Items

 insert [“banana”] at of [Words]


Places “banana” at position 2, shifting later items
right.

3. Deleting Items

313
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 delete of [Words]
Removes the third item.

 delete [all] of [Words] clears the entire list.

4. Replacing Items

 replace item of [Words] with [“orange”]


Changes the first item to “orange.”

5. Retrieving Items and Information

 item [i] of [Words]


Returns the string at position i.

 length of [Words]
Reports how many strings the list contains.

 [Words] contains [“kiwi”]?


Returns true if “kiwi” appears, false otherwise.

 item # of [“pear”] in [Words]


Gives the index of the first occurrence of “pear,” or 0
if absent.

Iterating Over String Lists

To process or display each string:

text

set [i v] to [1]

repeat (length of [Words])

314
CS25C03 - ESSENTIALS OF COMPUTING REG 25

say (item (i) of [Words])

change [i v] by [1]

end

This loop cycles through all list entries, showing each string.

Practical String-List Use Cases

1. Word Scramble Game

 Store words in WordList.

 Pick a random item:


set [word v] to (item (pick random (1) to (length of
[WordList])) of [WordList])

 Scramble letters using string and list blocks.

 Let the player guess the unscrambled word.

2. Dialogue System

 Create Dialogues list with sentences.

 Advance through dialogue on clicks:

text

when this sprite clicked

change [dialogueIndex v] by [1]

say (item (dialogueIndex) of [Dialogues])

315
CS25C03 - ESSENTIALS OF COMPUTING REG 25

end

3. Question Bank for Quizzes

 Populate Questions and Answers lists in parallel.

 On each turn, use the same random index for both lists to pose
a question and verify the answer.

Advanced Techniques

Dynamic Sentence Construction

 Use a Phrase list for sentence fragments (e.g., subjects, verbs,


objects).

 Build random sentences:

text

set [sentence v] to (join (join (item (pick random (1) to (length of


[Subjects])) of [Subjects]) [space]) (item (pick random (1) to (length
of [Verbs])) of [Verbs]))

set [sentence v] to (join (sentence) (join [space] (item (pick random (1)
to (length of [Objects])) of [Objects])))

say (sentence)

Filtering and Searching

To extract only certain strings (e.g., words longer than 5 letters):

text

316
CS25C03 - ESSENTIALS OF COMPUTING REG 25

delete [all] of [LongWords]

set [i v] to [1]

repeat (length of [Words])

if <(length of (item (i) of [Words])) > (5)> then

add (item (i) of [Words]) to [LongWords]

end

change [i v] by [1]

end

Best Practices

 Reset lists at the start of the project to avoid leftover data.

 Keep parallel lists (e.g., questions and answers) synchronized


by managing indices carefully.

 Use descriptive list names to clarify their purpose.

 For large lists, consider hiding them on stage and accessing


items via variable-driven code to declutter the interface.

String lists transform Scratch projects by empowering developers to


handle complex text-based logic, create interactive narratives, and
implement educational games that rely on dynamic string collections.

317
CS25C03 - ESSENTIALS OF COMPUTING REG 25

5.21.2 DYNAMIC LISTS

A dynamic list in Scratch is a list whose contents and size change


during project execution in response to events, user input, or program
logic. Unlike static lists defined at design time, dynamic lists support
real-time data structures such as queues, stacks, history logs, and
ranked leaderboards.

318
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Core Concepts

1. Runtime Modification
Dynamic lists leverage the following blocks to adjust contents
on the fly:

 add (item) to [List]

 delete (index) of [List]

 insert (item) at (index) of [List]

 replace item (index) of [List] with (item)

2. Variable Size
The length of [List] block returns the current count of items,
enabling loops and conditionals that adapt to list growth or
shrinkage.

3. Event-Driven Updates
Dynamic lists often respond to broadcasts, user actions (when
key pressed, when sprite clicked), sensor readings, or timer
loops.

Common Dynamic List Patterns

1. Queue (First-In, First-Out)

text

// Enqueue

when I receive [new message v]

add (message) to [Queue]

319
CS25C03 - ESSENTIALS OF COMPUTING REG 25

// Dequeue

when green flag clicked

forever

if <(length of [Queue]) > 0> then

set [current v] to (item (1) of [Queue])

delete (1) of [Queue]

// process current

end

end

This pattern handles tasks or messages in arrival order.

2. Stack (Last-In, First-Out)

text

// Push

when I receive [new state v]

add (state) to [Stack]

// Pop

when key pressed [space v]

320
CS25C03 - ESSENTIALS OF COMPUTING REG 25

if <(length of [Stack]) > 0> then

set [lastState v] to (item (length of [Stack]) of [Stack])

delete (length of [Stack]) of [Stack]

// revert to lastState

end

Stacks support undo functionality or nested state tracking.

3. Leaderboard (Sorted Dynamic List)

Maintain top scores in HighScores list:

text

when I receive [game over v]

add (score) to [HighScores]

set [i v] to (length of [HighScores])

repeat until <(i) = [1]>

if <(item (i) of [HighScores]) > (item ((i) - 1) of [HighScores])> then

// swap items i and i-1

set [temp v] to (item ((i) - 1) of [HighScores])

replace item ((i) - 1) of [HighScores] with (item (i) of [HighScores])

replace item (i) of [HighScores] with (temp)

321
CS25C03 - ESSENTIALS OF COMPUTING REG 25

end

change [i v] by [-1]

end

// trim list to top 5

repeat until <(length of [HighScores]) = [5]>

if <(length of [HighScores]) > [5]> then

delete [last] of [HighScores]

end

end

This pattern keeps scores sorted and limits the list size.

4. History Log

Track the last n user actions:

text

when this sprite clicked

add (current costume) to [History]

if <(length of [History]) > (n)> then

delete [1] of [History]

end

322
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Maintains a sliding window of recent events.

Managing Dynamic List Integrity

 Bounds Checking: Always verify that an index is between 1


and length of [List] before accessing or deleting to avoid
errors.

 Initialization: Use delete [all] of [List] at start to clear


previous runs.

 Synchronization: For parallel lists (e.g., names and scores),


ensure operations update both lists in tandem.

 Performance: Frequent list operations in long lists can slow


down projects; consider limiting list size or batching updates.

Best Practices

 Limit Unbounded Growth: Use conditional deletions or size


checks to prevent excessively large lists.

 Use Descriptive Names: Name lists to reflect their dynamic


role (e.g., MessageQueue, UndoStack, ActionHistory).

 Leverage Custom Blocks: Encapsulate common list


operations (enqueue/dequeue, push/pop) into reusable blocks.

 Visual Feedback: Show/hide lists strategically to inform


users without cluttering the interface.

 Event-Driven Design: Trigger list updates via broadcasts or


events, separating concerns and improving maintainability.

323
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Dynamic lists empower Scratch projects with flexible, real-time data


handling, enabling sophisticated behaviors such as task scheduling,
undo mechanisms, sorted leaderboards, and interactive histories.

324
CS25C03 - ESSENTIALS OF COMPUTING REG 25

5.21.3 NUMERICAL LISTS

A numerical list in Scratch is a list whose items are numeric values.


Numerical lists are essential for storing and manipulating sequences of
numbers, such as scores, sensor readings, statistical data, or computed
values. They support operations like summing, finding averages,
sorting, filtering, and performing mathematical analyses within
Scratch projects.

Creating and Using Numerical Lists

1. Make a List
In the Variables palette, click Make a List, name it
(e.g., Numbers, Scores, DataPoints) and select its scope (all
sprites or a single sprite).

2. Initialize the List


Use delete [all] of [Numbers] at the start of the project (when
green flag clicked) to clear old data.

3. Adding and Inserting Numbers

 add (value) to [Numbers] appends a number.

 insert (value) at (index) of [Numbers] places a value


at a specific position.

4. Deleting and Replacing

 delete (index) of [Numbers] removes an element.

 replace item (index) of [Numbers] with


(newValue) updates a number in place.

325
CS25C03 - ESSENTIALS OF COMPUTING REG 25

5. Retrieving Information

 item (i) of [Numbers] returns the number at position i.

 length of [Numbers] gives the current count of items.

Common Numerical List Patterns

Summing All Items

text

set [sum v] to [0]

set [i v] to [1]

repeat (length of [Numbers])

change [sum v] by (item (i) of [Numbers])

change [i v] by [1]

end

This computes the total of all values in the list.

Calculating the Average

text

// Ensure list is non-empty

if <(length of [Numbers]) > [0]> then

// Compute sum as above

326
CS25C03 - ESSENTIALS OF COMPUTING REG 25

set [average v] to ((sum) / (length of [Numbers]))

end

Divides the sum by the number of items to find the mean.

Finding Minimum and Maximum

text

// Assume list has at least one item

set [min v] to (item (1) of [Numbers])

set [max v] to (item (1) of [Numbers])

set [i v] to [2]

repeat until <(i) > (length of [Numbers])>

if <(item (i) of [Numbers]) < (min)> then

set [min v] to (item (i) of [Numbers])

end

if <(item (i) of [Numbers]) > (max)> then

set [max v] to (item (i) of [Numbers])

end

change [i v] by [1]

end

327
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Sorting a Numerical List (Bubble Sort)

text

repeat (length of [Numbers])

set [i v] to [1]

repeat (length of [Numbers] - 1)

if <(item (i) of [Numbers]) > (item ((i) + 1) of [Numbers])> then

// Swap items i and i+1

set [temp v] to (item (i) of [Numbers])

replace item (i) of [Numbers] with (item ((i) + 1) of [Numbers])

replace item ((i) + 1) of [Numbers] with (temp)

end

change [i v] by [1]

end

end

This organizes numbers in ascending order.

Filtering Values (e.g., Even Numbers)

text

delete [all] of [Evens]

328
CS25C03 - ESSENTIALS OF COMPUTING REG 25

set [i v] to [1]

repeat (length of [Numbers])

if <((item (i) of [Numbers]) mod (2)) = [0]> then

add (item (i) of [Numbers]) to [Evens]

end

change [i v] by [1]

end

Creates a new list containing only even numbers.

Practical Applications

 Score Analysis: Store and analyze player scores over multiple


rounds.

 Sensor Data Logging: Record and process real-time sensor


readings (e.g., microphone loudness, video sensing).

 Statistical Demonstrations: Teach mean, median, mode by


recording user-entered data.

 Game Mechanics: Manage health values, inventory counts,


or AI decision weights.

Best Practices

 Preallocate Size: If you know the number of items, initialize


the list with default values to simplify indexing.

329
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 Clear Lists on Start: Always delete all items at the beginning


to avoid residual data.

 Use Helper Blocks: Encapsulate common operations (sum,


average, min/max) into custom blocks for reusability.

 Optimize Sorting: For large lists, consider limiting list size


or using more efficient algorithms if performance issues arise
in Scratch.

 Guard Indexes: Verify that index values are within valid


bounds (1 to length of list) before accessing or deleting items
to prevent errors.

Numerical lists in Scratch unlock data-driven capabilities, enabling


projects that collect, process, and analyze numerical information
dynamically during execution.

330
CS25C03 - ESSENTIALS OF COMPUTING REG 25

5.21.4 SEARCHING AND SORTING

Efficiently searching and sorting data stored in lists elevates Scratch


projects from simple storages to dynamic, data-driven applications.
While Scratch lacks built-in search and sort blocks, these operations
can be implemented through scripts using loops, conditionals, and list
manipulation blocks.

Searching in Scratch

Linear Search

Scratch typically uses a linear search to find an item in a list because


lists are not indexed for binary search. A linear search inspects each
element sequentially until the target is found or the list ends.

Implementation:

text

define findItem(target, inList)

set [index v] to [0]

set [i v] to [1]

repeat (length of (inList))

if <(item (i) of (inList)) = (target)> then

set [index v] to (i)

stop [this script v]

end

331
CS25C03 - ESSENTIALS OF COMPUTING REG 25

change [i v] by [1]

end

end

when green flag clicked

set [resultIndex v] to [0]

findItem (“apple”) inList ([MyList v])

say (join (“Found at index ”) (resultIndex))

 Time Complexity: O(n), where n is the list length.

 Use Cases: Checking membership, retrieving position,


validating inputs.

Contains Check

Simpler than returning an index, the contains operator can test


membership:

text

if <([MyList] contains [“apple”])> then

say [Item found!]

else

say [Not found]

332
CS25C03 - ESSENTIALS OF COMPUTING REG 25

end

 Built-In: Uses Scratch’s contains block for lists.

Filtering Items

To search for items matching criteria (e.g., numbers > threshold),


iterate and add matches to a new list:

text

delete [all] of [Filtered]

set [i v] to [1]

repeat (length of [MyList])

if <(item (i) of [MyList]) > (10)> then

add (item (i) of [MyList]) to [Filtered]

end

change [i v] by [1]

end

Sorting in Scratch

Sorting orders list items, typically via simple algorithms. The most
common implementation is bubble sort due to its straightforward
logic.

Bubble Sort

333
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Algorithm: Repeatedly step through the list, compare adjacent items,


and swap them if they are out of order. Continue passes until no swaps
occur.

Implementation:

text

define bubbleSort(inList)

set [n v] to (length of (inList))

repeat (n)

set [swapped v] to [false]

set [i v] to [1]

repeat ((n) - 1)

if <(item (i) of (inList)) > (item ((i) + 1) of (inList))> then

// Swap adjacent items

set [temp v] to (item (i) of (inList))

replace item (i) of (inList) with (item ((i) + 1) of (inList))

replace item ((i) + 1) of (inList) with (temp)

set [swapped v] to [true]

end

change [i v] by [1]

334
CS25C03 - ESSENTIALS OF COMPUTING REG 25

end

if <not (swapped)> then

stop [this script v]

end

end

end

when green flag clicked

bubbleSort ([MyList v])

 Time Complexity: Worst-case O(n²), acceptable for small


lists in Scratch.

 Use Cases: Leaderboards, numeric data ordering,


alphabetizing word lists.

Optimized Bubble Sort

Add a swap flag to exit early if the list becomes sorted before
finishing all passes.

Insertion Sort (Alternative)

Although more efficient than bubble sort for small datasets, insertion
sort is rarely implemented in Scratch due to complexity. However, it
can be scripted by shifting elements and inserting values into their
correct positions.

335
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Practical Considerations

 List Size: Keep lists relatively small (e.g., under 30 items) to


avoid performance lags.

 User Feedback: Show intermediate sorting progress


via say or show variable blocks for educational demos.

 Custom Blocks: Encapsulate search and sort routines into


custom blocks for reuse and readability.

 Combined Patterns: Use search in conjunction with


sorting—for example, find the correct insertion index in a
sorted list to maintain sorted order dynamically.

 Error Handling: Validate list non-emptiness (length > 0)


before searching or sorting to prevent exceptions.

Implementing searching and sorting manually in Scratch deepens


understanding of algorithmic thinking and data structures while
enabling richer interactive projects such as games with leaderboards,
data-driven visualizations, and educational tools.

336
CS25C03 - ESSENTIALS OF COMPUTING REG 25

APP DEVELOPMENT

5.22 BUILDING APPS USING PROBLEM-SOLVING


TECHNIQUES

Effective app development hinges on structured problem-solving


approaches that guide teams from idea inception through delivery and
maintenance. By breaking complexity into manageable tasks,
enforcing clear decision points, and iterating with user feedback, these
techniques help deliver robust, user-centered applications.

1. Define the Problem and Requirements

Before writing a single line of code, it’s essential to understand and


articulate the problem you’re solving:

 Stakeholder Interviews: Engage end users, business


sponsors, and domain experts to gather pain points and
desired outcomes.

 User Stories and Use Cases: Document scenarios in which


users interact with the app, phrased as “As a [role], I want [to
achieve goal] so that [benefit].”

 Requirement Prioritization: Use frameworks like MoSCoW


(Must have, Should have, Could have, Won’t have) to focus
on core functionality first.

2. Break Down the Problem (Decomposition)

Large, nebulous problems must be subdivided into smaller, discrete


tasks:

337
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 Feature Decomposition: Split the app into modules—


authentication, data storage, UI, networking, business logic.

 Task Decomposition: For each feature, define specific tasks


(e.g., “Design login screen layout,” “Implement OAuth token
refresh”).

 Work Breakdown Structure (WBS): Represent tasks


hierarchically to visualize dependencies and estimate effort.

3. Select an Appropriate Development Methodology

Different project contexts call for different process models:

 Waterfall: A linear, phase-gate approach—requirements →


design → implementation → testing → deployment. Best for
well-defined, low-change environments.

 Agile (Scrum/Kanban): Iterative cycles (sprints) deliver


increments of working software. Frequent feedback loops and
backlog refinement adapt to changing requirements.

 Lean/Continuous Delivery: Emphasizes minimal viable


product (MVP), rapid releases, and constant user feedback to
iterate and improve.

4. Architect the Solution

A solid architecture ensures scalability, maintainability, and clear


separation of concerns:

 Layered Architecture: Divide into presentation, application,


domain, and data layers to isolate responsibilities.

338
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 Design Patterns: Apply proven templates like MVC (Model-


View-Controller), MVVM (Model-View-ViewModel),
Repository, and Singleton to standardize solutions.

 API Design: Define RESTful or GraphQL endpoints with


clear resources, actions, and data schemas. Use
OpenAPI/Swagger for documentation.

5. Prototype and Validate

Early prototyping uncovers design flaws and usability issues before


heavy investment:

 Low-Fi Prototypes: Sketch paper or wireframes to validate


user flows and navigation.

 High-Fi Prototypes: Interactive mockups in tools like Figma


or Adobe XD simulate UI behavior and transitions.

 Proof of Concept (PoC): Develop small code experiments to


test critical technical assumptions (e.g., payment gateway
integration).

6. Implement with Test-Driven Development (TDD)

Writing tests first enforces clarity on expected behavior and prevents


regressions:

 Unit Tests: Validate individual functions or classes.

 Integration Tests: Ensure components collaborate correctly


(e.g., network module with mock servers).

339
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 UI/End-to-End Tests: Automate user journeys in


frameworks like Appium or Espresso to catch interface breaks.

7. Continuous Integration and Continuous Deployment (CI/CD)

Automate building, testing, and releasing to increase velocity and


quality:

 CI Pipelines: On each commit, run static analysis,


unit/integration tests, and builds on multiple platforms.

 CD Pipelines: Automate deployment to staging and


production environments, with approval gates and canary
releases to mitigate risk.

8. Monitor, Analyze, and Iterate

Post-release data drives continuous improvement:

 Analytics and Telemetry: Integrate tools like Firebase


Analytics or Mixpanel to track user behavior, crash rates, and
performance metrics.

 A/B Testing: Experiment with UI variants or feature toggles


to quantify impact on engagement and conversions.

 User Feedback Loops: In-app surveys, support channels, and


app store reviews inform backlog refinement.

9. Optimize and Refactor

As apps evolve, maintainability and performance must be preserved:

340
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 Code Reviews and Pair Programming: Encourage


knowledge sharing and early defect detection.

 Refactoring Practices: Regularly restructure code—


eliminate duplication, simplify complex methods, and update
design patterns as needed.

 Performance Profiling: Use profiling tools (e.g., Xcode


Instruments, Android Profiler) to identify bottlenecks in CPU,
memory, and network usage.

10. Security and Compliance

Embed security considerations throughout the lifecycle:

 Threat Modeling: Identify potential attack vectors (e.g., data


leakage, injection flaws) and design mitigations.

 Secure Storage and Transmission: Encrypt sensitive data at


rest (e.g., using Keychain or Android Keystore) and in transit
(TLS).

 Compliance Audits: Ensure adherence to GDPR, HIPAA, or


PCI-DSS where applicable.

By applying these problem-solving techniques—from clear problem


definition and decomposition through agile implementation, testing,
and iterative improvement—development teams can build robust,
user-centric apps that adapt effectively to changing requirements and
maintain high quality over time.

341
CS25C03 - ESSENTIALS OF COMPUTING REG 25

5.23 MODELING AND DESIGN

Modeling and design are foundational phases in the app development


lifecycle that establish the blueprint for building a successful,
maintainable, and scalable application. These activities transform
requirements into structured, visual, and conceptual representations,
guiding developers and stakeholders throughout the project.

1. Purpose of Modeling and Design

 Clarify Requirements: Visualize and validate requirements


through models before starting development.

 Architectural Blueprint: Define app structure, component


interactions, and data flows.

342
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 Facilitate Communication: Provide a shared understanding


among developers, designers, testers, and business users.

 Reduce Risks: Identify design flaws early, preventing costly


rework.

2. Types of Models in App Development

a. Requirements Models

 Use Case Diagrams: Represent high-level interactions


between users (actors) and the app, capturing functional
requirements.

 User Stories: Narrative descriptions of features from the user


perspective, often stored in agile backlogs.

b. Structural Models

 Class Diagrams: Show classes (objects), attributes, methods,


and relationships for object-oriented design. Useful for
backend logic and data models.

 Component Diagrams: Detail modular parts of the app and


their dependencies, such as UI components, services, and
databases.

c. Behavioral Models

 Sequence Diagrams: Illustrate object interactions over time


for specific scenarios (e.g., login process).

 Activity Diagrams: Visualize workflows and decision points,


helping understand app logic and user navigation.

343
CS25C03 - ESSENTIALS OF COMPUTING REG 25

d. Data Models

 Entity-Relationship Diagrams (ERD): Outline data entities


and relationships, guiding database schema design.

 State Diagrams: Describe app states and transitions, useful


for apps with complex state management.

3. Design Principles and Patterns

Design Principles

 Separation of Concerns: Divide app into distinct sections


(UI, business logic, data access) for modularity.

 Encapsulation: Hide internal details to expose only necessary


interfaces.

 Single Responsibility Principle: Each module or class


should have one clear responsibility.

 DRY (Don't Repeat Yourself): Avoid code duplication by


creating reusable components.

Design Patterns

 MVC (Model-View-Controller): Separates data (Model),


user interface (View), and user input handling (Controller).

 MVVM (Model-View-ViewModel): Common in mobile


apps, linking UI with data-binding mechanisms.

 Repository Pattern: Abstracts data layer access to support


multiple storage types transparently.

344
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 Singleton: Ensures a class has only one instance, often for


configuration or resource management.

4. Tools for Modeling and Design

 Diagramming Tools: Microsoft Visio, Lucidchart, draw.io,


or specialized UML tools like StarUML.

 Prototyping Tools: Figma, Adobe XD, Sketch for UI/UX


design.

 Code Generation: Some modeling tools generate code


skeletons based on diagrams for rapid development.

5. Modeling in Agile Development

 Lightweight Modeling: Emphasizes just enough modeling to


guide development and avoid waste.

 Collaborative Design: Involve developers and stakeholders


continuously to refine models.

 User-Centered Design: Prioritize user needs and usability


throughout modeling and design.

6. Benefits of Effective Modeling and Design

 Improved Code Quality: Clear structure reduces bugs and


enhances maintainability.

 Faster Development: Well-defined architecture helps avoid


redesign mid-project.

345
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 Scalability: Designing for growth enables smooth future


feature additions.

 Better User Experience: Thoughtful UI/UX models ensure


intuitive and engaging apps.

Modeling and design bridge the gap between abstract requirements


and concrete implementation, providing a roadmap that delivers
functional, robust, and user-friendly applications efficiently and
reliably.

5.24 INCREMENTAL AND ITERATIVE DEVELOPMENT

ncremental and Iterative Development are two important software and


app development approaches, often combined for effective project
management and delivery.

Incremental Development

 The project is divided into smaller functional parts called


increments.

 Each increment is developed, tested, and delivered


independently as a working piece of the final product.

 Features are added progressively, building the product step-


by-step.

 This allows early delivery of partial functionality, reducing


risk for customers.

 Customer collaboration is improved as feedback can be


integrated after each increment.

346
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 Planning is more upfront and detailed for each increment.

 Risk is managed as increments are delivered but issues may


surface later.

 Example analogy: Building a house floor by floor.

Iterative Development

 The project development is divided into repeated cycles or


iterations.

 Each iteration involves planning, design, implementation,


testing, and evaluation.

 The product is refined continuously, with features added or


improved in each cycle.

 It allows a flexible and adaptive approach where early


feedback steers improvements.

 Testing and feedback happen constantly throughout


development.

 Early risk is identified and mitigated by delivering core


functionality early.

 Example analogy: Writing a draft and refining it multiple


times.

347
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Both Together (Iterative and Incremental Development)

 Often combined for best results, developing each increment


through iterative cycles.

 Allows early delivery with continuous feedback and


refinement.

 Provides risk reduction, improved quality, and flexibility.

 Facilitates continuous improvement and stakeholder


collaboration throughout the project.

Iterative and Incremental Development in Scratch Programming

 Scratch programming employs iterative and incremental


design principles.

 Iteration (loops) is a fundamental concept allowing the


repetition of sequences for refinement.

 Development in Scratch is often incremental by building


projects in small parts (e.g., scripts or sprites) and iteratively
improving them.

 This encourages learners to experiment, receive feedback, and


progressively enhance their projects.

This detailed explanation clarifies how incremental and iterative


development complement each other in app and programming
development contexts, including Scratch.

348
CS25C03 - ESSENTIALS OF COMPUTING REG 25

5.25 REUSE AND MODULARIZATION

Modularization in app development is the architectural practice of


dividing an app into discrete, independent modules, each responsible
for a specific functionality or domain. This approach fosters reuse,
maintainability, scalability, and enhanced collaboration within
development teams.

Key Principles of Modularization

 High Cohesion & Low Coupling:


Modules should have internally related functionalities (high
cohesion) and minimal dependency on other modules (low
coupling). This ensures changes in one module don’t ripple
undesirably into others, facilitating easier updates and testing.

 Encapsulation:
Each module hides its internal workings and exposes a clear
interface for communication with other modules. This

349
CS25C03 - ESSENTIALS OF COMPUTING REG 25

abstraction enforces boundaries and makes modules reusable


as black boxes.

 Clear Interfaces:
Well-defined APIs or contracts specify how modules interact,
enabling independent development and reducing integration
issues.

 Reusability:
Modules can be reused across different parts of the same app
or even in different apps. For example, a network or
authentication module can serve multiple projects.

Common Types of Modules

 Feature Modules: Implement specific app features like user


profiles, messaging, or payments.

 UI Modules: Centralize custom UI components for reuse


across features to maintain consistent design.

 Core/Common Modules: Contain utilities, network clients,


analytics, and helpers frequently required by other modules.

 Platform-specific Modules: Separate modules for device-


specific implementations (e.g., wearables, TV apps).

Benefits of Modularization

 Simplified Maintenance and Updates:


Problems in one module can be fixed or updated without
affecting the entire app, reducing risk and downtime.

350
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 Parallel Development:
Different teams can work concurrently on separate modules,
accelerating development and fostering specialization.

 Scalability & Flexibility:


New features can be added as new modules or enhancing
existing ones without impacting unrelated areas.

 Improved Testing and Debugging:


Isolated modules allow targeted unit testing and easier bug
identification.

 Faster Builds with Gradle and Build Tools:


Modular projects can benefit from incremental compilations,
speeding up the development cycle.

Implementing Modular Architecture — Best Practices

1. Analyze & Plan: Understand app requirements and clearly


identify functional boundaries for each module.

2. Keep Modules Independent: Avoid cross-module


dependencies beyond necessary interfaces.

3. Define Clear Interfaces: Design APIs or service contracts for


communication in a stable way.

4. Create Reusable Components: Build generic modules that


can be reused across projects.

5. Test Modules Separately: Perform unit tests and integration


tests for each independently.

351
CS25C03 - ESSENTIALS OF COMPUTING REG 25

6. Document Thoroughly: Maintain clear documentation for


functionality, interfaces, and usage of modules.

7. Monitor & Refactor: Regularly check module size,


complexity, and coupling to prevent deterioration of
modularity.

Popular Modularization Patterns in Android App Development

 Base Modules: Fundamental code shared across features.

 Feature Modules: Specific app functionality.

 Dynamic Features: Optional features downloadable on


demand.

 Core/UI/Network Modules: For reusable UI elements,


network communication, and utilities.

352
CS25C03 - ESSENTIALS OF COMPUTING REG 25

5.26 ALGORITHMIC THINKING IN APP DEVELOPMENT

Algorithmic thinking in app development refers to the ability to break


down complex problems into smaller, manageable, and logically
ordered steps or processes to design effective solutions. It is essential
for writing efficient, maintainable, and scalable code and underpins
problem-solving and functional design in app creation.

Key Components of Algorithmic Thinking

 Decomposition: Breaking down a complex problem into


smaller subproblems or tasks which are easier to solve and
understand.

 Pattern Recognition: Identifying similarities and recurring


patterns in problems to apply known solutions or optimize
processes.

353
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 Abstraction: Focusing on important information and ignoring


irrelevant details to create simplified models or algorithms.

 Algorithm Design: Creating clear, step-by-step instructions


or procedures for solving a problem, like writing a recipe or a
flowchart.

Why Algorithmic Thinking Matters in App Development

 Enables developers to thoroughly understand problems before


coding, leading to more effective solutions.

 Helps build modular and reusable components by addressing


subproblems independently.

 Facilitates debugging and optimization by isolating logical


steps.

 Supports designing algorithms for sorting, searching, data


handling, and UI logic crucial in apps.

 Improves communication and collaboration via clear problem


descriptions and solution plans.

Process of Applying Algorithmic Thinking

1. Understand the Problem: Analyze requirements, inputs,


outputs, and constraints.

2. Break it Down: Decompose into smaller manageable


problems.

3. Develop Algorithms: For each subproblem, outline step-by-


step solutions (possibly using pseudocode or flowcharts).

354
CS25C03 - ESSENTIALS OF COMPUTING REG 25

4. Combine Solutions: Integrate subsolutions into a coherent


whole.

5. Test and Optimize: Validate correctness, identify edge cases,


optimize for efficiency.

Examples in App Development

 Searching/filtering a list of items.

 Navigating routes or maps.

 Processing user inputs and validations.

 Implementing sorting algorithms for displayed data.

 Building recommendation systems using pattern recognition.

Enhancing Algorithmic Thinking Skills

 Solving puzzles or coding challenges.

 Practicing decomposition of everyday problems.

 Studying common algorithmic strategies: recursion, greedy


algorithms, dynamic programming.

 Writing pseudocode or flowcharts before coding.

 Iteratively refining algorithms based on testing and feedback.

Algorithmic thinking is critical for building robust, efficient, and


scalable applications. It gives developers a systematic framework to
approach problems, design logical solutions, and produce quality code.

355
CS25C03 - ESSENTIALS OF COMPUTING REG 25

If needed, a diagram illustrating the core principles and process of


algorithmic thinking can be provided.

Sources:

356
CS25C03 - ESSENTIALS OF COMPUTING REG 25

5.27 ABSTRACTION AND DECOMPOSITION

Abstraction in App Development

 Definition:
Abstraction is the concept of hiding complex internal
implementation details and exposing only the essential
features or interfaces needed by the user or other parts of the
system. It manages complexity by focusing on the "what"
rather than the "how."

 Purpose and Benefits:

 Simplifies software design by hiding unnecessary


details.

 Enhances code maintainability and readability.

 Enables modular design with clear interfaces.

 Facilitates reuse and scalability by separating


interface from implementation.

 Improves security by controlling access to sensitive


data or internal workings.

 Examples:

 Abstract classes and interfaces in object-oriented


programming encapsulate behavior without
specifying the implementation.

 APIs expose functionalities without revealing


underlying complexity.

357
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 In app UI, abstraction manifests as high-level


components hiding lower-level implementation
details.

 Levels of Abstraction:

 High-level: Focus on overall architecture and major


components.

 Mid-level: Modules or subsystems abstraction.

 Low-level: Class or function-level abstraction hiding


technical details.

 Use in Design Patterns and Architecture:

 Enables layered architecture (presentation, business,


data layers).

 Supports design patterns like Factory, Adapter, and


Facade which rely on abstraction to unify interfaces
or hide complex operations.

Decomposition in App Development

 Definition:
Decomposition is the process of breaking down a complex

358
CS25C03 - ESSENTIALS OF COMPUTING REG 25

system, problem, or application into smaller, more


manageable parts or components (modules, functions,
services). This divides a large problem into subproblems
which can be solved independently.

 Purpose and Benefits:

 Reduces complexity by focusing on smaller pieces at


a time.

 Improves modularity, making the system easier to


build, test, and maintain.

 Facilitates parallel development in teams.

 Helps in identifying reusable components.

 Supports clear boundaries and responsibility


delegation in system design.

 Types of Decomposition:

 Functional decomposition: Breaking down into


smaller functions or procedures.

 Object-oriented decomposition: Dividing system into


interacting objects or classes.

 Service decomposition (e.g., microservices): Dividing


system into loosely coupled services.

 Layered decomposition: Dividing architecture into


layers like UI, business logic, and data access.

359
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 Strategies:

 Single Responsibility Principle: Each component has


one responsibility.

 Cohesion and coupling principles to maximize


independent functionality within modules.

 Use domain-driven design to decompose by business


capabilities or domains.

Relationship Between Abstraction and Decomposition

 Decomposition breaks down a system into parts; abstraction


hides the internal workings of those parts. Together, they
make complex apps manageable by:

 Dividing functionality (decomposition).

 Hiding internal complexities behind interfaces


(abstraction).

 Both guide architecture design, coding practices, and testing


methodologies.

5.28 TESTING AND DEBUGGING

Testing and debugging are crucial phases in app development that


ensure the quality, functionality, usability, and performance of an
application before its release. Testing involves evaluating the app to
find defects or issues, while debugging focuses on identifying and
fixing those defects to improve the app’s stability and user experience.

Testing in App Development

360
CS25C03 - ESSENTIALS OF COMPUTING REG 25

Testing is the process of systematically checking the app's features


and performance to verify it meets the specified requirements. It
encompasses several types and methodologies:

 Manual Testing: Human testers interact with the app to find


usability issues, navigation flaws, and UI inconsistencies by
simulating real-world scenarios.

 Automated Testing: Uses scripts and tools to repeatedly test


functionalities, regression, compatibility, and performance
across devices and operating systems with greater speed and
accuracy.

 Beta Testing: Involves giving access to a limited group of


external users to gather real-world feedback on bugs,
performance, and user preferences before the final release.

 Types of Testing: Unit testing (individual components),


integration testing (component interactions), system testing
(overall behavior), acceptance testing (user requirements
compliance), and performance testing.

Key goals of testing include detecting functional errors, verifying


performance, validating user experience, and mitigating risks of

361
CS25C03 - ESSENTIALS OF COMPUTING REG 25

failures or security vulnerabilities. Early testing during development


helps reduce correction costs and improve overall product reliability.

Debugging in App Development

Debugging is the process following testing where developers identify,


analyze, and correct errors or bugs discovered in the app. It involves:

 Setting up a development environment with tools like


integrated debuggers and logging.

 Using breakpoints to pause execution and inspect code


behavior.

 Analyzing stack traces and error logs to locate the root cause
of problems.

 Fixing issues related to code logic, UI layouts, memory leaks,


network errors, and performance bottlenecks.

 Continuous retesting after fixes to ensure bugs are properly


resolved and no new issues arise.

Effective debugging can shorten development time, prevent crashes,


enhance user satisfaction, and reduce maintenance costs. It is
necessary at every stage from development through testing to post-
deployment monitoring.

Importance of Testing and Debugging Together

Together, testing and debugging:

 Ensure the app functions as intended and meets quality


standards.

362
CS25C03 - ESSENTIALS OF COMPUTING REG 25

 Help catch defects early, increasing development efficiency.

 Improve user experience through thorough usability and


performance validation.

 Reduce risks of costly bugs affecting security, usability, or


business operations.

 Support continuous improvement by providing feedback


loops from testing results back into debugging and code
refinement.

These practices are vital for building reliable, secure, and high-
performing applications, especially in complex and diverse mobile
environments where user devices and conditions vary significantly.

In summary, testing detects issues in the app, and debugging resolves


these issues to deliver a polished, functional, and user-friendly product.

363
CS25C03 - ESSENTIALS OF COMPUTING REG 25

5.29 IMPORTANT TWO MARKS

1) What is Scratch?
Scratch is a block-based visual programming language used
for creating interactive stories, animations, games, and
simple applications.
2) What is the Scratch Programming Environment?
The Scratch environment provides a stage, sprites, and
block palettes where users can drag and drop blocks to
create programs.
3) What is the use of the Paint Editor in Scratch?
The Paint Editor allows users to create or edit costumes and
backgrounds for sprites.
4) What are Scratch blocks?
Scratch blocks are visual coding elements that represent
commands or instructions in Scratch.
5) Name any two arithmetic operators in Scratch.
Addition (+) and Multiplication (×).
6) What is the purpose of the Pen commands in Scratch?
Pen commands are used to draw shapes, lines, and patterns
on the stage.
7) What is the function of the Looks palette?
The Looks palette is used to control the appearance of
sprites, such as changing costumes, showing/hiding, or
displaying text.
8) What is a variable in Scratch?
A variable is a named storage element used to hold values
that can change during program execution.
9) What is a loop block? Give an example.
A loop block is used to repeat a set of instructions. Example:
repeat (10) block.

364
CS25C03 - ESSENTIALS OF COMPUTING REG 25

10) What is a list in Scratch?


A list is a collection of items (numbers or strings) that can
be stored, accessed, searched, or sorted in Scratch.

REFERENCES

1. Peter Norton, Introduction to Computers, McGraw Hill


Education, 7th Edition, 2017.
2. V. Rajaraman, Fundamentals of Computers, Prentice Hall
of India, 6th Edition, 2014.
3. Reema Thareja, Computer Fundamentals and
Programming in C, Oxford University Press, 2nd Edition,
2016.
4. Alan Bundy, Computational Thinking, Springer, 2019.
5. Jeannette M. Wing, “Computational Thinking”,
Communications of the ACM, Vol. 49, No. 3, pp. 33–35,
2006.
6. R.G. Dromey, How to Solve it by Computer, Prentice-Hall
of India, 2006.
7. Ellis Horowitz, Sartaj Sahni, and Rajasekaran,
Fundamentals of Computer Algorithms, Galgotia
Publications, 2008.
8. David M. Mount and Sunil Arya, Problem Solving and
Algorithms, University of Maryland Lecture Notes, 2010.
9. Miller & Ranum, Problem Solving with Algorithms and
Data Structures, Franklin, Beedle & Associates Inc., 2nd
Edition, 2009.
10. John V. Guttag, Introduction to Computation and
Programming Using Python, MIT Press, 2nd Edition, 2016.
11. MIT Media Lab, Scratch Programming Guide, MIT Press,
2020.

365
CS25C03 - ESSENTIALS OF COMPUTING REG 25

12. Majed Marji, Learn to Program with Scratch: A Visual


Introduction to Programming with Games, Art, Science,
and Math, No Starch Press, 2014.
13. Timothy Lethbridge & Robert Laganière, Object-
Oriented Software Engineering: Practical Software
Development using UML and Java, McGraw Hill, 2005.
14. Thunkable, App Development Platform Documentation,
Available at: https://docs.thunkable.com
15. MIT App Inventor Team, MIT App Inventor: Create Apps
for Android, Available at: http://appinventor.mit.edu

**** All The Best****

366

You might also like