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

Basics of Complicated Concept Programming Logic-V06

This document discusses the history of computers and programming. It covers the evolution of computers from the first generation to present day, and the development of programming languages from the first computer programs to modern languages. It also examines problem solving techniques and computational thinking. Key topics include the first four generations of computers, early programming languages like FORTRAN, classifications of programming languages, and influential figures in problem solving like Alan Turing.

Uploaded by

Tom
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
0% found this document useful (0 votes)
103 views

Basics of Complicated Concept Programming Logic-V06

This document discusses the history of computers and programming. It covers the evolution of computers from the first generation to present day, and the development of programming languages from the first computer programs to modern languages. It also examines problem solving techniques and computational thinking. Key topics include the first four generations of computers, early programming languages like FORTRAN, classifications of programming languages, and influential figures in problem solving like Alan Turing.

Uploaded by

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

THE BASICS OF A COMPLICATED CONCEPT

(Programming logic)


TinyContent – V06
Naisit Publisher
© 2021

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Contents

THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Chapter 1 ...........................................................................................................................................................................10

Trace the Path Traveled By The Magnificent Machines ........................................................................................................ 10


History of Computer .............................................................................................................................................................. 10
The First Generation – Baby Steps Indeed ............................................................................................................................ 12
The Second Generation – A Significant Improvement In The Right Direction ....................................................................... 13
The Third Generation – Strengthening Of The Foundation ................................................................................................... 14
The Present Generation (1981 Onwards) – Inventions Galore.............................................................................................. 16
The Internet And The Smartphone Revolution – A Trendsetter Of Its Own .......................................................................... 18
Final Words ........................................................................................................................................................................... 19
References............................................................................................................................................................................. 20

Chapter 2 ...........................................................................................................................................................................21

The History of Computer Programming ................................................................................................................................ 21


The First-ever Computer Program ......................................................................................................................................... 22
First Generation Programming Language .............................................................................................................................. 23
Third Generation Programming Language - FORTRAN .......................................................................................................... 24
Fourth Generation Programming Languages ........................................................................................................................ 27
Fifth Generation Programming Languages ............................................................................................................................ 28
Classification of Programming Languages ............................................................................................................................. 28
Types of Development .......................................................................................................................................................... 29
Types of Developers .............................................................................................................................................................. 30
Food for Thought................................................................................................................................................................... 31
References............................................................................................................................................................................. 32

Chapter 3 ...........................................................................................................................................................................33

Computer Basics .................................................................................................................................................................... 33


Parts Of A Computer System ................................................................................................................................................. 35
Types Of Devices ................................................................................................................................................................... 37
Difference Between Input And Output Devices: ................................................................................................................... 38
Important Definitions And Classifications ............................................................................................................................. 38

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Difference Between Hardware And Software ....................................................................................................................... 41


Final Words ........................................................................................................................................................................... 42
Food For Thought .................................................................................................................................................................. 43
Some Interesting Facts About Computers ............................................................................................................................. 44
References............................................................................................................................................................................. 45

Chapter 4 ...........................................................................................................................................................................47

History of Problem Solving .................................................................................................................................................... 47


What is Problem Solving? ...................................................................................................................................................... 47
What Are the Types of Problem Solving? .............................................................................................................................. 48
Why is Problem Solving Important? ...................................................................................................................................... 50
Influential Figures in Problem Solving ................................................................................................................................... 50
Other Figures in Problem Solving .......................................................................................................................................... 51
Relation of Computation with Problem Solving .................................................................................................................... 52
Computational Problems and Computational Thinking ........................................................................................................ 52
What is Computational Thinking? ......................................................................................................................................... 53
Two Historical Problem-Solving Tools ................................................................................................................................... 55
Food For Thought .................................................................................................................................................................. 56
Final Words ........................................................................................................................................................................... 57
References............................................................................................................................................................................. 58

Chapter 5 ...........................................................................................................................................................................59

Steps To Solve A Problem ...................................................................................................................................................... 59


Introduction .......................................................................................................................................................................... 59
What Is A Computational Problem? ...................................................................................................................................... 60
What Is Computational Thinking? ......................................................................................................................................... 61
The Four Cornerstones Of Computational Thinking .............................................................................................................. 61
The Five-Step Method For Solving Computational Problems ................................................................................................ 63
Helpful Tools In Solving Problems ......................................................................................................................................... 65
Tips For Solving A Problem .................................................................................................................................................... 67
Final Words ........................................................................................................................................................................... 70
References............................................................................................................................................................................. 72

Chapter 6 ...........................................................................................................................................................................73

What Are Algorithms? ........................................................................................................................................................... 73


Introduction To Algorithms ................................................................................................................................................... 74
Search And Sort Algorithms .................................................................................................................................................. 75
Types Of Algorithms .............................................................................................................................................................. 76
Algorithm Development Process ........................................................................................................................................... 81
Run-time Analysis Of Algorithm ............................................................................................................................................ 82

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Final Words ........................................................................................................................................................................... 84


Food For Thought .................................................................................................................................................................. 84
References............................................................................................................................................................................. 85

Chapter 7 ...........................................................................................................................................................................87

Flow Charts ............................................................................................................................................................................ 87


Introduction To Flowcharts ................................................................................................................................................... 88
Shapes Of Flowchart.............................................................................................................................................................. 91
Branches, Conditions, And Decisions .................................................................................................................................... 92
Drawing Flowcharts Using MS Visio ...................................................................................................................................... 95
Drawing Flowcharts Using Different Tools ............................................................................................................................ 96
Open source and free tools ................................................................................................................................................... 96
Paid tools ............................................................................................................................................................................... 97
Applications ........................................................................................................................................................................... 97
Final Words ........................................................................................................................................................................... 99
Food For Thought ................................................................................................................................................................ 100
References........................................................................................................................................................................... 101

Chapter 8 .........................................................................................................................................................................102

Pseudocode ......................................................................................................................................................................... 102


Introduction to Pseudocode ................................................................................................................................................ 102
Let's start with a simple example of pseudocode: .............................................................................................................. 103
Algorithm & Pseudo-code ................................................................................................................................................... 105
How To Write Pseudocode .................................................................................................................................................. 106
Branches, Conditions, And Decisions Using Pseudocode .................................................................................................... 108
Food for Thought................................................................................................................................................................. 115
Final Words ......................................................................................................................................................................... 116
References........................................................................................................................................................................... 117

Chapter 9 .........................................................................................................................................................................118

Binary, Hex Numbers, ASCII Code, And Conversions ........................................................................................................... 118


Standard number systems................................................................................................................................................... 119
Computer Units Of Measurement ....................................................................................................................................... 120
Introduction To Binary, Hex, And ASCII Code ...................................................................................................................... 120
Conversions ......................................................................................................................................................................... 125
Final Words ......................................................................................................................................................................... 130
Food For Thought ................................................................................................................................................................ 131
References........................................................................................................................................................................... 132

Chapter 10 .......................................................................................................................................................................134

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Introduction To Programming ............................................................................................................................................. 134


Introduction To Programming ............................................................................................................................................. 135
Programming Development Cycle ....................................................................................................................................... 137
Input, Processing, Output .................................................................................................................................................... 139
Converting Flowcharts And Pseudocode Into A Program.................................................................................................... 140
Final Words ......................................................................................................................................................................... 141
Food For Thought ................................................................................................................................................................ 142
References........................................................................................................................................................................... 143

Chapter 11 .......................................................................................................................................................................144

Basics of Shell Programming ............................................................................................................................................... 144


What is Shell Scripting? ....................................................................................................................................................... 146
What Is Git Bash & Why Do You Need It? ........................................................................................................................... 147
How to install Git Bash? ...................................................................................................................................................... 147
Input/Output Techniques .................................................................................................................................................... 148
What is STDIN? .................................................................................................................................................................... 150
What is STDOUT? ................................................................................................................................................................ 152
What is STDERR? ................................................................................................................................................................. 154
Defining A Variable In A Programming Interface ................................................................................................................. 156
Final Words ......................................................................................................................................................................... 159
References........................................................................................................................................................................... 161

Chapter 12 .......................................................................................................................................................................162

Operators in Shell Script ...................................................................................................................................................... 162


What Is An Operator?.......................................................................................................................................................... 162
Why Do We Need Operators? ............................................................................................................................................. 163
Types Of Operators ............................................................................................................................................................. 164
Arithmetic Operators .......................................................................................................................................................... 164
Why Are Arithmetic Operators Used? ................................................................................................................................. 165
Relational Operators ........................................................................................................................................................... 167
Why Are Relational Operators Used? .................................................................................................................................. 168
Boolean Operators .............................................................................................................................................................. 171
Why Are Boolean Operators Used? ..................................................................................................................................... 171
Bitwise Operators ................................................................................................................................................................ 174
Why Are Bitwise Operators Used? ...................................................................................................................................... 175
File Test Operators .............................................................................................................................................................. 176
Why Are File Test Operators Used? .................................................................................................................................... 177
How To Handle Operators Using Variables And Numbers .................................................................................................. 180
Operator Precedence (Order of Operations)....................................................................................................................... 181
Final Words ......................................................................................................................................................................... 183
References........................................................................................................................................................................... 185

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Chapter 13 .......................................................................................................................................................................186

Decision Control Structure: Truth Tables & Conditional Statements .................................................................................. 186
What is Truth Table? ........................................................................................................................................................... 186
What is a Boolean value? .................................................................................................................................................... 187
What is a Boolean Expression? ............................................................................................................................................ 187
Types Of Conditional Statements And Their Syntax ............................................................................................................ 189
What is an If statement? ..................................................................................................................................................... 189
What is the Switch statement? ........................................................................................................................................... 191
Conditions ........................................................................................................................................................................... 194
Bash String Conditions......................................................................................................................................................... 194
Bash Number Conditions ..................................................................................................................................................... 195
Bash File Conditions ............................................................................................................................................................ 196
What are conditional statements and logical operators? ................................................................................................... 197
A simple example of conditional statements and logical operators ................................................................................... 198
What are the arithmetic operators? ................................................................................................................................... 198
Why do you need arithmetic operators? ............................................................................................................................ 198
Application of Conditional and Nested Conditional Statements ......................................................................................... 200
Final Thoughts ..................................................................................................................................................................... 202
Food for Thought................................................................................................................................................................. 203
References........................................................................................................................................................................... 204

Chapter 14 .......................................................................................................................................................................205

Decision Control Structure & Conditional Statements - Explained ..................................................................................... 205


Conditional Statement Explained with An Example ............................................................................................................ 205
Practice Problems................................................................................................................................................................ 207
Problem-A ........................................................................................................................................................................... 207
Problem-B............................................................................................................................................................................ 209
Problem-C............................................................................................................................................................................ 210
Problem-D ........................................................................................................................................................................... 211
Problem-A Solution ............................................................................................................................................................. 212
Problem-B Solution ............................................................................................................................................................. 215
Problem-C Solution ............................................................................................................................................................. 218
Problem-D Solution ............................................................................................................................................................. 221
Final Words ......................................................................................................................................................................... 224
Food for Thought................................................................................................................................................................. 225
References........................................................................................................................................................................... 226

Chapter 15 .......................................................................................................................................................................227

Defining and Understanding Iterations (Loops) In Bash Scripting ....................................................................................... 227


What is Iteration.................................................................................................................................................................. 227

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

FOR loop .............................................................................................................................................................................. 228


Using lists in FOR loop ......................................................................................................................................................... 228
Using ranges in FOR loop..................................................................................................................................................... 230
C-style FOR loop Syntax ....................................................................................................................................................... 231
For Loop Flowchart And Code Example ............................................................................................................................... 232
While and Until Loops ......................................................................................................................................................... 235
Breaking Statement ............................................................................................................................................................. 236
Continuing Statement ......................................................................................................................................................... 237
Infinite loop ......................................................................................................................................................................... 238
Example of an infinite loop.................................................................................................................................................. 238
While Loop Flowchart And Code Example........................................................................................................................... 239
Problems to Solve................................................................................................................................................................ 240
Solutions .............................................................................................................................................................................. 241
References........................................................................................................................................................................... 245

Chapter 16 .......................................................................................................................................................................246

Advanced Examples of Iterations (Loops) In Bash Script ..................................................................................................... 246


Problem A ............................................................................................................................................................................ 247
Problem B ............................................................................................................................................................................ 247
Problem C ............................................................................................................................................................................ 248
Problem D............................................................................................................................................................................ 248
Problem A Solution: ............................................................................................................................................................ 249
Problem B Solution: ............................................................................................................................................................. 251
Problem D Solution: ............................................................................................................................................................ 256
References........................................................................................................................................................................... 261

Chapter 17 .......................................................................................................................................................................262

Learning Function in Bash Scripting .................................................................................................................................... 262


What Is A Function? ............................................................................................................................................................ 262
How to Define A Function? ................................................................................................................................................. 263
How To Call A Function? ...................................................................................................................................................... 264
Built-In Functions and Shell Script Function Libraries. ........................................................................................................ 265
Syntax and Method Of Calling A Function ........................................................................................................................... 265
How to Return Values? ........................................................................................................................................................ 266
What Is an Attribute or Parameter? .................................................................................................................................... 267
Global and Local Variables .................................................................................................................................................. 268
Recursion ............................................................................................................................................................................. 269
Common Errors with Declaring and Using Functions .......................................................................................................... 271
Problems to Solve................................................................................................................................................................ 272
Solutions .............................................................................................................................................................................. 272
References........................................................................................................................................................................... 274

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Chapter 18 .......................................................................................................................................................................275

Advanced Examples on Functions ....................................................................................................................................... 275


Problem A ............................................................................................................................................................................ 275
Problem B ............................................................................................................................................................................ 277
Problem C ............................................................................................................................................................................ 277
Problem D............................................................................................................................................................................ 278
Problem-A Solution ............................................................................................................................................................. 280
Problem-B Solution ............................................................................................................................................................. 283
Problem-C Solution ............................................................................................................................................................. 284
Problem-D Solution ............................................................................................................................................................. 286
Exercise: .............................................................................................................................................................................. 288
Final Words ......................................................................................................................................................................... 289
References........................................................................................................................................................................... 291

Chapter 19 .......................................................................................................................................................................292

Bash Script: File Handling Commands in GitBash ................................................................................................................ 292


Read a File ........................................................................................................................................................................... 292
Create a New Directory ....................................................................................................................................................... 294
View all the directories ........................................................................................................................................................ 295
Remove a directory ............................................................................................................................................................. 295
Write to a File ...................................................................................................................................................................... 296
Append to a File .................................................................................................................................................................. 299
Update a File ....................................................................................................................................................................... 300
Other File Handling Commands........................................................................................................................................... 301
Exercise: .............................................................................................................................................................................. 302
Final Words ......................................................................................................................................................................... 303
References........................................................................................................................................................................... 304

Chapter 20 .......................................................................................................................................................................305

Advanced Examples On File Handling In Bash ..................................................................................................................... 305


Practice Problems................................................................................................................................................................ 306
Problem-A ........................................................................................................................................................................... 306
Problem-B............................................................................................................................................................................ 307
Problem-C............................................................................................................................................................................ 308
Problem-D ........................................................................................................................................................................... 309
Problem-A Solution ............................................................................................................................................................. 310
Problem-B Solution ............................................................................................................................................................. 312
Problem-C Solution ............................................................................................................................................................. 313
Problem-D Solution ............................................................................................................................................................. 316
Problems to Solve................................................................................................................................................................ 318

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Solutions .............................................................................................................................................................................. 319


Final Words ......................................................................................................................................................................... 321
References........................................................................................................................................................................... 322

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Chapter 1

Trace the Path Traveled By The Magnificent Machines


A world without computers would be unimaginable in today's times. We can't

thank enough the geniuses who invented the computer and modified and

perfected it through different epochs in history. The legacy they have left behind

is invaluable. Here's a brief history of computers, the most important invention

of the modern era.

History of Computer

"Necessity is the mother of invention." And humans have invented magnificent

machines over the years, starting from the wheel to vehicles to computing marvels

such as 'Computers.' Though one uses the computer for various purposes today, it

was invented to resolve a severe number-crunching crisis. The tabulation of the

1880 US Census results led to the invention of computers. However, the credit for

sowing the magnificent invention seeds goes to the English mathematician, Charles

Babbage (1822).

10

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

The Difference Engine (Serial no. 2), which was invented by Charles Babbage. Located currently in the Computer History
Museum in Mountain View, Silicon Valley, California. Image source: Flickr.com

The incredible history of modern computers began in 1890; Herman Hollerith


designed a punch card system to calculate the 1880 US census and accomplished
the task in three years. He went on to establish an organization that would
ultimately be known as IBM.

In the earlier days, computers were restricted to specific operations. It took over
four decades for scientists to come up with the notion of a universal machine. Alan

11

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Turing presented the first such machine in 1936, and the modern-day computers
result from his concepts.

This tabular description could help explain matters better.

Inventor Type Functions

Charles Difference • A steam-driven mechanical computer capable of


Babbage Engine performing simple calculations

• Automated equipment that uses punch cards as input


Charles Analytical
• Capable of solving mathematical problems and also
Babbage Engine
storing information as a permanent memory

• An improvement on the mechanical computers


Herman Tabulating designed by Charles Babbage
Hollerith Machine • Uses punch cards as input and can tabulate statistics
while recording and sorting data

• An analog device, also referred to as the first


electronic computer
Vannevar Differential • Uses vacuum tubes to switch electrical signals for
Bush Analyzer performing calculations
• Capable of performing up to 25 calculations in a few
minutes

The First Generation – Baby Steps Indeed

The First-Generation computers (1937 to 1946) were massive machines occupying


voluminous space running into hundreds of square feet. This period witnessed the
introduction of the world's first electronic digital computer in 1937, thanks to the

12

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

efforts of Dr. John V Atanasoff and Clifford Berry. Appropriately, the machine
was named ABC (Atanasoff Berry Computer). Other inventors like Howard Aiken
developed devices capable of performing calculations involving large numbers.

Though initially, computers were number-crunching devices, gradually, other uses


started emerging. For instance, an electronic computer was built in 1943,
exclusively for the military. The year 1946 saw the birth of the first general-
purpose digital computing machine, ENIAC (Electronic Numerical Integrator and
Computer). This machine weighed a massive 30 tons and used more than 18,000
vacuum tubes for processing. It was a significant challenge to power this computer
and to keep it cooled. As they did not have any OS (Operating System), this
computer could not perform more than one task.

Inventor Type Functions

Howard Aiken Calculating • Developed to perform calculations involving


Machine large numbers
IBM and Harvard Mark-I • The first programmable digital computer
Computer
John Mauchly and J. ENIAC • The first general-purpose digital computer
Presper Eckert • Designed as a stored-program computer
EDVAC working on binary rather than decimal

The Second Generation – A Significant Improvement In The Right Direction

The second-generation (1947 to 1962) saw a substantial improvement in the


hardware design with the phasing out of the vacuum tubes and transistors replacing
them. 1953 was a watershed year in computers' history because of introducing the

13

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

first computer for commercial use, the Universal Automatic Computer (UNIVAC
1). The same year saw IBM manufacturing its 650 and 700-series computers. This
generation also saw the introduction of various computing programs like COBOL
(Common Business Oriented Language), FORTRAN (Formula Translation), and
the integrated circuit's introduction, also known as 'the chip.'

Some of the popular second-generation computers are,

a) IBM 1620
b) IBM 7094
c) CDC 1604
d) CDC 3600
e) UNIVAC 1108

The Third Generation – Strengthening Of The Foundation

The chip's invention paved the way for the third generation of computers (1963 to
1980), leading to a revolution in the computer manufacturing industry. In 1969,
Bell Labs invented the first operating system, UNIX. The Dynamic Access
Memory chip (DRAM) was born in 1970 when Intel unveiled the world's first
DRAM chip, Intel 1103. It was followed by many path-breaking inventions like
the floppy disk, Ethernet, and other hardware.

This period between 1963 and 1980 was a golden period with the incorporation of
companies such as Microsoft in 1975 by Paul Allen and Bill Gates, and Apple
Computers by Steve Jobs and Steve Wozniak.

Though IBM started manufacturing mainframe computers in 1952, the demand for
these massive machines peaked during the 1960s and 1970s. Mainframe computers

14

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

are often used as servers. One can link numerous individual personal computers to
these servers and form a network.

Here are some popular third-generation computers.

a) IBM 360 Series


b) Honeywell 6000 Series
c) Personal Data Processor – PDP
d) IBM 370/168
e) TDC 316

The period from 1971 to 1980 saw the invention of the following computers.

a) DEC 10
b) STAR 1000
c) PDP 11
d) CRAY – 1
e) CRAY – X – MP

The last two names were the first supercomputers to see the light of day.

15

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Apple-1, the first computer designed by Steve Jobs and Steve Wozniak in the 1970s

Image Source: Barnebys.com

The Present Generation (1981 Onwards) – Inventions Galore

The world's first personal computer, Acorn, was released in 1981 by IBM. It
worked on Microsoft's MS-DOS operating system with an Intel chip, an optional
colour monitor, and two floppy disks.

Apple introduced the first PC with a GUI in 1983. It was named Lisa but
eventually evolved into the Macintosh. The same year witnessed the invention of
the first portable computer Gavilan SC, which was marketed as a laptop.

March 15, 1985, was a red-letter day in the history of computers because of the
registration of the first dot-com domain name before the birth of the World Wide
Web and the formal introduction of the internet. Around the same time in 1985,
Microsoft announced Windows.

16

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Inventions started gathering pace with Tim Berners-Lee developing HTML in


1990 as a precursor to the World Wide Web. The Pentium processors made their
appearance in 1993, whereas gaming machines were introduced to the world in
1994.

1996 witnessed the launch of the Google search engine by Sergey Brin and Larry
Page. Wi-Fi became a reality in 1999 as users started to connect to the internet
without wires.

The 21st century had an auspicious beginning, which started by introducing the
MacOS by Apple and the rolling out of Windows XP by Microsoft in 2001.

The world's first 64-bit processor, AMD Athlon 64, saw the light of day in 2003.

The present-day generation computers can be classified as,

a) Desktop PC
b) Laptop
c) Notebook
d) Ultrabook
e) Chromebook
f) MacBook

Are we missing out on something? Yes, it is the smartphone. Read on to know


more.

17

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

A modern-day laptop

Image source: Pickpik.com

The Internet And The Smartphone Revolution – A Trendsetter Of Its Own

If someone had predicted that you would be able to carry the computer in your
pocket at the time of the ENIAC installation, the world would have termed them
insane. However, every one of us does hold a computer in our palms and accesses
the internet using a device better known as a smartphone.

With the internet technology developing at a tremendous pace, it was a matter of


time before we carried the computer in our pockets. Besides being extremely
portable, smartphones can pack in much more data than multiple ENIACs put
together. It can perform complicated calculations within no time. The smartphone

18

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

and the internet have opened up several vistas of communication. Thus, we can say
that the computer has travelled a long way since the days of Charles Babbage. It
has brought the world closer. At this developmental rate, we do not know what the
future holds for us; computers have made radical changes to the world we live in.

Final Words

The subsequent events in the history of computers are too recent to merit a mention
here. Today, we carry a piece of computer in our hands in the form of smartphones
and other devices that we use daily. Since the inception of the first 'computer,' we
have travelled quite a long way, but the inventors' legacy still lives on. We have
traced the path that computers have travelled since 1820. Now, we are indeed at a
crossroads where the computer defines the way we go forward.

19

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

References
1. Contributor, K. (2020). History of Computers: A Brief Timeline. livescience.com.
Retrieved August 23, 2020, from https://www.livescience.com/20718-computer-
history.html.

2. History of Computers. Homepage.cs.uri.edu. (2020). Retrieved August 23, 2020, from


https://homepage.cs.uri.edu/faculty/wolfe/book/Readings/Reading03.htm.

3. Contributor, S.H., The History of Computer Technology, Medium.com (March 07, 2019)
Retrieved August 24, 2020, from https://medium.com/newtown-partners/the-history-of-
computer-technology-cf87154a7bc1

20

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Chapter 2

The History of Computer Programming


Computer programming languages instruct the computers what to do, but the
way they introduce varies from language to language. This chapter looks
through the complex but exciting history of computer programming and
discusses different programming languages.

The credit for giving birth to computer programming goes to an English


noblewoman, Ada Lovelace, who created an algorithm for the Analytical Engine of
Charles Babbage in 1883. Then in 1936, Alan Turing and Alonzo Church
specialized computer codes for the first time in 1936. They devised a formulaic
way of expressing lambda calculus.

Different Programming Languages


Image Source: www.toppr.com

21

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

The First-ever Computer Program

In 1843, Ada published for the first time, a sequence of steps to perform
calculations, using the differential engine designed by Charles Babbage. She used
these notes to calculate Bernoulli numbers, a mathematical series. These notes
constituted the first-ever computer program.

Gradual Evolution of Computing Programming

Jon Von Neumann, working at the Institute of Advanced Study, in 1945, developed
two significant concepts that would go on to shape computer programming.

• Shared-Program Technique: This technique envisaged the computer hardware


to be simple without needing to be hard-wired for every task it accomplishes.
He proposed that one should use complicated instructions for controlling the
hardware, thereby allowing it to be reprogrammed quickly.
• Conditional Control Transfer: This concept formed the genesis of computer
programming because it considered having subroutines. Instead of following a
single set of chronological steps, the computer could jump towards an
alternative solution. This idea gave birth to logical statements like 'IF,' 'THEN,'
and 'FOR.'

22

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

The Chronological Sequence to the Development of Computer Programming

Classification of Different Programming Languages


Image source: www.geeksforgeeks.com

The First Era of Programming Languages - Up to 1970

Konrad Zuse, a German scientist, used concepts from Jon Von Neumann's work in
his machines and the Plankalkul programming language. This language was the
first high-level programming language and started the early era of programming.

First Generation Programming Language

1949 witnessed the birth of the language Short Code, the first computer language
for electronic devices. Short Code was primitive because the programmer had to
change the statements into 0's and 1's manually. Nevertheless, it was the initial step
towards the development of modern computer languages.

23

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Second Generation Programming Language

Second Generation Programming encompasses assembly languages.

In 1951, Grace Hopper devised the first compiler, A-0. The compiler converted
language statements into 0's and 1's automatically for the computer to understand
better. With the programmer no longer having to do anything manually, the speed
of programming increased significantly.

Third Generation Programming Language - FORTRAN

John Backus and other scientists at IBM designed the first high-level programming
language, FORTRAN, on October 15, 1956. FORTRAN is derived from the words
- FORmula TRANslating system. This program used the statements, 'IF,' 'DO,' and
'GOTO.' It might appear to be restrictive by today's standards, but it was a path-
breaking for its time.

• Business Computing Program – COBOL


FORTRAN was good at handling numbers, but it could not handle 'Input'
and 'Output' properly. In 1959, Grace Hooper and Bob Bemer invented
COBOL, the Common Business Oriented Language. COBOL was an easy
language to learn because it used English-like grammar. The goal was to
make it easy for the average businessperson to learn and adopt it.

• BASIC - Programming for people without a computer background


On May 01, 1964, Thomas Kurtz, Mary Keller, and John Kemeny
introduced the first computer language for people not having a computer
background. It was named BASIC, short for Beginner's All-Purpose
Symbolic Instruction Code.

24

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Microsoft still uses an extended form of BASIC in its VB (Virtual Basic)


product.

Birth of Pascal – A combination of Algol, FORTRAN, and COBOL

Pascal's development marked the end of the first era of computer programming and
signalled the second era's birth with the development of languages like C and C++.
Niklaus Wirth developed Pascal in 1968 as a necessity for a useful teaching tool. It
combined the best features of other languages like Algol, FORTRAN, and COBOL
by refining their irregularities and cleaning them.

The Second Era of Computer Programming – Post 1970

This era of computer programming paved the way for developing different
programming languages to cater to many requirements. It also began when
computers were starting to be accepted globally.

• The invention of C - 1972


The second era of computer programming can be said to have started
developing the C language in 1972 at Bell Labs. Dennis Ritchie gets the
credit for beginning the transition from the first computer programming
languages to today's languages.

• An extension of C – C++
C++, an extension of C language, is used in the in-game engines and
software like Adobe Photoshop. Developed by Bjarne Stroustrup in 1983,
C++ is still the preferred language for many packaged software.

25

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

The same year saw the development of a unique language used for writing
software for iOS and macOS. Named as Objective-C, Brad Cox and Tom
Love created it.

• The language that statisticians speak – R


R is the preferred language of data analysts and statisticians because of its
user-friendliness. The credit for designing this language goes to Ross Ihaka
and Robert Gentleman in 1993 at the University of Auckland in New
Zealand.

• Web development language – PHP


With the Internet sweeping everything in front of it, PHP (Personal Home
Page) became the most commonly used programming language for web
development. Today, PHP finds its applications in building some of the most
extensive websites, such as facebook.com. Rasmus Lerdorf invented PHP in
1995 to manage his online information.

• JavaScript
JavaScript has a reputation for being created in the shortest time - just ten
days by Brendan Eich in 1995. It is universally used for enhancing web
browser applications.

• Replacement for C, C++, and Objective-C – Swift


With the advancement in computer programming technology, there is
always room for improvement. Apple developed Swift in 2014 as a
replacement for C, C++, and Objective-C, as it is easy to use. It is one of the
more universal languages for desktop, mobile apps, and cloud services.

26

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Fourth Generation Programming Languages

Fourth Generation Languages have statements that are similar to human languages.
A single command that the programmer enters can allow it to perform multiple
everyday operations. These are easier to use for users than first-generation
(machine languages), second-generation (assembly languages), and third-
generation (older high-level) languages. They include SQL, Ruby, Python, Pel, and
MatLab.

• Mathematical Language – MATLAB


Developed by Cleve Moler in 1978, MATLAB stands for Matrix
Laboratory.

MATLAB is one of the best computer programming languages for writing


mathematical programs. It has tremendous use in education and mathematics
research. One can also create 2D and 3D graphics using MATLAB.

• Database Programming Languages – SQL


Perhaps, SQL can be called the backbone of all those complex databases that
we see today. It was developed in 1974 by Raymond Boyce and Donald
Chamberlin. Structured Query Language (SQL) uses command sentences for
adding, removing, and viewing data.

• The language that social media loves – Python


1991 saw the emergence of a new language, Python, which has since
become one of the most favoured frameworks for social media sites like
Instagram and YouTube. Designed by Guido Van Rossum, Python is easy to
read and requires fewer code lines.

27

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Fifth Generation Programming Languages

These languages have visual tools that help programmers develop the program.
Some examples are OPS5, Mercury, and Prolog.

• Mercury – For Real-World Uses


Mercury is a language which has a functional logic programming. Three
scientists in the Computer Science department of the University of
Melbourne, namely Zoltan Somogyi, Fergus Henderson, and Thomas
Conway, released it on April 8, 1995. Mercury is a language that operates
on purely declarative logic programming and features a polymorphic type
system, which is both strong and static.
• OPS5- Rule-Based Programming Language
It became the first production system language used on the R1/XCON
system to configure the VAX computers. Charles Forgy of the Carnegie
Mellon University invented it back in the 1970s. The forward-chaining
interference engine is the crucial characteristic of the OPS5 language.

Classification of Programming Languages

There are various classifications of programming languages. We discuss some of


the categories in the table below.

Low-level Languages High-level languages


They are languages that are very close to These languages are user-friendly and easy
machine language and are also called to understand. They are closer to human
Assembly languages. languages.
Unlike high-level languages, they do not They have concise codes and flexible

28

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

need compilers. syntax.


They are architecture-specific and run They are functional and object-oriented.
directly on the processor.
Suitable for developing new operating Suitable for writing applications that can
systems. run on various platforms.
Example: Machine code, Binary Example: Python, Java, C++

High-level languages are further classified into the following types:

Compiled Language Interpreted Language


It takes the entire program as a single input It takes single instruction as input and
and converts it into object code. executes the instruction.
It generates intermediate object code and It does not generate the intermediate object
hence requires more significant memory. code, and hence, the memory requirement is
less.
Examples are C, C++ Examples are Perl, Python, Matlab

Types of Development

• Front End Development A front end developer is in charge of the user side of
the applications. They code webpages, software, games, and application that
users see. Examples of front end coding languages are HTML, CSS, Javascript,
etc.
• Back End Development It is also called server-side programming. The back
end developers take care of the things that happen behind the scenes. Some
back-end programming languages include Python, Java, Ruby, etc.

29

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

• Full-stack development This type of development takes care of both the client-
side (front-end) and server-side (back-end) portions of developing a web
application.

Types of Developers
• Web Developer A web developer takes web designs from clients or design teams and
transforms it into a website by writing code lines. They use different languages to achieve
this, like Python or HTML.
• Desktop Developer Programmers writing code for applications running natively on
operating systems like Windows, macOS, and Linux are called desktop developers. These
applications don’t need an internet connection to work.
• Mobile Developer They are software developers who specialize in mobile technology. They
build applications for Android, iOS, and other mobile platforms. They choose the language
for coding according to their chosen medium (Android – Java, iOS – Objective C, etc.).

Final Words

Computer programming is not solely restricted to the "geeks" or movie hackers in


today's technological age. It has evolved into a respectable profession that has a
unique history. While this lesson tracing computer programming's roots may not
guarantee a full stack developer's job, every aspiring computer programmer must
be aware of how it all started!

30

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Food for Thought

Can you guess the top real-world applications of C++?

Answer: C++ sits close to the hardware, can manipulate the resources
efficiently, and is fast. Hence, it finds its uses in Games, GUI based
applications (Adobe systems, Win Amp Media Player, etc.), Database
software (MySQL), operating systems (Apple OS, windows), Browsers,
among other applications.

31

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

References

1. Contributor A, A History of Computer Programming Languages, Reviewed


on August 26, 2020,
https://cs.brown.edu/~adf/programming_languages.html.
2. Contributor B, Computer Programming History, Reviewed on August 26,
2020, Computer Hope,
https://www.computerhope.com/history/programming.htm.
3. Contributor C, Computer Programming, Reviewed on August 26, 2020,
Computer Programming – History of Computer Programming,
https://www.softschools.com/inventions/history/computer_programming_his
tory/369/
4. Contributor D, A History of Computer Programming Languages, Reviewed
on August 26, 2020, Online College Plan,
https://www.onlinecollegeplan.com/computer-programming-languages/.

32

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Chapter 3

Computer Basics


Learning The Key Terms Associated With Computers And Their Functioning

The world of computers is fascinating and revolutionary. Computers are

machines that simplify human work. But to operate these machines, it is

essential to be comfortable with the basics of computers. Here is a brief

Although initial computers were created to simplify calculations, as we all know,


modern computers can do a lot more than that, from screening movies, playing
your favourite games, to sending space crafts up in space.

Computers operate on instructions and binary codes. The data fed to the computing
device is processed and then reflected or shown on the output device. The
foundation of computing (or computers) is based on three necessary steps:

Input: The term input means putting something 'in.' Input in computers refers to
the command or signal fed to the device. Several devices are used to provide Input
(data) to the computer, known as 'Input Devices.'

33

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

(Source Image: Pixabay)

Process: The execution of the data inserted by the user is known as the 'process' in
computing. The processing takes place within the CPU (Central Processing Unit)
and is invisible to the human eye.

(Source Image: Pixabay)

34

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Output: Once the data is processed by the 'Processor' it is converted to meaningful


information or results called 'Output.' It is the opposite of Input and is usually
displayed on an output device, such as the monitor or computer screen.

Parts Of A Computer System

A computer system compromises of several parts or units designated to perform a


predefined set of operations. Let's briefly touch upon what these parts are.

(Image Source: Pixabay)

35

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

• Input Unit: As discussed above, the input unit comprises input devices like
keyboards and mouse. These devices are used to feed instructions to the
computer.
• Output Unit: It consists of devices like the monitor, printer, and visual
display unit. These devices provide information to the user after the raw data
has been processed.
• Control Unit: The control unit is responsible for all the functions of the
computer. It keeps all devices or parts of the computer in interaction with
one another.
• Arithmetic Logic Unit: The Arithmetic Logic Unit (ALU) is known as the
computer's brain and regulates all arithmetic and logical operations.
• Memory: Yet another vital component of the computer system is memory.
Memory stores all data entered by the user until the data gets processed to
information. There are two types of memory– primary
memory and secondary memory. Primary memory is the main memory of
the computer and is a part of the CPU. Secondary memory refers to
additional memory that is used to store files permanently or in a portable
format. Some secondary memory devices are CDs, DVDs, floppy disks, hard
drives, and pen drives.
• Central Processing Unit: CPU (Central Processing Unit), also known as the
central or main processor, is a crucial element of the computer system. It
comprises the Control Unit (CU), the Arithmetic Logic Unit (ALU), and the
memory. CPUs are responsible for prompt computer actions – be it the quick
delivery of complex calculations or animations, video and audio merging,
etc.

36

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Types Of Devices

The devices that keep the computer system working are of different types and have
different functions. The following is a list of some primary input and output
devices along with their descriptions:

INPUT DEVICES
MOUSE The input device mouse is plugged into the CPU and functions as a
direction indicator and operator that enables a user to select or deselect a
file. It comes with two buttons (left and right) and a scroll wheel.
KEYBOARD Designed in-line with the olden typewriters, this input device comes with
buttons (or keys) that contain all alphabetical letters, numbers from 0 to 9,
and an array of other special characters and operations.
MICROPHONE The microphone is not an essential input device, but it can capture audio
signals by converting sound waves into electrical signals.
SCANNER Scanners or image scanners can scan hard copies of documents or
photographs and convert them to soft copies stored and viewed on a
computer.
WEBCAM Webcams came into the picture much later and can be used for clicking
pictures, video conferencing, or recording.
OUTPUT DEVICES

MONITOR The monitor is one of the computer system's main components and the best
example of an output device. It is a television-like device with a screen.
Although monitors these days come in LED or LCD variants, the first
monitors were the boxed-shaped CRT ones. Monitors display every action
performed by the user on the computer and show the final output after
processing the CPU data.
PRINTER The peripheral device Printer is used to print documents or pictures stored
on the computer unto paper, thus converting soft copies of files into hard

37

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

copies. Printers are of different types, such as inkjet printer, laser printer,
thermal printer, and today we have 3D printers. Printers could only perform
black and white printing when they first came out, but over time, they have
evolved into these powerful machines (such as 3D printers) that we know
of today.
SPEAKER Speakers come with computers and work as loudspeakers that convert
audio signals into audible loud sounds that can be heard by the human ear.

Difference Between Input And Output Devices:

Input Device Output Device


Input devices take data from users. Output devices display the processed data to
users.
Input devices operate when operated upon by Output devices are independent of the direct
the user. application by the user.
These are slightly more complicated devices. These are comparatively less complicated in
structure.
Examples – Keyboard, Mouse, etc. Examples – Monitor, Printer, etc.

Important Definitions And Classifications

• Hardware & Software: Computer hardware comprises all tangible


components of a computing device, categorized as internal or external
components. Internal hardware (such as motherboard, CPU, RAM, hard
drive, optical drive, USB ports, etc.) stores the operating system (OS).
External components of hardware (monitors, printers, speakers, headphones

38

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

and earphones, etc.) provide instructions to the software and display its
execution results.
• Types of Software:
1. System software includes software designed to manage the computer,
like the operating system, DOS (disk operating system), or file
management utility. System software acts as a platform for developers
to design applications. Examples of system software are OS, antivirus
programs, disk formatting software, etc.
2. Application software: They are also called end-user programs and lie
on top of the system software. They help the user perform tasks on the
system like surfing the web, graphic designing, playing games, doing
calculations, etc.
3. Utility software: They are used for analyzing and maintaining the
computer. They focus on the working of the OS and enable smooth
functioning of the system. Sometimes, they are included in the OS
package. Some examples are file manager, antivirus, disk
compression tool, etc.
4. Free distribution software: This software is available to the user
without any cost. They can simply download the free distribution
software from the internet and start using it. Unlike open-source
software, users cannot modify, share, or study free distribution
software. Some examples are: Adobe PDF, yahoo messenger, Google
Talk
5. Commercial software: Commercial or shareware software are
available for download free of cost. However, they come with an

39

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

inbuilt time limit. (30 days to 2 months). After the time-limit, the
software gets deactivated automatically, and the user needs to buy it to
continue using it. Examples are Adobe acrobat, PHP Debugger,
Winzip, Getright, etc.
• Motherboard: A motherboard or mainboard is a circuit board that facilitates
the power distribution and communication between the CPU, RAM, and
other computer peripherals. It acts as the backbone for connectivity within
the computer and contains important computing components such as the
CPU, RAM, power supply, sound card, graphics card, etc.
• RAM & ROM: RAM and ROM are two integral parts of a computer
system's primary memory. RAM refers to the Random Access Memory, and
ROM stands for Read-Only Memory.

Random Access Memory (RAM) is also known as Read Write Memory. It is


a volatile memory, and hence, data is stored only as long as the computer is
switched on; once the power is turned off, all stored data gets erased. It
stores all programs and data required by the CPU for the execution of a
program.
Read-Only Memory (ROM) is the permanent, non-volatile memory of the
computer system. It retains all information or programs needed for the
computer's smooth operation.
• Operating System (OS): The interface between the computer and its user is
known as the Operating System (OS). It is a software responsible for
performing basic tasks like process management, controlling peripheral

40

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

devices, file and memory management, etc. Windows Operating System,


macOS, and Linux Operating System are the popular OS in the market.
• 32 Bits V/S 64 Bits: There are two types of processors in the computing
world – 32-bit and 64-bit. They decide the amount of memory the processor
can access from the CPU. While the 32-bit operating system can access only
4 GB RAM, the 64-bit system can handle any memory greater than 4 GB.
The defining factor affecting the speed of performing tasks is the number of
cores. 64-bit processors are usually available in dual, quad, and octa-core
configuration. Hence, they are suitable for running programs that require
many calculations.

Difference Between Hardware And Software

Examples of hardware and software devices

Image Source: guidancecorner.com

41

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Hardware Software
These are physical devices connected to the These are programming codes installed in the
computer system. computer's hard drive.
These are tangible devices. These are intangible and exist in the form of
codes.
Hardware is integral to a computer's smooth The software adds to the basic functioning of a
functioning. computer system.
Examples - Monitor, mouse, and keyboard. Examples - operating systems, internet
browsers, or applications are examples of
software.

Final Words

Ever since the invention of computers in the 1880s, there has been an exponential
growth and evolution of computers. From desktops to laptops, CRT to LED
monitors, computers are becoming compact, affordable, power-packed, and
efficient. Understanding computers' basic concepts are the first step towards diving
into the vast ocean of technological advancements.

42

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Food For Thought

Across Down

3. House of chipsets 1. A computer providing one or more


services
5. Storage Device Codeveloped By Philips &
Sony 2. Portable Computer

6. Input device closely connected with the 4. Output devices producing sound
world of music

7. Physically tangible parts of a computer

43

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Some Interesting Facts About Computers

Do You Know?:
➢ Did you know that the world's first mouse was wooden? Doug Engelbart
invented it in around 1964.
➢ One striking similarity between tech giants HP, Microsoft, and Apple is
that they were all started in a garage.
➢ Computers weren't always the way they are now. The earliest computers
were created in the 1940s and occupied an entire room and lots of
electricity.
➢ Don't they tell us gadgets are addictive? We do blink only seven times
every minute while using a computer; the number is 20 otherwise.
➢ When first invented, keywords had letters arranged in alphabetical order.
The 'Q' 'W' 'E' 'R' 'T' 'Y' system came in later because human typing speed
was faster than the computer's ability to process data.

44

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

References

1. Wikipedia, the free encyclopedia. Input (Computer Science), from


https://en.wikipedia.org/wiki/Input_(computer_science)
2. Tutorialspoint. Basics of Computer – Introduction, from
https://www.tutorialspoint.com/basics_of_computers/basics_of_computers_i
ntroduction.htm#:~:text=Control%20unit%2C%20arithmetic%20logic%20u
nit,hardware%20components%20of%20a%20computer.
3. GCF Global. Computer Basics – What is a Computer? from
https://edu.gcfglobal.org/en/computerbasics/what-is-a-computer/1/
4. Wikipedia, the free encyclopedia. Process (Computing), from
https://en.wikipedia.org/wiki/Process_(computing)
5. Difference Between.net. Difference Between Primary Memory and
Secondary Memory, from
http://www.differencebetween.net/technology/difference-between-primary-
memory-and-secondary-
memory/#:~:text=Computer%20memory%20is%20categorized%20into,stor
e%20data%20or%20information%20permanently.
6. Study.com. Central Processing Unit (CPU): Parts, Definition & Function,
from https://study.com/academy/lesson/central-processing-unit-cpu-parts-
definition-function.html
7. GeeksforGeeks. Difference Between Input and Output Devices, from
https://www.geeksforgeeks.org/difference-between-input-and-output-
devices/

45

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

8. TechTarget| SearchNetworking. Computer Hardware, from


https://searchnetworking.techtarget.com/definition/hardware
9. GeeksforGeeks. Random Access Memory (RAM) and Read-Only Memory
(ROM), from https://www.geeksforgeeks.org/random-access-memory-ram-
and-read-only-memory-rom/
10. GoTechUG. 100 Computer Facts I Learned Online, from
https://gotechug.com/interesting-facts-about-computers-you-didnt-know/

46

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Chapter 4

History of Problem Solving


Human evolution finds problem-solving at its core. Problem-solving traces back its roots into
the earlier twentieth-century Germany, with the work of Gestaltists. It is the seed for all the
latest inventions, cultural growth and marks the foundation of market-based economies. This
chapter deals with the history of problem-solving, which has been one of the foundations for
the evolution of humankind.

What is Problem Solving?

Problem-solving is a technique in which a person defines a problem, determines its


cause, identifies, prioritizes, and selects alternatives as solutions and implements
them. The problem-solving process includes:

The Problem Solving Process


Image Source: www.asq.org

47

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

1. Defining the problem

It means focussing on the problem, and not merely its symptoms. Flowcharts and
cause and effect diagrams can help in diagnosing the root causes of the problem.

2. Generating alternative solutions

It is the next stage of problem-solving, which involves considering multiple


alternatives for solving the problem. It improves the value of the solution because
it takes into account numerous options.

3. Evaluating and selecting an alternative

There are a series of considerations that skilled problem solvers take into account
to choose the best alternative. These include:

• The alternative must solve the problem efficiently without creating other
unanticipated issues.
• The alternative must be acceptable to all the concerned individuals.
• The likelihood of the implementation must be high.
• The alternative must fit in the organizational constraints.
4. Implementing and following up on the proposed solution

Involving other members in the implementation process can minimize resistance


against the proposed solution.

What Are the Types of Problem Solving?

The plan of action which a problem-solver uses to find an optimum solution is


called the problem-solving strategy. According to an old saying, the most common

48

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

problem-solving approach is, "Keep trying until you succeed." It forms the basis of
the trial and error problem-solving method. Other problem-solving types are
summed up in the table below.

Method Description Example

If your mobile phone starts


It includes trying different malfunctioning, you restart
Trial and
methods until there is a solution the phone, turn off the Wi-Fi,
error
to the problem. turn off the Bluetooth to
determine the cause.

Instruction manual to clear


It includes a step-by-step guide/
Algorithm the printer off the jammed
formula for finding the solution.
paper.

It includes mental shortcuts for


solving problems. It is often Breaking a problem into steps
Heuristic referred to as a common and working backward to
problem-solving framework. find the solution.

49

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Why is Problem Solving Important?

From an individual to billion-dollar conglomerates, problem-solving has


applications in almost every place or industry you can think of! Here are some
general uses of problem-solving:

• It fixes broken things: Business and personal environments include


processes, things, interactions, and activities that may not work in the
desired way. Some things get worn out over some time. Problem-solving is a
mechanism that helps to identify these things and determines how to fix
them.
• It addresses risks: Problem-solving helps in identifying and averting future
risks. It guides the action that individuals can take in the present to prevent
the likelihood of a similar future event.
• It improves performance: Through the complex web of human
relationships, one action often impacts several others. These relationships
allow people to solve complex problems. Hence, each person needs to
improve their performance to match the improvement of others.
• It helps in seizing opportunities: We need not just respond to and fix
today's environment through problem-solving. It also helps to innovate,
create new things, and change our setting to become more desirable.

Influential Figures in Problem Solving

• The Father of Modern Problem-Solving: George Polya

Dr. Geroge Polya (1887-1985) was an esteemed professor and distinguished


mathematician at Stanford University. He has many contributions to his

50

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

name in the calculus of variations, number theory, probability theory, and


functions theory. He also authored classic works like Mathematical
Discovery, How to Solve It, and Mathematical and Plausible Reasoning.
These works encouraged and helped students in becoming independent and
thoughtful problem solvers.

Other Figures in Problem Solving

• We can trace the origins of problem-solving can be traced back to Gestaltists


in Germany. Karl Duncker (1903-1940) was a Gestalt psychologist and a
visiting professor at Clark University, Worcester. He coined the term
functional fixedness to describe difficulties in problem-solving and visual
perception, which arises because one element of the problem involves a
fixed-function that the problem-solver has to change to find the correct
solution the accurate perception.
• Another important personality in problem-solving is Alan Schoenfeld, who
started as a research mathematician. Born in 1947, he earned his Ph.D. from
Stanford University in 1973. Posterity credits him with transforming
mathematics education because he shifted it from a focussed field on
specific concepts into using them to tackle complex and non-routine
problems effectively.

51

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Relation of Computation with Problem Solving

• What is Computation?

Any calculation, including non-arithmetical and arithmetical steps and


following a well-defined model (algorithm), is computation. Computers are
the electronic or mechanical devices that carry out computations.

• How Computation Revolutionized Problem Solving

Computation can solve mathematical problems, interpret data, and build


engineering systems. It is finding relevance with students who want to
become skilled at using tools and create them. We live in a world that is
significantly influenced by computing.

• Theory of Computation

The Theory of Computation, also known as Automata theory, refers to the


theoretical branch of Mathematics and Computer Science that includes
applying the logic of computation to simple machines, also called automata.
Through automata, scientists can understand the way machines solve
problems and compute functions.

Computational Problems and Computational Thinking

• What Are Computational Problems?

In simple words, computational problems are those problems that can be


solved by a computer. It can also include a question which the computer
might answer. An example of a computational problem:

"For a given number ‘n’ (a positive integer), find its nontrivial prime factor."

52

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

We can view a computational problem as a collection of instances (infinite)


where every model can have an empty set of solutions. The integers n
represent instances in the above situation, and prime numbers p (nontrivial
prime factors) represent the solutions.

What is Computational Thinking?

Computational thinking uses computer science techniques extensively and is a


relatively new method for problem-solving. It curates existing knowledge and
critical thinking ability to solve complex technological problems.

• The Three A's of Computational Thinking The three A iterative process


of computational thinking includes the following three stages:

1. Abstraction: It includes problem formulation;


2. Automation: It involves the solution expression;
3. Analyses: It includes two steps: solution execution and evaluation

53

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

The 3A Process of Computational Thinking

Image Source: www.researchgate.net

• Connection of Computational Thinking with The Four Cs

Learning in the 21st century includes the following 4Cs:

• Creativity
• Collaboration
• Communication
• Critical Thinking
The fifth element in the four Cs can be the algorithmic and logical ability of
problem-solving – computational thinking, as computational thinking finds

54

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

relevance beyond mathematics, science, and technology in language arts and


social science.

Two Historical Problem-Solving Tools

• Abacus
The abacus is believed to have originated about 5,000 years ago in Babylon.
Thus, it predates the invention of the alphabet and glass making! Before the
counting machines were invented, people made marks in the muds, used
their fingers, or used stones for counting. The earliest abaci included shallow
trays that were filled with dust (a layer of fine sand).

A modern replica of a Roman hand abacus from 1st century CE

Image Source: history-computer.com

• Mechanical and Analogue Computers

The first analog computer can be traced back to 1873, a particular purpose
machine made by William Thomson. He was also called Lord Kelvin. The

55

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

mechanical computer used consistent physical phenomena (mechanical,


hydraulic, or electrical) to solve a problem. It reads the instructions
contained in the setup, and cannot read instructions like a digital computer.

Food For Thought

Here's an interesting story about a math problem, which was solved by


renowned mathematician and physicist John von Neumann:

Q. There are two trains 150 miles apart and are travelling toward each other
along the same track. Assuming that the first train's speed is 60 miles per
hour, the second train rushes along at 90 miles per hour. There is a fly that is
hovering just above the nose of the first train. It flies from the first train to the
second train, turns around immediately, it then flies back to the first train, and
turns around again. It repeats the same activity and keeps on flying back and
forth between the two trains. It does it until both the trains collide. Assuming
that the fly's speed is 120 miles per hour, how far will it travel? [Source:
Two Trains and a Fly]

A. What's your first thought after reading this problem? Do you feel like
approaching this problem with the infinite series method? Well, you're not
alone! That's what Mr. Neumann thought. However, there's a simple solution
to this:

Concentrate on the trains, and forget about the fly for a second. The speed of
the first train is at 60 miles/hour, and the second train is going 90 miles/hour,

56

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

so they are approaching each other at (60 + 90) miles/hour = 150 miles/hour.
So, we have the rate at which the trains are closing in on each other and the
distance between them (150 miles), now it has merely become a speed-
distance-time problem, and we can calculate the time as:

Distance = Rate * Time


Time = Distance / Rate
= (150 miles) / (150 miles/hour)
= 1 hour.

Now, we know that the time spent by the fly will be equal to the time spent by
trains travelling. It was given that the fly moves at 120 miles/hour; therefore,
in the one hour the trains take to collide, the fly will go 120 miles.

From this question, we learn how it's crucial to approach a problem the right
way. Had we used a mathematic approach for this, it would have taken us
much longer to solve it.

Final Words

The key to solving a problem is reaching a goal state and overcoming the
circumstances that stand in the way. The most powerful problem-solving machine
is the human mind, which is solving problems every second! Problem-solving is
the epicentre of the computational world, which forms the foundation of our
advancement as a whole, and pushes us to generate innovation-driven ideas that
can be implemented for solving some of the most crucial real-world problems.

57

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

References

1. Wayne Stottler, What is problem-solving, and why is it important. kepner-


tregoe.com. Retrieved August 27, 2020, from https://www.kepner-
tregoe.com/blog/what-is-problem-solving-and-why-is-it-important/
2. What is problem-solving? Asq.org. Retrieved August 27, 2020, from
https://asq.org/quality-resources/problem-solving
3. Problem Solving. Lumenlearning.com. Retrieved August 27, 2020, from
https://courses.lumenlearning.com/wsu-sandbox/chapter/problem-
solving/
4. Ulrich Boser, March 6, 2017, I learned how to do math with the ancient
abacus. vox.com. Retrieved August 28, 2020, from
https://www.vox.com/first-person/2017/3/6/14766970/abacus-math-
learning-lessons
5. Anna Lamprou, Alexander Repenning, July 2018, Teaching how to teach
computational thinking. researchgate.net. Retrieved August 28, 2020, from
https://www.researchgate.net/figure/The-AAA-model-a-three-stage-process-
describing-Computational-Thinking_fig2_325901317
6. The Classic "Two Trains and a Fly" problem. Primepuzzle.Com. Retrieved

August 28, 2020, from


http://www.primepuzzle.com/leeslightest/howfar.html
7. Arithmetic - 'Bee flying between two trains' problem .... Stackexchange.com.
Retrieved August 28,2020, from
https://math.stackexchange.com/questions/1805312/bee-flying-between-
two-trains-problem

58

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Chapter 5

Steps To Solve A Problem


Solving any problem is always fun if you adopt the right approach. Computers
can help in solving problems fast, but you need to program them accordingly. In
this chapter, we discuss some interesting methods, tools, and tips to solve
computational problems.

Introduction

One of the principal applications of a computer is to solve problems that are not
humanly practical. The reason is that the computer can perform permutations and
combinations better and faster than humans. A computer also takes a logical
approach when solving a problem. This chapter discusses how to solve a
computational problem in the right and efficient way.

59

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Image source: Pixabay

What Is A Computational Problem?

By the theoretical definition, a computational problem is one that requires


computers to solve. There are different types of computational problems such as,

a) Decision Problem – The answer is either a Yes or a No.


b) Search Problem – The solution will be in the form of arbitrary strings.
c) Counting Problem – It gives the number of solutions for a given search
problem.
d) Optimization Problem – It looks for the best possible solution among the
various available ones to a search problem.

60

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Computational Thinking: The Cornerstone Of Solving Computational


Problems

Solving a computational problem requires a specific approach. In computer


parlance, it is known as Computational Thinking. One needs to understand the
problem before attempting to solve it. Computational Thinking allows one to do
so. Here's more about Computational Thinking.

What Is Computational Thinking?

Computational Thinking is a logical approach to solve a problem. It involves


understanding the problem and developing possible solutions. Finally, the
presentation of the solution is also critical. It should be in a way that both
computers and humans can understand.

The Four Cornerstones Of Computational Thinking

As Computational Thinking involves taking a logical approach, one should follow


specific techniques to arrive at the right solution. We can break down the process
into the four cornerstones of Computational Thinking.

1. Decomposition – Breaking Down Complex Problems


Initially, a problem might look impossible to solve, whereas breaking it
down into small, manageable parts helps understand the situation better.

2. Recognizing Patterns – Finding Similarities in Problems


At times, the hints for finding a solution to the problem lie within the
problem itself. One should recognize it as it would make it easier to solve

61

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

the problem. Going through solutions to other similar problems can be


helpful.

3. Abstraction – Focusing on Key Elements


All problems consist of relevant and irrelevant details. One should focus on
the relevant elements alone and ignore unnecessary information. It helps to
concentrate better and arrive at the most logical conclusion.

4. Algorithms – Step By Step Rules For Solving Problems


Since solving problems requires adopting a logical approach, embarking
upon the issue in a logical sequence of well-defined steps becomes an
integral part of the process. It paves an easy path to the solution.

Each of these four cornerstones has its significance. One should apply all these
four techniques to arrive at the best possible solution.

How Computational Thinking Is Related To Solving Computational Problems


And Programming

People often confuse Computational Thinking with computer programming. While


programming instructs a computer what to do and how to go about it,
Computational Thinking empowers one to think about what to instruct the
computer.

A simple example should be planning a vacation. When you plan a vacation to an


exotic location, you break down the task into various smaller tasks like,

a) Deciding on the mode of the main transport

62

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

b) Booking your tickets in advance

c) Planning where to stay and eat

d) Checking out the local modes of transport

e) Research the places you wish to see

f) Consult your friends who have visited the place before

As you break down the task into smaller activities, it becomes easy for you to plan
the vacation.

The Five-Step Method For Solving Computational Problems

Adopting the five-step method to solve computational problems is the best way to
approach any problem on hand.

1. Identify: Identification of the Problem


Identifying the problem is one of the essential aspects of solving any problem.
Unless you know what to solve, you will not be able to move further. As you
identify the problem, you begin to understand what is necessary to solve it.

2. Model: Mathematical Modeling for the Problem


Understanding the problem helps you to create a mathematical model for the
problem. It involves making a set of assumptions that will help you give a
recognizable form to the issue and understand how to solve it. A

63

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

mathematical model for a problem allows you to formulate a computational


method.

3. Method: Making a Computational Method For Solving Your Model


Computers can perform tasks infinitely faster than humans do. However, the
computer, as such, cannot think. Therefore, it is your responsibility to
program the computer to develop an ideal solution to the problem. Making a
computational method can help the computer know what to solve and how to
do it.

4. Implement: Implementation of Your Computational Methods in a Computer


Now that you have made a computational model and programmed the
computer, it should be ready to solve it. However, you need to run the
program and provide the computer's necessary inputs to start working.
Implementation of your computational methods is a crucial step in finding the
solution to any problem.

5. Assess: Checking and Reassessing for Disparities


Generally, a computer will arrive at the correct solution based on the
programming and the input provided. However, one should check the answers
for various types of data. It helps in improving the computer's accuracy and
enhances the quality of the solution.

64

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Helpful Tools In Solving Problems

Problem-solving is a challenging task. Just as one needs specific methods to solve


a problem, one also requires tools to help solve it. As mentioned earlier, computers
need programs to solve any problem. A computer program is nothing but a series
of steps that a computer should follow to solve its problem. The computer
performs each step in a specific sequence. The following tools help the computer
perform these steps and arrive at the perfect solution.

Image source: Pickpic.com

• Pseudocode
Pseudocode is similar to the flowchart, as it expresses a computational process.
In simple terms, pseudocode is a code that a machine cannot understand. On

65

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

the other hand, humans can understand it. It allows you to bring in the element
of creativity when solving problems.

• Flowcharts
A flowchart is the step-by-step dissection of the problem. It helps you to write
down the computing process. A flowchart consists of different kinds of steps
like,

a) Instruction Steps – They represent the actions you need to perform. When
preparing a flowchart, you write the instruction steps inside a rectangle.

b) Decision Steps – Such steps can have more than one answer. Depending on
the answer, you proceed in a specific direction. You write decision steps
inside a diamond-shaped figure.

c) Sequential Steps – Depending on the outcome of the decision steps, you


move in a specific direction. Sequential steps show the path.

• Mathematical Models
Mathematical models help to understand the problem and its characteristics. It
enables you to reason and arrives at a logical conclusion. Creating a
mathematical model is crucial for solving computational problems. The
advantage is that mathematically described models are compatible with
computers using mathematical techniques like graph theories, algebra, etc. A

66

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

mathematical model helps the computer arrive at a scientifically acceptable


solution.

• Operators
Just as you have different mathematical signs to indicate the steps to solve
mathematical problems, computers have operators to verify elements' validity.
These operators do not express numbers but True/False values. The computer
uses the True/False values to proceed ahead sequentially. The direction of the
problem-solving process changes with every True/False value.

• Logic
Solving any problem is one aspect. However, one should also be able to
explain the procedure used to arrive at the respective solution. It is done by
applying logic, which is critical because the answer should be the same every
time you input the same data. As a corollary, a different input should provide a
different yet consistent solution to the problem.

Tips For Solving A Problem

Those were the theoretical aspects which are the fundamental steps that one should
use when solving problems. Now, here are specific tips that can help you approach
any situation and go about solving it with confidence and effectiveness, thereby
improving the chances of finding a logical solution.

• Begin With A Plan


Initially, even a simple problem can sometimes look intimidating. Having an
appropriate plan should make it easy to solve it. Planning well reduces the

67

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

chances of errors popping up during the execution process. It is beneficial to


begin with, more than one plan to solve a problem. In that way, you will be
ready with a Plan B if Plan A fails.

• Restate The Problem In Your Own Words


Understanding the problem is the first significant step towards resolving it. The
best way to understand any problem is to read it repeatedly and restate it in
your own words. Summarizing a problem in your terms helps you adopt
multiple strategies to approach it.

• Divide The Problem As Necessary


If a problem looks too complicated, it is good to break it down into multiple
modules. Now you will have separate, smaller problems to tackle. Solving
these divided problems can help you arrive faster at the solution to the main
problem.

• Begin With Known Information


As you break down your problem into smaller ones, you will find that you
know the solutions to those problems. It is better, to begin with solving such
known parts of the problem. It reduces the severity of the problem and gives
you hints to find solutions that you were not initially aware of when you started
your approach. Looking for the information you know also helps to eliminate
several steps that are otherwise unnecessary. It narrows down your options,
thereby providing a better chance of arriving at the proper solution.

68

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

• Reduce The Complexity Of The Problem


Eliminate any unnecessary and unrelated parts from the problem to reduce
complexity. It is easily possible if you perform the two steps mentioned above
correctly. You will eventually find that you have viable options that can easily
lead to the correct solution.

• Find Analogies

Every problem would have some precedents. Logical thinking of the problem
can help you find analogies, thereby making it easy for you to understand the
issue on hand.

• Experiment And Have Fun

As you dissect the problem and find analogies, you may find the need for
experimentation. While some analogies might lead you to the right solution,
some could be confusing. Unless you experiment, you will never know.
Experimentation also improves your perception skills.

• Try Not To Get Frustrated


When you experiment with a possible solution in mind, it doesn't need to work
every time. Therefore, one should not get frustrated if an experiment fails. The
more you keep trying, the better are your chances of arriving at the correct
solution.

69

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Final Words

Problem-solving is fun, provided you adopt the right approach. Every problem has
a logical solution. If you plan well and approach the problem step by step, it should
be easy to find a solution. You can use the fundamental techniques, tools, and tips
discussed in this chapter to formulate a practical problem-solving approach. It will
enhance your chances of arriving at the right solution every time you embark on a
problem.

Food For Thought

We shall look at a simple example where we determine whether a number is a


prime number or not.
By applying computational thinking, we do the following:

a) Identify the problem: We have to find out whether a given number is a


prime number. A prime number is one that is divisible only by one and
itself. Therefore, it should not be divisible by any of the other numbers.
b) Break down the problem: Start dividing the number by all integers
starting from 2. If you get a whole number in any of the divisions except
for one and the number itself, it is not a prime number.

Given below is a small program in C language that would help the computer
to understand and solve the problem. As an example, the number 29 has
been used. You can try out with any number and arrive at the solution
accordingly.

70

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

71

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

References

1. BBC, Introduction to Computational thinking,


https://www.bbc.co.uk/bitesize/guides/zp92mp3/revision/1

2. Kristen Thorson, Getting Smart, Early Learning Strategies for


Developing Computational Thinking Skills, March 18, 2018,
https://www.gettingsmart.com/2018/03/early-learning-strategies-for-
developing-computational-thinking-skills/

3. Joseph L. Zachary, cs.utah.edu, Solving Computational Problems,


https://www.cs.utah.edu/~zachary/computing/lessons/uces-1/uces-
1/node1.html

4. mathcs.emory.edu, Computational Problem Solving,


http://www.mathcs.emory.edu/~fox/NewCCS/CompPS.html

5. Samson Ehigiator, The Fundamentals of Computational Problem Solving,


September 29, 2018, https://medium.com/@dasamdave/the-
fundamentals-of-computational-problem-solving-b6f2ae95b805

6. programiz.com, C Program to Check Whether a Number is Prime or Not,


https://www.programiz.com/c-programming/examples/prime-number

72

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Chapter 6

What Are Algorithms?


Digital systems are passive by themselves and require coded instructions for
delivering results. Today's digital era is driven by the mathematical model and
is backed by algorithms for providing the outcome, whether it is launching a
rocket or displaying movie recommendations.

Today's era is technology-driven, and mathematics and computers use a predefined


set of instructions, known as algorithms or pseudocodes, to perform specific
functions. The word algorithm is derived from the mathematician Mohammed ibn-
Musa al-Khwarizmi's name, who lived in Baghdad between 780 and 850 CE.
Developing algorithms is a crucial requirement for software development.

73

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Introduction To Algorithms

An algorithm consists of a set of rules and steps that should be followed during
problem-solving. An algorithm is provided with some inputs for processing, which
gives out desired outputs after following a set of predefined steps. In programming,
a concise description of such executable instructions is known as pseudocode. An
optimal algorithm is one that executes in minimum time using minimum resources
and possesses the following characteristics.
• Input: Zero or more inputs supplied externally
• Output: One or more structured, desired outcomes
• Correctness: Each step in an algorithm should produce relevant results
• Definiteness: Each step should be well-defined and unambiguous
• Finiteness: The algorithm should execute in a well-defined number of steps

The general flow of control in algorithms


Image source: GeeksforGeeks

74

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Search And Sort Algorithms

Searching and sorting are two essential functions that play an indispensable role in
many programs.

Search algorithms involve looking up databases for the requested items. They
search for an item x in an array of elements A[0….n] by cross-checking items in
position 0 to n, one by one. The two main search algorithms are.

• Linear search that searches for items by cross-checking each


element in the array
• Binary search that looks for items from a sorted array

Sort algorithms sort elements in an array based on the developer's preference.


Commonly used sorting algorithms are discussed below.

• Bubble sort: The first two elements are compared and swapped for
ordering. This interchanging is iterated until complete sorting.
• Insertion sort: The second element is compared, and items are
interchanged, followed by the third element, and so on.
• Merge sort: It is based on the 'divide and conquer' algorithm, and is
discussed in the subsequent section.
• Selection sort: It maintains two sub-arrays and repeatedly finds the
smallest element in an unsorted array and sorts it.

75

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Types Of Algorithms

Each algorithm differs from another in the flow of control, repetition, speed, and
efficiency. They can be broadly classified into six, as described below.

1. Recursive Algorithm
A Recursive algorithm takes smaller inputs and repeats its execution until a
solution is found. These algorithms are mainly used for the Tower of Hanoi and
DFG graph-related solution searches. These algorithms are computation-
intensive and need more memory than iterative algorithms but are more
straightforward and represent a natural way of thinking.
An example code of the recursive algorithm is given below.

factorial (number)
if number is 0:
return 1
otherwise
return (number * factorial (number-1) )

2. Greedy Algorithm
The Greedy algorithm is an intuitive algorithm that finds the optimal solution for
each step as it considers an overall optimal solution for the entire problem. Such
optimization problem-solving algorithms are commonly used in Huffman
encoding and also in Dijkstra's algorithm. The Greedy algorithm works by
taking into account all data associated with a specific problem and then sets

76

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

rules for each element added in each step while solving the problem. The
algorithm generally comprises of five components:

▪ The candidate set from where solutions will be found


▪ Selection function that helps to find the best candidate
▪ Feasibility function which decides if a candidate can be used for a
solution
▪ The objective function that assigns value to a possible solution
▪ Solution function which notifies if an answer has been found
3. Divide And Conquer Algorithm
In the Divide and Conquer algorithm, the entire problem is divided into smaller
chunks and executed separately. The final result will be a combination of all the
outputs. These algorithms find applications in merge sort, Strassen's matrix
multiplication, quick-sort, and binary search.

An illustration of the flow of the 'Divide and Conquer' algorithm


Image source:medium.com/@james_aka_yale

77

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

4. Brute Force Algorithm


Brute Force is the most straightforward algorithm that iterates all possible
solutions to find more than one answer. The algorithm does not have any pre-
processing phase, and also comparisons can be made in any order. However,
since the algorithm processes all possible ways, the time and space complexities
are higher and not always optimal.

The below example describes a sequential search using a brute force algorithm.

Sequential Search(A[0.. n], X)


A[n] <- X
i <- 0
while A[i] not equal to X
i <- i+1
if i < n
return i
else
return -1

5. Dynamic Programming Algorithm


Dynamic programming algorithms aim to use past data and reduce complexity
and make the code more efficient and optimal. It avoids repetition of work by
using partial results and uses the concept of memorization. It memorizes the
results of some states so that it can be used to solve some other sub-problems.

78

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Overlapping sub-problems and optimal substructure can be solved using


Dynamic Programming. Some famous Dynamic Programming algorithms
include TeX, Bellman-Ford, UNIX diff, travelling salesman problem, and
WASP. The following pseudocode explains how the Fibonacci sequence is
implemented using a Dynamic Programming algorithm.

Fibonacci(N)=0 (N=0)
Fibonacci(N)=0 (N=1)
Fibonacci(N)=Fibonacci(N-1)+Fibonacci(N-2) (N>1)

6. Backtracking Algorithm
Backtracking is a systematic approach in which the code solves problems
recursively by building solutions incrementally and deleting solutions that do
not satisfy the given constraints. In other words, the algorithm tries to solve a
sub-problem, and if it fails, then the final solution will be truncated, and the
algorithm starts again to find another solution.
N-Queens and Sudoku are typical applications of the Backtracking algorithm.
The N-Queen problem is based on the fact that there are N queens on the
chessboard, and once arranged, none of the queens attack the other. The
pseudocode for the N-Queens problem solution using a backtracking algorithm
is given below.

CheckValid()
If queen at left of current column, return false
If queen at upper-left diagonal of current column, return false

79

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

If queen at lower-left diagonal of current column, return false


Return true
Solve()
If columns full, return true
For each row in board
If CheckValid()
Set queen at (X, column)
If Solve()=true
Return true
Else
Remove queen from (X, column)
Return false

A solution for N-queens problem using the backtracking algorithm


Image source: Code Pumpkin

80

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Algorithm Development Process

Generally, any algorithm's developmental phase consists of five steps, as discussed


below.

• Obtaining Problem Description


In this step, an ambiguous and incomplete description is created, which may
even contain internal contradictions. It is the weakest phase, where
developers will have to collaborate and think hard to understand the
problem's requirements adequately.

• Problem Analysis
This step involves connecting the endpoints. The developers have data,
rules, and interconnection between data. They need to come up with facts
and also include changes.

• Developing a High-level Algorithm


In this step, a solution plan will be developed but will not include the entire
part. Suppose if the problem is to send a birthday card to Mark, the analysis
will find that client needs to buy a card from the store for a birthday. Then
the algorithm will be as given.
Step-1: Go to greeting card seller
Step-2: Select a card
Step-3: Purchase the card
Step-4: Send the card to Mark

81

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

• Refinement
Also called step-wise refinement, developers will include even minor details
if required in this step. These detailed descriptions will be added only after
high-level algorithm development.

• Review
The final review ensures that the problem has been solved, and the solutions
are the most optimal solutions possible. Moreover, simplification, if
possible, will be done in this step.

Run-time Analysis Of Algorithm

Analysis of an algorithm gives insights into the complexities of the code, time, and
space. It also helps programmers to discover the characteristics of the algorithm
and its applications. The efficiency of algorithms is measured in terms of the
following notations.
• Omega (Ω) Notation
Omega notation represents a formal way of expressing the lower bound of
an algorithm's execution time and is a measure of base-case time
complexity. For instance, it takes 10 seconds to sort 1000 numbers; in
omega notation, these numbers cannot be sorted in less than 10 seconds.
• Theta (Θ) Notation
Theta notation defines asymptotic behaviour and represents lower and upper
bounds and represents an average running time of the algorithm. To
exemplify, if one algorithm takes 7 seconds to sort 1000 numbers and

82

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

another algorithm takes 11 seconds, then it takes an average of 9 seconds to


sort algorithm in the theta notation.
• Big-o (O) Notation
Big-o notation represents the upper limit of the algorithm's running time and
measures worst-case time complexity. For example, if an algorithm can sort
1000 numbers in 50 seconds, then in big-o notation, the numbers can be
sorted in 50 seconds and not more.

83

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Final Words

It is evident that algorithms form the foundation for flawless operation of digital
systems, and the most impressive services are built on top of well-defined
algorithms. Which algorithm to use for each project is up to the developer. New
forms of dynamic algorithms have been increasing to cope with the changing
digital world, such as that for ANN Artificial Neural Network and other data
analytic techniques.

Food For Thought

To better understand algorithms, students can write an algorithm to reverse a


word-string. For example, if 'computer' is the given string, then the output
should be 'retupmoc.'
Solution:
Step-1: Start
Step-2: Take two variables i and j
Step-3: Do length (string)-1, to assign j at last position
Step-4: Do string [0], to assign i on first character.
Step-5: string [i] is exchanged with string[j]
Step-6: Increment i by 1
Step-7: Decrement j by 1
Step-8: if (i>j) then go to Step-3
Step-9: Stop

84

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

References

1. GeeksforGeeks. (2019). Introduction to Algorithms.


https://www.geeksforgeeks.org. Retrieved August 28, 2020, from
https://www.geeksforgeeks.org/introduction-to-algorithms/
2. Educba. (2020). Types of Algorithms. https://www.educba.com. Retrieved
August 28, 2020, from https://www.educba.com/types-of-algorithms/
3. CS. (2020). Recursive Algorithm. https://www.cs.odu.edu. Retrieved August
28, 2020, from
https://www.cs.odu.edu/~toida/nerzic/content/recursive_alg/rec_alg.html
4. Moore, Karleigh. (2020). Greedy Algorithms. https://brilliant.org. Retrieved
August 28, 2020, from https://brilliant.org/wiki/greedy-
algorithm/#:~:text=A%20greedy%20algorithm%20is%20a,to%20solve%20th
e%20entire%20problem
5. Tutorialspoint. (2020). Data Structures - Divide and Conquer.
https://www.tutorialspoint.com/. Retrieved August 28, 2020, from
https://www.tutorialspoint.com/data_structures_algorithms/divide_and_c
onquer.htm
6. IGM. (2017). Brute Force algorithm. https://www-igm.univ-mlv.fr/.
Retrieved August 28, 2020, from https://www-igm.univ-
mlv.fr/~lecroq/string/node3.html
7. Garg, Prateek. (2020). Introduction to Dynamic Programming 1.
https://www.hackerearth.com/. Retrieved August 28, 2020, from

85

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

https://www.hackerearth.com/practice/algorithms/dynamic-
programming/introduction-to-dynamic-programming-1/tutorial/
8. GeeksforGeeks. (2020). Backtracking Algorithms.
https://www.geeksforgeeks.org. Retrieved August 28, 2020, from
https://www.geeksforgeeks.org/backtracking-algorithms/
9. Edwards, Stephen. (2012). Problem Solving and Algorithms.
http://sofia.cs.vt.edu/. Retrieved August 28, 2020, from
http://sofia.cs.vt.edu/cs1114-ebooklet/chapter4.html
10.Obosi, Philip. (2020). A Gentle Introduction to Algorithms and Data
Structures. https://scotch.io/. Retrieved August 28, 2020, from
https://scotch.io/courses/the-ultimate-guide-to-javascript-algorithms/a-
gentle-introduction-to-algorithms-and-data-structures
11.Zaveri, Meet. (2018). An intro to Algorithms: Searching and Sorting
algorithms. https://codeburst.io/. Retrieved August 28, 2020, from
https://codeburst.io/algorithms-i-searching-and-sorting-algorithms-
56497dbaef20
12.Panchal, Sumeet. (2019). What is Runtime Analysis of Algorithms.
https://medium.com/. Retrieved August 28, 2020, from
https://medium.com/@sumeetpanchal.21/what-is-runtime-analysis-of-
algorithms-cf321bd65636

86

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Chapter 7

Flow Charts


Algorithms and programming languages work hand in hand to execute
programs in digital systems. But it is vital to make such instructions
documentable and understandable among non-technical staff too. A flowchart
plays a crucial role in achieving it.

A flowchart, also called 'Process Flow Diagram,' is a step-by-step illustration of a


sequential process. These charts are used in industries worldwide for a simplified
representation of instructions. The initial usage of flowchart dates back to late 1921
when industrial engineers Frank and Lillian Gilbreth introduced the term 'flow
process chart' to the American Society of Mechanical Engineers (ASME).

A flowchart is cross-functional as the chart is divided into horizontal and vertical


parts to describe the flow of control in the chart. The basic structure of a flowchart
represents abstract nodes, contents, and additional information. A range of drawing
software that can be used online or offline is available today. They have high
capabilities and features and can even automatically construct sophisticated
flowcharts depending upon the input given. Such software can create charts from
descriptive language or drag and drop options. It is up to developers and users to
decide which applications to use depending upon the requirements and reports that
should be generated.

87

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

(Image Source: Pexels.com)

Introduction To Flowcharts

Flowcharts are a graphical representation of algorithms, and the process of


developing a flowchart from an algorithm is known as flowcharting. Developers
use these charts as a problem-solving tool. A chart contains various shapes
connected logically to represent the flow of control throughout the algorithm.
Flowcharts describe certain aspects of a program and are sometimes complemented
by other types of diagrams. Process maps, process flowchart, functional flowchart,
and process flow diagrams are alternative names for flowcharts. Flowcharts are
also associated with UML (Unified Modeling Language) diagrams and data flow
diagrams (DFD). Flowcharts use two main types of boxes, namely, a rectangular

88

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

box (or activity box), which represents a processing step, and a diamond box,
which means decisions.

Flowcharts are used for representing computer programs, and modern diagrams
such as UML and Drakon charts are all extensions of flowcharts. There are mainly
four types of flowcharts, as described below.

• Program flowcharts: These flowcharts describe the controls within a


program or a system.

• Document flowcharts: They are flowcharts that describe the controls


over a document in a system.

• System flowcharts: These flowcharts show controls at the resource or


physical level.

• Data flowcharts: Data flowcharts are those that represent control


over a data flow in a system.

Flowcharts can provide a visualization of how the code is executed and users
navigate a program. The execution of the code inside a program can also be
represented using flowcharts. Like any other process, the designing of flowcharts
takes place through a series of steps, as shown below.

89

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

1. Define the algorithm to be visually represented and write a title for the
flowchart.

2. Decide the inputs and output for the process and identify the limitations.

3. Brainstorm the activities that will take place and take note of it.

4. Arrange the entire process logically in a proper sequence.

5. After the process has been sequenced, draw shapes, and connect each step
without compromising the flow.

6. Review and modify the flowchart to ensure that the flowchart's logic and
relevance have not been compromised.

A sample flowchart that calculates the sum of two numbers


Image source: it.iitb.ac.in

90

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Shapes Of Flowchart

The following table illustrates the symbols and their associated usage in
flowcharts.
Name Symbol Function
Denotes the starting or ending of
Start or End an algorithm and contains the
word Start or End
Represents a single process or
Action or Process entire sub-process within an
extensive process
Denotes a printed report or
Document document
Denotes different decisions
Decision emerging from various points
Represents the input given by
Input or Output the user or the result generated
by the system
An indication that the flow
continues where a matching
Connector symbol has been placed
anywhere else in the flowchart
Indicates the sequence of
Flowline instructions and the flow of
control
Represents a delay during the
Delay process
An indication that one or more
Merge sub-sets merge into one step

91

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

The above-represented symbols are basic flowchart shapes. In addition to them,


there are ANSI/ ISO defined symbols that can be used for higher-level
flowcharting. They include symbols for representations such as database,
annotation or comment, on-page or off-page connector, and multiple document
pages.

Branches, Conditions, And Decisions

In a flowchart, branching represents that the process splits based on two or more
conditions, and the control of the program will continue based on user preference.
A diamond-shaped decision box takes the user preference or changes the flow of
control based on previous results. The three main decision statements are discussed
below.
• 'If' statement
The 'If' statement is a widely used conditional statement that redirects
the flow of control in one path if the condition is 'true' and halts or skips
some steps if it is not valid.

• 'If… else' statement


The 'If… else' statement is a modification of the 'If' statement in which a
pre-defined set of instructions is executed if the condition is 'true.'
Otherwise, another set of instructions will be performed.

92

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

If Else If Statement
Image source: javatpoint.com

• Switch statement
A switch statement or case statement is a multi-way decision-making
statement. If value equals one of the case conditions, a particular block of
instructions will be executed among various other conditions. If no
conditions are 'true,' a default set of statements will be performed.

93

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Switch statement in javascript


Image source: tutorialcodeplay.com

94

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Drawing Flowcharts Using MS Visio

Microsoft Visio is a powerful tool to create interactive flowcharts and modify them
at later stages if required. Visio also allows developers to store data and compare
or evaluate information before further additions to existing algorithms. It is
recommended to follow the below steps to create a flowchart in MS Visio.

1. Open the MS Visio application.

2. Select the 'New Flowchart' option, and choose a shape from the list of
forms in the sidebar to create a flowchart.

3. Drag and drop the required shape from the sidebar. Whenever a user
hovers over any shape, the name and details of the shape will be
shown. The start and the end of the process can be represented with
the terminator symbol.

4. Double click on the shape and write the name for each process and
continue until all shapes have been assigned some names. Use the
connector tool for connecting all the functions in the flowchart.

5. Finally, the flowchart can be saved or downloaded in a format


specified by the user.

95

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Drawing Flowcharts Using Different Tools

More tools, free, open-source, and paid, are available in the market for creating
flowcharts. Here's is a list of some of the most popular ones.

Open source and free tools

• Draw.io: Draw.io is a tool that can create flowcharts and works across all
sorts of platforms. The documents can be stored either on the system or
cloud storage.

• Gliffy: Gliffy is a web application that allows one to make flowcharts,


graphs, and more.

• Canva: This flowchart development application has provisions to engage


the audience by visualizing ideas. It also provides high-resolution graphs.

• Pencil: Pencil is a tool with many useful provisions, including linking the
flowcharts and graphs with different locations on the same document.

• PlantUML: PlantUML can work with plain-text languages. It provides


many features besides flowcharts like Gantt chart and packages for projects.
A choice of styles and colours are also available.

96

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Paid tools

• Lucidchart: Lucidchart allows you to create flowcharts and technical


diagrams of varying complexity. You can import information and work with
your live data.

• Edraw Max: With Edraw Max, one can work with readily available
templates and symbols. It also allows one to work with multiple file formats.

• SmartDraw: SmartDraw is another tool widely used by business


organizations to create and manage flowcharts. It also helps in creating
graphs and visuals for plans and strategies.

• Visme: Visme is a tool that allows handling many visual tools, infographics,
and graphs, besides flowcharts.

• yED Graph Editor: yED helps in creating flowcharts and high-quality


diagrams. The creation can be done manually or by using additional data
resources.

Applications

The purpose of the flowchart is to convey how the process works even to non-
technical staff. Such pictorial representation is useful in engineering, physical
sciences, computer programming, and even entertainment. The below descriptions
examine the applications of flowcharts.

97

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

• Planning a new project: Engineers and scientists can decide the flow of
process while designing a new project and assign tasks to their
workforce.

• Auditing the process: A process flow displays step-by-step instructions


of a process and allows developers to identify malfunctions and fix them
appropriately. It is done by auditing and reporting each issue while
analyzing the process.

• Managing workflows: Flowchart can represent process integration and


task orientation and help attain standardized output based on the process
defined.

• Program and Network Designing: Flowcharts help problem-solving


and troubleshooting for customers since it can visually represent the
flow of procedures.

• Process Engineering: Flowcharts also represents high-level process


flow in major plants and process industries without containing all minor
details.

• Data Management: Helps reduce the gap between clients and


developers using DFD (Data Flow Diagrams).

98

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

• Mapping Computer Algorithms: Specification and Description


Language (SDL) diagrams map real-time systems using symbols and
contain the system definitions, processes, and blocks.

• Integration with other programs: Flowcharts help in quickly


identifying the modules in a program that can be connected or integrated
with different codes to work together.

Final Words

The flowchart or process flow diagram plays a prominent role when developers
start working on their projects. It is also beneficial to identify malfunctions and
make non-technical staff understand the tasks they are supposed to do. Otherwise,
algorithms and programming languages will be complicated for non-technical
employees. Many newer forms of flowcharts have been developed from time to
time. However, the symbols and structure are still more or less the basic, globally
accepted ones. The advent of technology has resulted in various automatic
flowcharting applications that read the source code and develop detailed visual
representation.

99

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Food For Thought

Fill out the cross-word using the hints provided below the puzzle. All the answers
are related to flowcharts.

Across:
1. I am rectangular while designing a flowchart. What am I?
2. You use me whenever you want to represent a decision-making step.
4. You use me to communicate ideas, and I represent a problem-solving
process.
5. I join two different geometrical boxes with the flowcharts.
Down:
1. I represent data or information available in the flowchart.
3. I am elliptical, and all flowchart begins with me. What am I?

100

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

References

1. ASQ, LEARN ABOUT QUALITY, https://asq.org/quality-resources/flowchart

2. Lucid chart, What is a Flowchart, https://www.lucidchart.com/pages/what-


is-a-flowchart-tutorial#:~:text=UML)%20Activity%20Diagrams.-
,History,1930s%2C%20industrial%20engineer%20Allan%20H.

3. FTMS College, PROG0101 FUNDAMENTALS OF PROGRAMMING,


https://ftms.edu.my/v2/wp-content/uploads/2019/02/PROG0101_CH06.pdf

4. 4. Lucid chart, Flowchart Symbols and Notation,


https://www.lucidchart.com/pages/flowchart-symbols-meaning-explained

5. Launie Sorrels, How to Draw a Flowchart in Visio,


https://itstillworks.com/draw-flowchart-visio-4814522.html

6. Smart draw. (2020). What are the Different Types of Flowcharts,


https://www.smartdraw.com/flowchart/flowchart-types.htm

101

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Chapter 8

Pseudocode


Structured Language to Describe Algorithms
Do you want to know about an informal way of programming that does not need
any strict programming syntax or technology considerations? In this chapter,
we learn about pseudocode – a casual way to create a rough draft or program
outline..

Introduction to Pseudocode

A pseudocode is an informal representation of the actual code showing a computer


program's working or an algorithm in plain English words.

Why Pseudocode?

Any programming language's syntax can be confusing, especially in the initial


phases, when you are just beginning to think about what you want to achieve with
the next program. Pseudocode helps you pen down those brilliant ideas without
worrying about the syntax. There is no pre-defined syntax for pseudocode, and it is
effortless to read and write. Hence, even if you are working on various
programming languages, you can comfortably communicate the Pseudocode ideas
and concepts.

102

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

What is Pseudocode

Image Source: www.educative.io

Let's start with a simple example of pseudocode:

Suppose you want a program that prints even numbers from 0 to 99. The
pseudocode for the same program will look like this:

set i to 0
for each i from 0 to 99
if i is even
print i
end for loop

Note: Since there is no specific syntax for a Pseudocode, you might have a
different one in your mind.

Due to its simplistic nature, pseudocode may sound trivial to many users. They
simply need to convert the above code in simple English to the actual one. Below,
we give a translation of the pseudocode, as mentioned above in C++, Python, and
Java:

103

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

C++

#include <iostream>
using namespace std;
int main() {
// Printing even numbers from 0 to 99
for (int i = 1; i <= 99; i++) {
if (i % 2==0)
cout << i << endl;
}
}

Python

For i in range (1,100):


if(i % 2 == 0):
print("{0}".format(i))

Java

class HelloWorld {
public static void main( String args[] ) {
// Printing even numbers from 0 to 99
for (int i = 1; i <= 99; i++) {
if (i % 2 == 0)
System.out.println( i );
}
}
}

104

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Algorithm & Pseudo-code

The significant difference between pseudocode and an algorithm is that while


pseudocode is a way to write an algorithm, the latter defines the step-by-step
procedure for solving a problem.

Here are the significant differences between pseudocode and algorithm:

Pseudocode Algorithm
Pseudocode refers to an informal The algorithm refers to the step-by-step
way to write a program. One cannot procedure for solving a problem. The
classify it as a computer program process consists of a fixed set of
because it represents the program instructions, where each instruction
algorithm in a simplistic and natural gets executed in a finite amount of
language. Since you write it in time. A typical example of an
simple English language, there is no algorithm is the steps you take to log in
strict syntax of writing a Pseudocode to your Facebook account.
like other programming languages.

Programmers use several formats for You can express algorithms in simple
writing Pseudocodes, most of which and natural language, or by using
are inspired by language structures flowcharts.
like C, FORTRAN, etc.
Example of Pseudocode for Linear Example of Algorithm for linear
Search: search :

FUNCTION 1. Start from the leftmost


linearSearch(list, element of arr[] and

105

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

searchTerm): one by one compare x with


FOR index FROM 0 -> each element of arr[].
length(list):
IF list[index] == 2. If x matches with an
searchTerm THEN element, return the index.
RETURN index 3. If x doesn't match with
ENDIF any elements, return -1.
ENDLOOP
RETURN -1
END FUNCTION

How To Write Pseudocode

Given below are a few tips to write pseudocode:

1. First things first, arrange the sequence of tasks you want to complete through
the pseudocode.
2. Start writing the pseudocode by defining a statement that establishes the
primary goal.

Example of the main statement:

Users can check if a number is even or odd by using


this program.

3. You must indent the if-else, for and while loops in the pseudocode, if they are
indented in the program. While improving the readability for users, it will also
allow them to comprehend the mechanism of decision control and
implementation.

106

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

For Example:

if "1."
print response
"we are group 1."
if "2."
print response
"we are group 2."

4. It is crucial to follow standard naming conventions. It is human tendency to


follow the approach that we see. Since the programmer will follow the same
procedure as the pseudocode, keep the naming distinct and straightforward.
5. Some sentence casings that must be kept in mind are – a lower case for
variables, upper case for constants, and CamelCase for methods.
6. You must avoid making the pseudocode abstract. It must explain everything
that will happen in the actual program.
7. Standard programming structures must be kept in mind while writing
pseudocode. In other words, use 'if-then,' 'while,' 'cases,' 'for' the way you
would use them in programming.
8. It is prudent not to incorporate too much technical jargon in pseudocode since
it must be easy to understand for a layman. Hence you must not write the
pseudocode in a programmatic language completely.
9. After you finish writing the pseudocode, recheck all the sections to see if they
are complete and clear to understand.

107

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Branches, Conditions, And Decisions Using Pseudocode

The "structured" part in pseudocode refers to a notation used to represent the six
structured programming constructs. These are SEQUENCE, IF-THEN-ELSE, FOR,
WHILE, REPEAT-UNTIL, and CASE. You can embed any of these constructs inside
other constructs. They represent the flow of control or the logic of an algorithm.
Let's look at each one in detail:

1. SEQUENCE

Programmers can indicate sequential control by writing an action after the


other, with each step in-line with itself, and every step aligned with the same
indent. The order of performing the actions in the sequence (top to bottom) in
which they are written.

A non-computer example:

Brush teeth

Smile in mirror
Wash face
Comb hair
Another example of a sequence:

READ length of the rectangle


READ breadth of the rectangle
COMPUTE area as length times the breadth

108

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Some Common Action Keywords which you can use to indicate input, output,
or processing operations are:

• Input: GET, READ, OBTAIN,


• Output: SHOW, PRINT, DISPLAY
• Compute: DETERMINE, COMPUTE, CALCULATE
• Initialize: SET, INIT
• Add on: BUMP, INCREMENT
2. IF-THEN-ELSE
If you want to display a binary choice for a Boolean condition, you can use the
following keywords:

• IF
• THEN
• ELSE
• ENDIF
The general form of writing this expression is:

IF condition THEN

group 1

ELSE

group 2

ENDIF

109

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Note: The "Group 2" and ELSE keyword are optional. For true condition,
"group 1" gets executed, otherwise "group 2" is executed.

Example of IF-THEN-ELSE condition:

IF ScreenHours > MaxNormal THEN

Display takes a rest message.

ELSE

Display regular use message

ENDIF

3. FOR

This loop is a specialized construct for iterating a specific number of times,


often called a "counting" loop. Two keywords, FOR and ENDFOR, are used.
The general form is:

It is a specialized construct, also called the "counting" loop, and is used to


iterate a particular number of times. Its general form is:

FOR iteration limits

sequence

ENDFOR

It is prudent to use problem domain vocabulary in cases when loop bounds are
easy to infer.

110

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Example of a FOR structure:

FOR each day of the week (good)


FOR day = 1 to 7 (ok)

FOR each person in the list (good)


FOR personno = 1 to listsize (ok)

4. WHILE
The WHILE construct specifies a loop which contains a condition at the top.
WHILE will indicate the beginning of the loop, and ENDWHILE marks the
ending. The general form of the WHILE construct is:

WHILE condition

sequence

ENDWHILE

The program enters the loop only if the condition is true. It performs the
"sequence" for each iteration. In the end, it again evaluates the condition and
continues the loop until the condition is true.

A simple example of WHILE construct:

WHILE Population < Limit

Calculate Population as Population + Newborns -


Deaths

ENDWHILE

111

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

5. REPEAT-UNTIL

The REPEAT-UNTIL loop shares similarity with the WHILE loop except that
the condition test is done at the end of the loop, not at the start. It uses two
keywords: REPEAT and UNTIL. The general form of the REPEAT-UNTIL
loop is:

REPEAT

sequence

UNTIL condition

Since the condition is checked after the sequence's execution, the REPEAT-
UNTIL loop performs the series at least once. The loop keeps repeating till the
time condition remains false, and when it becomes true, it terminates.

6. CASE

The CASE construct represents a multiway branch based on mutually exclusive


conditions. It uses the following four keywords to indicate alternatives:

• CASE
• OF
• OTHERS
• ENDCASE

The general form of the CASE construct:

CASE expression OF

112

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

condition 1: series 1 condition 2: series 2


... condition n: series n
OTHERS:
default series

ENDCASE

The OTHERS clause is optional. While some programmers represent the


condition through numbers or characters, others use simple English statements
to specify the condition.

Example of the CASE construct:

CASE Title OFMr: Print "Mister"


Miss: Print "Miss"
Ms: Print "Mizz"Mrs: Print "Missus"Dr: Print "Doctor"

ENDCASE

7. NESTED CONSTRUCTS

You can also embed constructs within each other by using indenting in
pseudocode. The point worth noting here is that you must indent the nested
constructs from surrounding constructs.

Example of a NESTED CONSTRUCT:

SET total to zero


REPEAT

113

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

READ Temperature
IF Temperature > Freezing THEN
INCREMENT total
END IF

UNTIL Temperature < zero


Print total

The IF construct nests within the REPEAT construct in the given example.

114

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Food for Thought

Find the output of the following pseudocode

Integer i, j, k
Set k = 8
for(each i from 1 to 1)
for(each j from the value of i to 1)
print k+1
end for
end for
Ans: 9
Explanation:

The code uses a nested FOR loop. It declares i,j, and k variables, and the initial
value for k is 8.

1. i value is 1, the FOR loop checks i<=1, and it is true.

2. In the inner FOR loop, j value is 1, and the condition j<=1 is correct. Hence
it prints K+1.

3. Then it increments the j value by 1; hence j=2, the condition for inner FOR
loop (2<+1) becomes false.

4. The value of i increases by 1 in the next iteration. Hence the condition


(2<=1) becomes false.

5. The answer is 9.

115

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Final Words

In this chapter, you learned that pseudocode summarizes the program flow,
excluding the underlying details. It acts as a crucial tool for system designers who
want to make it easier for programmers to understand a software project's
requirements and align their codes accordingly. It is very critical to understand the
concept of pseudocodes before diving into writing programs using actual codes.

116

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

References

1. usejournal.com. How to write Pseudocode: A beginner's guide. Reviewed


on September 5, 2020
https://blog.usejournal.com/how-to-write-pseudocode-a-beginners-guide-
29956242698
2. geeksforgeeks.org. Difference between Algorithm, Pseudocode, and
Program. Reviewed on September 5, 2020
https://www.geeksforgeeks.org/difference-between-algorithm-
pseudocode-and-program/amp/
3. pediaa.com. Difference Between Algorithm and Pseudocode. Reviewed on
September 5, 2020
https://pediaa.com/difference-between-algorithm-and-pseudocode/amp/
4. calpoly.edu. PSEUDOCODE STANDARD. Reviewed on September 5, 2020
https://users.csc.calpoly.edu/~jdalbey/SWE/pdl_std.html
5. educative.io. What is Pseudocode? Reviewed on September 5, 2020
https://www.educative.io/edpresso/what-is-pseudocode

117

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Chapter 9

Binary, Hex Numbers, ASCII Code, And Conversions


Computers and electronics systems can't understand the syntax that we humans
use to converse with them. It is first converted into a form that they can
understand. And for that purpose, the use of various number systems and codes
across different digital environments came into existence. These number
systems, such as binary, hex, and many others, represent numbers using
multiple symbols that electronic machines understand.

Modern computers follow standardized number systems (also known as


numeral systems), mainly comprising four variations: binary, decimal,
hexadecimal, and octal. These are positional number systems where digits
represent values depending on their position in the number. In digital systems, all
characters typed or documented will be converted into numerals for processing.
Across varying platforms, digital systems perform conversions of number systems
for computability and efficient processing of data.

118

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

(Image Source: Pexels)

Standard number systems

The below table lists four standard number systems.

Number System Base Digits

Decimal 10 0,1,2,3,4,5,6,7,8,9

Binary 2 0,1

Octal 8 0,1,2,3,4,5,6,7

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

119

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Computer Units Of Measurement

Bits And Bytes

Computer systems are based on binary digits, and for understandability, these
binary digits are converted to a human-readable form. A bit is the smallest unit of
representation of data and holds a value of 0 or 1 at a time, which is
corresponding electrical values for off and on. A byte is a combination of 8 bits
used for the basic unit of information in storage and processing. To exemplify, a
representation for word B or comma or any number can be denoted as a byte.

Other Units Of Measurement

Bits and bytes are not able to hold massive data and process it. In addition to bits
and bytes, digit systems use the following units of measurements too.

Unit Equivalent
1 kilobyte (KB) 1,024 bytes
1 megabyte (MB) 1,048,576 bytes
1 gigabyte (GB) 1,073,741,824 bytes
1 terabyte (TB) 1,099,511,627,776 bytes
1 petabyte (PB) 1,125,899,906,842,624 bytes

Introduction To Binary, Hex, And ASCII Code

The following section briefly describes the number systems, ASCII code, and their
usage.

120

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

● Binary Numbers
Binary numbers are a way to express characters in digital systems. It follows
the base-2 numeral system, consisting of the two digits, 0 and 1. This number
system is preferred while designing a digital system due to the implementation
of binary numbers in logic circuits.

Each digit in the system is a bit, and a binary number can consist of many bits.
The below table shows the binary notation of numbers up to 10 in the decimal
number system.

Number Binary Number

1 1

2 10

3 11

4 100

5 101

6 110

7 111

8 1000

9 1001

10 1010

121

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

● Hexadecimal Numbers
Hex numbers, also known as hexadecimal numbers, follow a base-16
numerical system commonly used to represent long strings of binary
numbers. This system uses 16 digits. The below table represents decimal
numbers 0 to 15 in the hexadecimal notation.

Number Hexadecimal Notation

0 0

1 1

2 2

3 3

4 4

5 5

6 6

7 7

8 8

9 9

10 A

11 B

12 C

122

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

13 D

14 E

15 F

Hexadecimal notation of numbers from 256 to 512

Image source: TK Computer Service

● ASCII Code
ASCII or American Standard Code for Information Interchange is a globally
followed standard for computers and the internet to assign characters in
256 slots in an 8-bit code. Out of the 256 characters, only 128 characters
are standardized by ASCII, and the first 32 characters are control
characters.

123

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Since the ASCII code was developed as per American English, it does not
include some European language codes. However, it has lowercase,
uppercase, and special characters. ASCII code is the lowest common
denominator to represent textual information and is followed by most
systems globally.

The ASCII Table

Image source: https://ascii.cl/

124

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Bacon code, the predecessor of ASCII code, developed by Francis Bacon in 1626 using bilateral steganography.

Image source: medium.com@amangondaliua555

Conversions

The number systems' conversion is a vital process to ensure capability so that


data can be viewed across various platforms. Common number system
conversions are discussed below.

125

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

(Image Source: Pixabay)

● Binary To Hexadecimal Conversion


Binary to hexadecimal conversion initiates by dividing the binary digits into
groups consisting of four bits in each group starting from the rightmost
side. In the last group, blanks spaces will be assigned zeros on the left side
to make it a four-bit binary digit. After that, each group will be given its
corresponding hexadecimal number and written together to form a hex
number.

126

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

For instance, take the binary number 1000101001012. The binary digits will
be separated into four groups to convert it to hexadecimal, as shown here.

1000|1010|0101

Corresponding hexadecimal digits of the binary numbers will be

8|A|5

Therefore the final hexadecimal value will be

8A516

● Hexadecimal To Binary Conversion


Hexadecimal to binary conversion is simple, and one has to write the binary
equivalent of each hex digit initially. Each equivalent binary digit should be
a group of 4 bits, and zeros should be added at the least significant
position. And then concatenate the digits, and discard any zeros at the left
of the binary digits.

For instance, to convert 3AB216 to binary, the binary equivalent of each


digit will be

0011 | 1010 | 1011 | 0010

Therefore the final binary equivalent of 3AB216 will be 00111010101100102

● Binary To ASCII Code


A binary number must be first divided into groups of 8 digits or octets.
Further, each octet will be replaced with corresponding decimal codes,

127

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

which will then be replaced by corresponding ASCII value from the ASCII
table.

For example, for the binary number 0100000101000010010000112

will be separated into octets as:

01000001 01000010 01000011

On converting each octet into a decimal value, the resultant output will be

65 66 67

When the decimals are replaced by ASCII codes available from the table,
the final ASCII code will be

ABC

● Hexadecimal To ASCII Code


ASCII uses a one-byte word for character representation, and when
hexadecimal is provided, it splits the digits and makes it into pairs. The
blank spaces will be filled with zeros on the right-hand side. And then, ASCII
value of corresponding hexadecimal values will be found using the ASCII
lookup table for an equivalent character.

For example, to convert hexadecimal 52696368 into corresponding ASCII,


the algorithm initially splits the digits into pairs as

52 | 69 | 63 | 68

128

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Using the ASCII table for equivalent hex numbers, the final ASCII code will
be obtained as

Rich

● ASCII To Binary Number


This conversion initially gets the decimal for each character using the ASCII
table. The decimal value is then converted to corresponding binary digits,
and the process continues until the last character in the ASCII code has
been converted. The binary outputs after each iteration will be joined to
obtain the final binary number.

For instance, the conversion of the ASCII text Pla to the corresponding
binary code is:

01010000 01101100 01100001

● ASCII To Hexadecimal
First, an ASCII code will be taken of each character from the table and
converted to the equivalent decimal value. And then, the decimal value will
be converted to equivalent hexadecimal, and this process continues until
every ASCII code has been converted to hexadecimal.

For instance, to convert character A to hexadecimal, the decimal equivalent


will be retrieved from the ASCII table as

65

129

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Then the hexadecimal value will be found by dividing it by 16 and noting


the remainder. The answer is again divided, and the remainder is noted
again until the answer is 0. Then the remainders are arranged bottom up to
get the hexadecimal value, as follows,

65 = 16 x 4 + Remainder 1

4 = 16 x 0 + Remainder 4

Therefore, the hexadecimal equivalent of character A is

41

Final Words

Computers and digital systems use a base-2 number system. The number system
has been of utmost priority among IT experts and has been taught to engineers
and mathematicians since it forms the foundation for electronic devices. Newer
number systems could be developed in the future for quantum computing-based
systems. Still, traditional methods using binary, hexadecimal, and ASCII codes will
be the foundation, and newer systems will be based on them.

130

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Food For Thought

Researchers worldwide are developing a quantum computing-based


quantum bit, commonly known as a qubit. Qubits are analogous to bits in
the traditional computing structures. However, qubits can exist in
superposition and represent the spin of an atom in its actual state.
Moreover, qubits are two-state quantum systems, which can perform
standard basis measurement and quantum logic gates.
A 30-qubit quantum computer can operate at the power of a
conventional computer running at ten teraflops. Entanglement is another
qubit property that can allow qubits to represent a higher correlation,
which is impossible in traditional systems.

131

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

References

1. ab-cjnr. (2017). Computer Numbering System.

https://amudabadmus.wordpress.com. Retrieved August 26, 2020, from


https://amudabadmus.wordpress.com/2017/10/02/machine-numbering-system/

2. Byjus. (2020). Number System. https://byjus.com. Retrieved August 26, 2020,


from https://byjus.com/maths/number-system/

3. Byjus. (2020). Binary Number System. https://byjus.com. Retrieved August 26,


2020, from https://byjus.com/maths/binary-number-system/

4. Electronics Tutorials. (2019). Hexadecimal Numbers. https://www.electronics-


tutorials.ws. Retrieved August 26, 2020, from https://www.electronics-
tutorials.ws/binary/bin_3.html

5. Thakur, Dinesh. (2020). What is ASCII Code?. https://ecomputernotes.com.


Retrieved August 26, 2020, from
https://ecomputernotes.com/fundamental/number-system/ascii-code

6. Electrical4U. (2020). Binary to Hexadecimal and Hex Binary Conversion.


https://www.electrical4u.com. Retrieved August 26, 2020, from
https://www.electrical4u.com/binary-to-hexadecimal-and-hex-to-binary-
conversion/#:~:text=Binary%20to%20Hexadecimal%20Conversion&text=To%20co
nvert%20a%20binary%20number,in%20the%20left%20most%20side.

132

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

7. Brennan, Eugene. (2020). How to Convert Hex to Binary and Binary to


Hexadecimal. https://owlcation.com. Retrieved August 26, 2020, from
https://owlcation.com/stem/How-to-Convert-Hex-to-Binary-and-Binary-to-
Hexadecimal

8. C Programming. (2018). Binary to text (ASCII). https://www.c-programming.


Retrieved August 26, 2020, from https://www.c-programming-simple-
steps.com/binary-to-text.html

9. Elprocus. (2020). Hexa to ASCII & ASCII to Hexa Conversion with Example.
https://www.elprocus.com. Retrieved August 26, 2020, from
https://www.elprocus.com/hexa-to-ascii-and-ascii-to-hexa-conversion-with-
example/

10. Rapid Tables. (2020). Text to Binary Converter. https://www.rapidtables.com.


Retrieved August 26, 2020, from
https://www.rapidtables.com/convert/number/ascii-to-binary.html

11. Rapid Tables. (2020). ASCII Text to Hex Code Converter.


https://www.rapidtables.com. Retrieved August 26, 2020, from
https://www.rapidtables.com/convert/number/ascii-to-hex.html

133

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Chapter 10

Introduction To Programming


Computers and other electronic systems are used for different purposes at
home and office. Engineers use it to design, develop, and implement software
or design buildings. At home, it can be used for browsing the internet or
educational purposes. The base of the computer is the programs that instruct
the digital systems.

The computer's hardware alone is not capable of performing even a single action.
Any hardware must be supported by coded instruction that guides the system.
Programs, also collectively called software, contains a set of instructions that a
computer follows. Such instruction blocks are developed by software developers
using various languages, which hide the back-end from casual users. The users can
browse the software using the GUI (Graphical User Interface). Common examples
of computer software are Microsoft Word, Zoom application, and Norton anti-
virus. There have been thousands of languages developed to aid developers and
system administrators from FORTRAN to the Python programming languages.
Some languages were designed for scientific research purposes, whereas some
were intended for application development, and so on.

134

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Introduction To Programming

Programming involves analyzing the environment, designing algorithms, profiling


resource requirements of the algorithm, and finally, using a standardized
language for implementation of the algorithm as programs, also called coding.
These programs are mainly written in human-understandable languages, and an
interpreter converts them into binary code for executing the program at the
system level. The first computer program was developed by Ada Lovelace back in
1843, which calculated a sequence of Bernoulli numbers to be used for Charles
Babbage's Analytical Engine.

Initial computer programs were written in machine language, which was coded
using binary numbers. Later on, assembly language was used for programming,
which specified instructions in text format such as ADD, SUB, etc. Around 1957,
high-level programming languages that simplified the complexity of coding were
introduced. FORTRAN was the earliest high-level language used for development
in addition to LISP and COBOL.

A program will always have some inputs which will be processed to produce a
predefined type of output. Today's modern high-level languages are supposed to be
readable by professionals to analyze and debug the source code. In addition to
readability, computer programs also possess the following features.

• Efficiency In Performance: Programs are always supposed to use minimal


system resources and the least time without compromising the quality of
output

135

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

• Robustness: Any software should be able to work using conditional


statements in case of errors. Errors could be user error, corrupted data,
memory error, or operating system issues.

• Maintainability: The program should be scalable and should be able to


accommodate new modifications in the future without compromising its
functionalities.

• Portability: Computer software should be able to work seamlessly across


different networks and operating systems when executed.

• Usability: The prime feature of a program should be to provide relevant


tools for its users to perform required tasks.

Since the usage of high-level programming languages is more and computers can
understand only binary language, many language-translating tools have been used
for conversions, as given below.

• Interpreters: Generally, translators analyze source code step by step before


execution. An interpreter pauses to report a fault in the source code during
conversion into machine code. Python is an example.

136

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

• Compilers: Compilers initially converts the whole program into binary and
then executes in one go. If errors are detected, then it will be flagged for
the users.

• Assemblers: Assemblers convert programming languages written in


assembly language into binary code and works similar to compilers.

Programming Development Cycle

Computer programs are developed in a step by step sequence, and each stage
requires expert knowledge from the team members of the project. The main six
steps in the programming development lifecycle are as follows.

• Planning: This step is performed by the development team and involves


information gathering, requirement analysis, and cost-benefit analysis.
• Analysis: The step involves defining the project's goals and is also known as
the problem-solving step. Project development begins only after systematic
analysis.
• Design: This step defines the architectural modules along with external and
third-party data flow interactions. Budget, time, and risk assessment must
all be considered in this stage. The design proposed should meet the client
requirements before proceeding to further steps.
• Implementation: During the execution of the project, developers and other
team members use tools such as editors, compilers, debuggers, and

137

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

interpreters to launch the application. Errors identified in this step are


rectified at the earliest.
• Testing And Integration: In this stage, the software's quality and
functionality will be assessed and modified if required. Testing will be
usually done in various phases according to internationally accepted
standard testing methodologies. If the application needs to be integrated
with other applications, such connections will be performed at this stage.
• Maintenance: As long as the product exists, proper functional care ensures
that the program will be resilient to cyberattacks and malfunctions and
does not compromise performance.

The Software Development Lifecycle

Image source: Husson University Online

138

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Input, Processing, Output

A program receives some input and performs logical calculations on them and
processes them before generating some output for the end-user. In addition to
the three stages, programs store the information temporarily for using it in the
succeeding steps.

Input is the information given to the program for processing, and it is fed into the
program using input statements in the code. The inputs given in human-
understandable form will be converted into binary code before processing.

The processing phase takes place in the CPU (Central Processing Unit) inside the
computer and involves converting raw data into informative data. During
processing, data will be temporarily stored for future reference or when the
software crashes. CPU uses CU (Control Unit), Memory, and ALU (Arithmetic And
Logic Unit) for data processing in different stages.

In the IPO (Input-Processing-Output) model, the output is the final stage in which
the results generated will be displayed for its users. The final product will be in
human-understandable form after conversion from binary code. Developers will
predefine the output type before executing the program. A feedback channel is
sometimes attached to some IPO model to rectify the error rate. Alternatively,

139

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

the output feedback can also be used as input at the next iteration of the
program.

IPO Model with a Feedback System

Image source: Velisa Africa

Converting Flowcharts And Pseudocode Into A Program

The conversion of algorithms to flowcharts is called flowcharting, and the


transformation of this pseudocode or flowcharts into computer language is called
coding. Computer programming can be done using three fundamental steps as
given below.

• Determining The Inputs And Data Flows: Input types can be derived from
flowcharts, and programmers can understand how data flows and how

140

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

control is transferred throughout the code from pseudocode. The number


of inputs given should be optimal, and the program should validate the
input type before processing to avoid malfunctions.

• Develop The Logic: Logical definition of code ensures relevant output with
the least utilization of resources. In other words, developing logic and
connecting separated blocks ensure the appropriate working of the code.

• Writing The Code: In this phase, developers decide on the programming


language required based on their skills and the working environment. It is
the longest stage in developing a project.

Final Words

Programs are the core of any computer system today. If there are no instructions,
hardware alone will be meaningless, unless it is a mechanical system. To address
varying environments, newer forms of programming languages have been
evolving. In addition to coding, developers also have to deal with gathering
information and analyzing it to design an efficient program. It is expected that, in
the future, newer programming languages will evolve that will enable even non-
technical professionals to code sophisticated projects in no time.

141

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Food For Thought

A computer virus called Brain was written by two brothers in Lahore,


Pakistan, in 1986. It was the first computer virus for MS-DOS. The
program attacked MS-DOS and infected the boot sector of the storage
media with the FAT (File Allocation Table) system. They created this
virus to stop customers who had been illegally distributing their software.
The virus displayed the details of both of them. It notified the victims that
the machine was attacked and advised them to call them for assistance.

The Hexcode Of The Brain Virus That Attacked Users Back In 1986
Image source: The Vintage News

142

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

References

[1] Pearson Highered, "Introduction to Computers and Programming."


https://www.pearsonhighered.com/assets/samplechapter/0/3/2/1/0321537114.
pdf (Accessed on: Sept. 9, 2020)

[2] "What Is the Software Development Life Cycle?" Husson University Online,
https://online.husson.edu/software-development-cycle/ (Accessed on: Sept. 9,
2020)

[3] "Input, Processing, Output & Feedback: Information System Components."


Study, https://study.com/academy/lesson/input-processing-output-feedback-
information-system-components.html (Accessed on: Sept. 9, 2020)

[4] Greg Perry, "Beginning Programming: Designing a Program."


https://www.informit.com/articles/article.aspx?p=25074&seqNum=4 (Accessed
on: Sept. 9, 2020)

[5] Alex Uhde, "A short history of computer viruses."


https://www.sentrian.com.au/blog/a-short-history-of-computer-
viruses#:~:text=The%20first%20computer%20virus%20for,designed%20as%20a%
20copy%20protection. (Accessed on: Sept. 9, 2020)

143

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Chapter 11

Basics of Shell Programming


Every operating system requires its users to interact with a shell indirectly.
Users who operate Ubuntu, Linux Mint, or other Linux variants interact with the
shell whenever they use the terminal. We discuss the basics of shell
programming in this chapter.

Introduction To Shell Programming

Before understanding the basics of shell scripting, one needs to get familiar with
the following terms related to the Operating System (OS) of a computer.

Kernel

The kernel is the computer program that forms the core of your computer's
operating system. It maintains complete control over every aspect of the system. In
a Linux system, it is responsible for managing the following resources:

• File management

144

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

• Process management
• I/O management
• Memory management
• Device management

Shell: The particular user program which offers the users interface for interacting
with the operating system is called a shell. It plays the role of converting the
human-readable commands from the user to kernel language. Hence, it can be
called a command language interpreter executing commands which it reads from
input devices like keyboards. It starts running as soon as the user logs in or opens
the terminal.

There are two classifications of shell:

• Command-Line Shell: Users can access this shell through a command-line


interface. Special programs like Command prompt in Windows OS or
Terminal in macOS allow the users to type human-readable commands.

• Graphical shell: Users can manipulate programs using a graphical user


interface (GUI) through this shell. It allows operations like opening and
closing, moving and resizing, and switching focus between various
windows.

145

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Terminal: Terminal can be defined as a program that runs a shell or simply the
interface, which gives you access to the command line.

What is Shell Scripting?

Shells are interactive, and they execute commands after accepting them as input
from the user. But, what to do if you wish to run a set of commands routinely? You
will have to type all the commands every time in the terminal.

However, to avoid this repetitive work, you can type the commands in a file and
then execute them in a shell as the shell can also take inputs from a file. These files
which contain commands as inputs in a file are known as shell programs or shell
scripts. The shell scripts have a similar syntax to other programming languages.
Hence, students who have experience writing programs in Python, C/C++, etc. find
it easy to start with shell programming. It comprises of the following elements –

• Shell Keywords: break, if, else, etc.


• Shell commands: pwd, echo, touch, etc.
• Functions
• Control flow: if-then-else, shell loops, etc.
Shell programming is necessary because:
• Programmers can avoid repetitive work.
• Shell scripting is the go-to choice for system admins to create
regular backups.
• It is used for system monitoring.

146

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Image Source: Geeksforgeeks

What Is Git Bash & Why Do You Need It?

‘Bash’ is a default shell on Linux operating system and macOS. Git Bash is a
package that installs Bash for you on a Windows operating system and some
commonly-used bash utilities. Git Bash is an application for Microsoft Windows
environments that provides an emulation layer for the Git command-line.

Git command-line provides you with an environment within which you can run
your shell commands.

How to install Git Bash?

Before you start writing and executing your first ‘bash’ script, you’ll need to install
Git bash. You can install Git to run your shell commands in three simple steps:

147

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

STEP-1: Visit the Git official site: https://git-scm.com/


STEP-2: Download the installer for Windows (you’re your preferred OS).
STEP-3: Execute the downloaded file.

How To Start Writing & Execute Your First ‘bash’ Script?

Every object in the Linux System gets handled as a file, including the input and
output processes. A shell script is a file that contains various ASCII text in it. In
order to create a shell script, we can use any text editor or a word processor. Here
is the step-by-step procedure to start writing your bash scripts:

Once you have downloaded and installed Git Bash, it will look like this:

Input/Output Techniques

Linux uses a file descriptor for identifying file objects. It refers to a non-negative
integer that specifies the open files uniquely. Hence, each process can have a

148

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

maximum of nine file descriptors open at a particular time. The first three
descriptors (0,1,2) are reserved for special purposes. These unique descriptors are
the ones responsible for handling the input and output from the script.

Start

STDIN

(Input)

STDERR
If ‘Error’
(Output)
Yes

No

STDOUT

(Output)

End

149

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

What is STDIN?

The STDIN file descriptor is used to reference standard inputs to the shell. Since
the keyboard is the standard input for the terminal interface, the shell will receive
all information on the STDIN file descriptor.

Why do you need STDIN?

STDIN is needed because it processes every character as the user types it. The
input redirect signal (<) commands the shell to replace the file referenced in the
redirection with the standard file descriptor. It will retrieve the file's data, just like
the user would have typed on the keyboard. If the programmer does not specify
any file on the command line, the bash command will accept STDIN input.

A Simple Code Example:

Here’s an example showing the use of cat command in which the shell enters data
from STDIN:

$ cat
this is the first test.
this is the first test.
this is the second test.
this is the second test.

The cat command will accept the input from STDIN if it sits on the command line
by itself. It will echo the displayed line as the user enters each line. Programmers
can also use the redirect symbol if they want other files to input the cat command.
For example:

150

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

$ cat < testfile


This is the first line.
This is the second line.
This is the third line.
$

Image Source: programskills.wordpress.com

151

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

What is STDOUT?

STDOUT stands for standard output. The STDOUT file descriptor is used for
referencing the standard output in the shell. The standard output for a terminal
interface is the terminal monitor. The shell outputs that include the programs and
scripts that the user runs in the shell get directed to the monitor.

Why do you need STDOUT?

STDOUT is needed to store the text output of a command in the stdout stream. The
STDOUT file descriptor receives outputs from most bash commands by default.
However, programmers can change redirect the output by using output redirection.

A Few Simple Code Example:

Consider the following example:

$ ls -l > test2
$ cat test2
total 20
-rw-rw-r-- 1 rich rich 53 2020-09-17 11:30 test
-rw-rw-r-- 1 rich rich 0 2020-09-17 11:32 test2
-rw-rw-r-- 1 rich rich 73 2020-09-17 11:23 testfile
$

The output redirection symbol will direct the output to the redirection file
designated by the shell, which otherwise would have gone to the monitor.
Programmers can also append data to the file. For example:

152

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

$ who >> test2


$ cat test2
total 20
-rw-rw-r-- 1 rich rich 53 2020-09-17 11:30 test
-rw-rw-r-- 1 rich rich 0 2020-09-17 11:32 test2
-rw-rw-r-- 1 rich rich 73 2020-09-17 11:23 testfilerich
pts/0 2020-09-17 15:34 (192.168.1.2)
$

The who command will generate an output that will get appended to the data
present in the test2 file. However, the users will run into a problem if they use
standard output redirection. For example:

$ ls -al badfile test3


ls: cannot access badfile: No such file or directory
$ cat test3
$

The shell will not redirect the error to the output redirection file if there is an error.
Although there was an output redirection file that the shell created, the error
message will appear on the monitor.

153

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

What is STDERR?

STDERR file descriptor is the one that the shell uses to handle error messages. It is
used to reference the standard error output. Whenever a command results in an
error, the corresponding error message is stored in this stream.

Why do you need STDERR?

All the error messages that the shell generates or the scripts that it runs get
redirected to the location defined by STDERR. Although the file descriptor values
for STDERR and STDOUT are different, STDERR will redirect all the error
messages to the same place as STDOUT. Hence, all error messages will go to the
monitor by default. As evident from the previous example, even if the user
redirects the STDOUT file descriptor, the STDERR will remain the same (the
monitor display).

What Are Variables And Variable Types?

Variables are used to store data that are referenced and manipulated during a
computer program's execution. A variable's type determines the kind of values the
variable can hold and the operations that can be performed on it.

Why do we need Variables?

Variables play a crucial role in every programming language. They act as a means
to reference a character or numeric value in a shell script. However, contrary to
formal programming languages, programmers do not need to declare the type of
variable in a shell script.

A Few Simple Examples:

154

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

There are two types of variables:

1. System Defined Variables :


They are variables that the Linux operating system creates and maintains. The
command “$ set” is used to display these variables. The following table shows
some system-defined variables:

System Defined Variables Meaning

BASH=/bin/bash Shell Name

BASH_VERSION=4.1.2(1) Bash Version

COLUMNS=80 No. of columns for the screen

HOME=/home/apjtech Home Directory of the User

LINES=25 No. of columns for the screen

LOGNAME=APJTECH Logging name

OSTYPE=Linux OS type

PATH=/usr/bin:/sbin:/bin:/usr/sbin Path Settings

PS1=[\u@\h \W]\$ Prompt Settings

PWD=/home/apjtech Current Working Directory

155

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

SHELL=/bin/bash Shell Name

The user name currently logged in to


USERNAME=apjtech
the system.

2. User-Defined Variables:
They are the variables that the users define. The shell script allows the
programmers to define their unique set of variables for storing data temporarily
and using it throughout the script. Thus, the user-defined variables make shell
script analogous to a computer program. They can be a text string of maximum:

• 20 Letters
• 20 Digits
• An underscore character
An important point to note is that these variables are case sensitive. For instance,
Var1 is different from var1.

Defining A Variable In A Programming Interface

Users can define a variable using the ‘=’ operator, followed by assigning a value to
a variable name. A variable name refers to a series of alphanumeric characters that
start with '_' or a letter. The shell script treats all variables as text strings unless the
user specifies them to be treated as numeric. For example:

$ myvar=greetings

156

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

$ mycount=1

In case the user needs to include spaces in-between values, they can surround it by
double-quotes. For example:

$ myvar1=” greetings all!”

Accessing a Variable

The shell script de-references a variable name by adding the prefix $. To print the
variable's value, use the 'echo' command. For example:

$ echo $myvar

greetings

If there is the ‘expr’ command, the script will treat the variable as a numeric value.
For example:

$ expr $mycount + 2

In case the variable is not followed by a space, surround it with spaces. For
example:

$ echo ${myvar}ss

greetingsss

Special characters, for example, ‘$’ retain their meaning in double-quotes. For
example:

157

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

$ myvar2=”$myvar everyone!”

$ echo $myvar2

greetings everyone!

Single quotes can be used if you want to treat special characters in their literal
sense. For example:

$ myvar3=’$myvar everyone!’

$ echo $myvar3

$myvar everyone!

158

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Final Words

Shell programming can perhaps be called as the first step into the world of
programming. It is crucial to get familiar with the basic terminology and shell
scripting before deciding to move on to more complex programming.

159

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Food for thought:

Can you list some disadvantages of shell programming?

Answer: The disadvantages of shell scripting include:

• It is prone to costly errors. Even a single mistake can change the command.

• Slow execution speed

Not suited for large or complex tasks, etc.

160

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

References

1. Geeksforgeeks. Introduction to Linux Shell and Shell Scripting, from


https://www.geeksforgeeks.org/introduction-linux-shell-shell-scripting/
2. Wisdom Jobs. Understanding Input And Output - Shell Scripting, from
https://www.wisdomjobs.com/e-university/shell-scripting-tutorial-
174/understanding-input-and-output-3162.html
3. Linux Techi. How to use variables in shell Scripting, from
https://www.linuxtechi.com/variables-in-shell-scripting/
4. Software Testing Help. Working With Unix Variables: Features Of Shell
Scripting, from https://www.softwaretestinghelp.com/unix-variables/

161

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Chapter 12

Operators in Shell Script


Various operators exist in Bash, which programmers can apply for performing
multiple operations using the Bash script. Fundamental knowledge of these
operators is essential for computer programming.

Variables are an integral part of every program. However, they only become
valuable when programmers can perform various operations with them. Hence,
many ‘operators’ are available in any programming and scripting languages
(including the Linux Shell) for programmers to perform the intended functions.

What Is An Operator?

An operator is fundamentally a symbol that connects different variables and


constants by specifying a relation between them. They constitute a set of building
blocks of the program syntax in a shell script and help produce results for problems
based on the considerations assigned.

162

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Why Do We Need Operators?

Programmers use operators to manipulate constants and variables in the shell


programs. They use them to perform operations from simple mathematical
functions like addition and subtraction to logical expressions and from relational
comparisons to performing various tests on a file.

A Simple Code Example Of Operators

#!/bin/bash

var1=$ (( 120 - 100 ))


echo $var1

var2= $ ((200+300))
echo $var2

var3=$(( 5*3 ))
echo $var3

var4= $((40/6))
echo $var4

163

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Types Of Operators

It must be clear by now that operators are an essential part of any programming
syntax, as programming itself will be non-existent without them. Various operators
are entrusted with their respective functions, such as arithmetic, relational,
Boolean, bitwise, and file testing. Before going into the detailed description, one
must first know about Unary and Binary operators. Unary operators are applied to
one argument, and programmers often use them to verify the file status (for
example, does a particular file exist?). Binary operators are applied to two
arguments, and programmers use them as part of arithmetic comparisons or strings
(for example, b is bigger than c).

A detailed description of each kind of operators with examples is given below.

Arithmetic Operators

Arithmetic Operators are used when there is a need to perform arithmetic functions
on variables and constants. The following table contains the list and a description
of the seven different Arithmetic Operators.

Operator Purpose

Addition Operator (+) The binary operation is used for adding two operands.

Subtraction Operator (-) The binary operation is used for subtracting one
operand from another.
Multiplication Operator (*) The binary operation is used for multiplying two
operands.

164

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Division Operator (/) The binary operation is used for dividing one operand
from another.

Modulus Operator (%) The binary operation is used for finding the remainder
of two operands.
Increment Operator (++) The unary operator is used for increasing the value of
an operand by one.
Decrement Operator (– –) The unary operator is used for decreasing the value of
an operand by one.

Why Are Arithmetic Operators Used?

One of the main reasons to write a computer program is to perform arithmetic


operations. For example, one may need to calculate the average value of a group of
numbers, a rectangle’s area, the factorial of an integer, etc. Hence, Arithmetic
Operators find applications with various computer programs.

Example:

read -p “Enter two numbers: ” x y

A=‘expr $x + $y’

S=$(($x - $y))

M=$(($x * $y))

D=$(($x / $y))

let “P = $x ** $y”

echo “$x + $y = $A”

165

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

echo “$x - $y = $S”

echo “$x * $y = $M”

echo “$x / $y = $D”

echo “$x ** $y = $P”

Output:

166

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Relational Operators

Relational Operators make various comparisons between two values and return a
‘true’ or ‘false’ as a result based on the comparisons. The following table contains
the list and description that shows the relevance of the six Relational Operators in
programming.

Operator Description

‘==’ Operator It compares two operands. It returns ‘true’ when they are
Equal to equal; otherwise, it will return ‘false.’
‘!=’ Operator It returns ‘true’ when the two operands are not equal;
Not Equal to otherwise, it will return ‘false.’
‘< 'Operator It returns ‘true’ when the first operand is less than the
Less than second operand; otherwise, it will return ‘false.’
‘<=’ Operator It returns ‘true’ when the first operand is less than or equal
Less than or equal to to the second operand; otherwise, it will return ‘false.’
‘>’ Operator It returns ‘true’ when the first operand is greater than the
Greater than second operand; otherwise, it will return ‘false.’
‘>=’ Operator It returns ‘true’ when the first operand is greater than or
Greater than or equal to equal to the second operand; otherwise, it will return
‘false.’

167

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Why Are Relational Operators Used?

Programmers use Relational Operators to define a relation between two operands.


They return either a ‘true’ or a ‘false’ result depending on the connection defined.

Example

read -p "Enter a : " a

read -p "Enter b : " b

if(( $a==$b ))

then

echo "$a==$b: a equal to b. "

else

echo "$a==$b: a not equal to b. "

fi

if(( $a!=$b ))

then

echo "$a!=$b: a not equal to b. "

else

echo "$a!=$b: a equal to b. "

fi

if(( $a<$b ))

168

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

then

echo "$a<$b: a is less than b. "

else

echo "$a<$b: a is not less than b. "

fi

if(( $a<=$b ))

then

echo "$a<=$b: a is less than or equal to b. "

else

echo "$a<=$b: a is not less than or equal to b. "

fi

if(( $a>$b ))

then

echo "$a>$b: a is greater than b. "

else

echo "$a>$b: a is not greater than b. "

fi

if(( $a>=$b ))

169

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

then

echo "$a>=$b: a is greater than or equal to b. "

else

echo "$a>=$b: a is not greater than or equal to b."

fi

Output:

170

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Boolean Operators

Boolean or logical operators take in Boolean values of two elements and return a
Boolean result. Boolean Operators are of three types, as mentioned in the table
below:

Operator Description

Logical AND (&&) Operator It is a binary operator and will return ‘true’ if
both the operands are ‘true’; otherwise, it will
return ‘false.’

Logical OR (||) Operator It is a binary operator, and it will return a


‘true’ if either of the operands is ‘true,’ or
when both the operands are ‘true,’ and it will
return a ‘false’ if none of them is ‘true.’

Not Equal to (!) Operator It is a unary operator and will return ‘true’ if
the operand is ‘false’ and ‘false’ if it is ‘true.’

Why Are Boolean Operators Used?

These operators form the basis to make decisions in a shell program and execute
different sets of instructions based on them. They are also called Logical Operators
and are used for flow control.

171

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Example:

read -p "Enter a : " a

read -p "Enter b : " b

if(($a == "true" & $b == "true" ))

then

echo "Both are true. "

else

echo "Both are not true. "

fi

if(($a == "true" || $b == "true" ))

then

echo "At least one of them is true. "

else

echo "None of them is true. "

fi

if(( ! $a == "true" ))

then

echo " "a" was initially false. "

172

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

else

echo " "a" was initially true. "

fi

Output:

173

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Bitwise Operators

Bitwise Operators help in applying mainly logical or relational operations on a


specific bit. In the following table are listed the six types of Bitwise Operators:

Operator Description

Bitwise OR (|) Operator It performs binary OR operation bit by bit on the


operands.

Bitwise XOR (^) Operator It performs binary XOR operation bit by bit on the
operands.

Bitwise AND (&) Operator It performs binary AND operation bit by bit on the
operands.

Bitwise complement (~) It performs binary NOT operation bit by bit on the
Operator operand.

Right Shift (>>) Operator It will shift the operand’s bits to the right by the
number of times specified by the right operand.

Left Shift (<<) Operator It will shift the operand’s bits to the left by the
number of times specified by the right operand.

174

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Why Are Bitwise Operators Used?

Programmers use Bitwise Operators for changing the individual bits in an operand.
They can perform bitwise operations on bit patterns using these operators.

Example:

read -p "Enter A : " a

read -p "Enter B : " b

bitwise OR=$(( a|b ))

echo "Bitwise OR of A and B $bitwise OR"

bitwise XOR=$(( a^b ))

echo "Bitwise XOR of A and B $bitwise XOR"

bitwise AND=$(( a&b ))

echo "Bitwise AND of A and B $bitwise AND"

bitwise Complement=$(( ~a ))

echo "Bitwise Compliment of A is $bitwise Complement"

right shift=$(( b>>1 ))

echo "Right Shift of B is $right shift"

left shift=$(( a<<1 ))

echo "Left Shift of A is $left shift"

175

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Output:

File Test Operators

File Test Operators are a set of operators specifically meant to evaluate various
statuses and properties of files. The following table lists some types of file test
operators:

Operator Description

-b Operator It will check whether a file is a special block file or


not. Block special files are ordinary files: an array
of bytes and the value last written there is the value
read at a given location.

-c Operator It will check whether a file is a special character


file or not. Character special files behave like serial
ports, pipes, etc. Immediate action is reading or

176

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

writing to them.

-d Operator It will check if the given directory exists or not.

-e Operator It will check whether the given file exists or not.

-r Operator It will check if the given file has ‘read’ access or


not.
-w Operator It will check if the given file has ‘write’ access or
not.
-x Operator It will check if the given file has ‘execute’ access or
not.
-s Operator It will check the size of the given file. If the size is
greater than 0, it will return ‘true’; otherwise,
‘false.’

Why Are File Test Operators Used?

Linux and Unix OS consider everything as a file. Hence, it becomes necessary for
programmers who use Bash files to perform some tests on the files. File Test
Operators help them test particular properties of a file.

Example:

read -p "Enter file name : " FileName

177

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

if [ -e $FileName ]

then

echo "File Exist"

else

echo "File does not exist"

fi

if [ -s $FileName ]

then

echo "The given file is not empty. "

else

echo "The given file is empty. "

fi

if [ -r $FileName ]

then

echo "The given file has read access. "

else

echo "The given file does not have read access. "

fi

178

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

if [ -w $FileName ]

then

echo "The given file has write access. "

else

echo "The given file does not have write access. "

fi

if [ -x $FileName ]

then

echo "The given file has execute access. "

else

echo "The given file does not have execute access."

fi

Output:

179

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

How To Handle Operators Using Variables And Numbers

Bash offers programmers an essential feature - the ability to use a label or a name
for referring to some other quantity as a value, command, or operator. It is called
‘assigning variables.’

• Setting a variable

The following example shows how users can assign “greetings” to the variable
var_a, and “30” to another_var.

var_a=“Greetings”

another_var=30

However, users need to be careful about the syntax they use for setting variables.
Bash does not allow white space between a variable name, the equal sign, and the
value. Hence, Bash will throw an error for the following commands:

var_a= “greetings”

var_a = “greetings”

var_a =“greetings”

180

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

• Referencing the value of a variable

Whenever the programmer enters a ‘dollar sign’ ($) followed by a word


immediately within a double-quoted string or a command, Bash will replace the
token with the assigned variable’s value. This process is called ‘expanding the
variable.’ For example:

var_a=“greetings”

another_var=30

echo $var_a

greetings

echo $another_var

30

echo $var_a$another_var

greetings 30

Operator Precedence (Order of Operations)

Many computer languages follow the rule “left-associative in case of operators


with the same precedence. In other words, they execute leftmost operations first.
Bash follows the same trend. Given below is the order of precedence from HIGH
to LOW, of operators in a bash script:

181

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Post-increment/decrement > Pre-increment/decrement > Negation > Arithmetic >


Unary Comparison > Compound comparison > Equality/Inequality > AND > XOR
> OR

In practice, one only needs to remember the following:

• The "My Dear Aunt Sally" mantra for the arithmetic operations. (multiply,
divide, add, subtract)
• Low precedence is given to compound logical operators like &&, ||, -a, and -
o.
• The order of execution of equal-precedence operators is left-to-right

182

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Final Words

Operators have an indispensable position in shell scripts as they are the elements
that give value to the variables and constants. In other words, operators infuse
functionality into the program. It is interesting to study the various types of
operators and understand their functional relevance. A strong knowledge base of
operations is also an essential tool for an efficient programmer.

183

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Food For Thought

Find the output of the following program:

a=10

b=$(( $a<0&&$a<100 ))

echo $b

exit 0

Answer: The condition' $a<0’ is false; hence, the logical AND operator will
provide the output 0.

184

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

References

1. Geeksforgeeks, Basic Operators in Shell Scripting,


https://www.geeksforgeeks.org/basic-operators-in-shell-scripting/

2. Eduonix, Learn about Arithmetic Operators in Linux Shell Scripting,


https://blog.eduonix.com/shell-scripting/learn-about-arithmetic-operators-in-
linux-shell-scripting/

3. FolksTalk, File Test Operators / Operations Examples in Unix / Linux Shell


Script, https://www.folkstalk.com/2012/09/file-test-operators-operations-
examples.html#:~:text=When%20you%20are%20using%20files,is%20reada
ble%2C%20writeable%20or%20executable.

4. Stanford Journalism, Bash variables and command substitution,


http://www.compciv.org/topics/bash/variables-and-substitution/

185

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Chapter 13

Decision Control Structure: Truth Tables & Conditional Statements


Computer programs use logical and arithmetic operators to arrive at proper
conclusions. One should know the basic concepts of the decision control
structure in Shell, of which truth tables and conditional statements are critical
components.

What is Truth Table?

Truth Table is a chart showing the truth-value of one or more compound


statements for every truth-value of the individual propositions making up the
compound statement (1).

Why Do We Need Truth Table?

A truth-value can help test the validity of any argument. Every statement can either
be true or false. The truth-value is the truth or the falsity of every proposition.

A truth table consists of rows and columns. The columns correspond to the number
of compound statements. If there are two statements, there will be two columns,
and so on. The rows constitute the possible combinations (truth or falsehood).
Thus, if the compound has two propositions, there will be a maximum of four
possibilities. Therefore, there will be four rows to the truth table.

186

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

A Simple Example of Truth Table

Here is a simple example of a truth table. It is a self-explanatory statement.

Proposition “P” Proposition “Q” P or Q


True True True
True False True
False True True
False False False
You can see that P or Q is False only if both P and Q are false. This example is a
simple one. You can have more statements with multiple propositions. However,
the logic behind the concept is the same.

What is a Boolean value?

A Boolean or bool is a data type with two possible values: true or false, and it
represents the two truth values of logic and Boolean algebra. There are primarily
two types of Boolean Values, True and False (2).

Why do we need Boolean Values?

Boolean Values are used as values of the expressions with "Yes" or "No" as its
answers. In computer circuits, these values are represented by a "1" or "0" where
"1" represents 'True' or 'Yes,' and "0" represents 'False' or 'N'.

What is a Boolean Expression?

The Boolean expression evaluates to a Boolean value. The following are the
Boolean expressions supported by Shell:

187

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

• Logical negation (!): It will invert a false condition into true and vice versa.
• Logical AND (-a): The condition will be true when both of the operands are
true.
• Logical OR (-o): The condition will be true when either one of the operands is
true.

Why do we need Boolean Expression?

A Boolean Expression is a logical statement that denotes whether a statement is


True or False. Boolean expressions are used to compare data of any type, given
that both parts of the expression have the same basic data type.

A simple example of Boolean Expression

In this example, we use the logical negation (!) to determine whether the two
values are equal or not.

#!/bin/sh
# Read the user input
echo “Enter first number”
read x
echo “Enter second number”
read y
if [ $x != $y ]
then
echo "$x != $y : x is not equal to y"
else
echo "$x != $y: x is equal to y"
fi

188

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Types Of Conditional Statements And Their Syntax

Conditional statements are useful for making decisions based on the conditions. If
there are no conditions, the conditional statements execute sequentially. If there is
a condition, the execution flow will change, depending on the result evaluated by
the condition.

There are many types of conditional statements.


Sr No Statement Description
1 If statement A Boolean expression followed by one or multiple
statements
2 If….Else An "If" statement followed by an optional case
statement statement that executes when the Boolean expression is
false
3 Nested If Use one "If" or "Else If" conditional statement inside
statement another "If" or "Else If" statements
4 Switch It allows the testing of a variable for equality against a
Statement specific list of values
5 Nested Switch Use one switch statement inside another.
statement

What is an If statement?

An "If" statement is a powerful conditional statement. It is responsible for


modifying the execution flow of a program. It is always used along with a
condition. We use Double-brackets [[ ]] to enclose the conditional expression

Please note to include a space between the enclosing brackets and the expression.

189

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

• Wrong: [[$x == $y]]


• Right: [[ $x == $y ]]

This block will process if the specified condition is true.

Syntax If (Expression)
Then
Statement
fi

Why do we need the "If" statement?

The If statement modifies the execution flow of the program, depending on which
condition is satisfied. The condition is evaluated first before the execution of any
statement inside the body of It. The programmers use conditional expressions with
the [[ compound command and the [ builtin commands.

A Simple example of If statement

In this example, we will display a statement if the number is greater than 100.
if [ $x -gt 100 ]
then
echo “That is a large number.”
fi

190

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Flowchart

What is the Switch statement?

The case statement works like a switch statement in Bash. It executes a block of a
particular pattern if the specified value matches the pattern. When there is a match,
it executes all the associated statements up to the double semicolon (;;).

case in

Pattern 1) Statement 1;;

Pattern n) Statement n;;

*)
Default statement need to execute

esac

191

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Why do we need the Switch statement?

The Switch statement is an alternative for the "If-Else" statement. There is an issue
with the "If-Else" statement. The program becomes more complicated if there are
more alternative paths. Using multiple "If-Else" statements can make the program
difficult to comprehend. The ideal solution is the switch statement.

Switch stamen flowchart

This flowchart of a simple switch statement should help you understand it better.

192

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

A simple example of the Switch statement

#!/bin/bash

echo -n "Enter The Country: "

read COUNTRY

echo -n "What Is The official Language Spoken In The $COUNTRY "

case $COUNTRY in

UK)

echo -n "English" ;;

Romania | Moldova)

echo -n "Romanian" ;;

Colombia | Cuba | Spain | Argentina)

echo -n "Spanish";;

*)

echo -n "unknown"

;;

esac

193

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Conditions

At times, it might be necessary to specify different courses of action to take in a


shell script, depending on the success/failure of a command.

The If statement should be used when making a comparison and controlling the
program flow is required. There are three types of Bash conditions: string
conditions, number conditions, and file conditions (3).

Bash String Conditions

Here are some string operators.

• = or == means equal to
• != means not equal to
• < means less than
• > means greater than
• -z test that the string is null
• -n test that the string is not empty or null

A Simple example of Bash string comparison


#!/bin/bash
echo "Please enter first string"
read str1
echo "Please enter second string"
read str2
if [[ "$str1" == "$str2" ]]; then
echo "These strings are same"
else
echo "These strings are different!"
194
fi
Troy Benson - [email protected]
THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Bash Number Conditions

Following are examples of comparing values with numbers

• -eq means equal to


• -ne means not equal to
• -lt means less than
• -le means less than or equal to
• -gt means greater than
• -ge means greater than or equal to

A simple example of Bash Number Conditions

#!/bin/bash
echo "Please enter first number"
read x
echo "Please enter second number"
read y
if(( $x lt $y ))
then
echo “$x lt $y: x is less than y.”
else
echo “$x lt $y: x is not less than y.”
fi

195

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Bash File Conditions

Here are some handy test operators for files.

• -e denotes "Does a file exist."


• -f means "Test if a file."
• -d means "test if a directory."
• -L means "test if a symbolic link."
• -N means "if a file was modified after it was the last read."
• -O means "if the current user owns the file."
• -C means "if the file's group ID matches the current user's"
• -s means "if the file has a size greater than 0."
• -r means "if the file has read permission."
• -w means "if the file has write permission."
• -x means "if the file has execute permission"

A simple example of Bash File condition

#! /bin/bash
file_name=$F
if [ -e $file_name ]
then
echo -e "File $file_name exists"
else
echo -e "File $file_name doesnt exists"
fi

196

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

What are conditional statements and logical operators?

We have seen that the "If" statement tells the program to execute a block code if a
specific condition is true. If it is false, it suggests an alternate route.

What is the need for conditional statements and logical operators?

Conditional statements will take you to the logical conclusion. A simple example
would be as follows (4).

"If it rains outside, I will take an umbrella, but if it is sunny, I will take my
sunglasses." You can do things conditionally using the "If" and If Else" statements
along with conditional statements.

At times, we might require making multiple comparisons together in a conditional


statement. The logical operators come in handy during such occasions. For
example, it allows us to say things like "If both A and B are true" or "If either of
the variables, A or B is true." We use && to test more than one conditional
expression at once, such that both must be true. We can also use, || to ascertain
that either one (or both) of the conditions are true.

197

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

A simple example of conditional statements and logical operators


Here is an example where we require both conditions to be true.

#! /bin/bash
echo "Please enter degrees outside"
read degree
echo "Please enter number of clouds"
read cloud
if [ $degree -gt 35 ] && [ $cloud -lt 5 ]
then
echo "Wear sunscreen and take glasses!"
else
echo "No for sunscreen, Sunglasses would do!"
fi

What are the arithmetic operators?

We have seen the significance of logical operators in a statement. Arithmetic


operators perform mathematical calculations on variables that represent numbers,
and on numbers.

Why do you need arithmetic operators?

Arithmetic operators perform simple arithmetic calculations like addition,


subtraction, division, and multiplication.

198

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

A simple example of arithmetic operators

#!/bin/bash
inp1=10
inp2=12
echo "1. Add"
echo "2. Subtract"
echo -n "Please choose [1 or 2]? "
read choice
if [ $choice -eq 1 ]
then
echo "Addition Result " $(($inp1 + $inp2))
else
if [ $choice -eq 2 ]
then
echo "Subtraction Result " $(($inp1 - $inp2))
else
echo "Invalid input"
fi
fi

199

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Application of Conditional and Nested Conditional Statements

We have seen that computer programs use conditional statements for selecting the
right path to proceed. If the program has to choose between one or two paths, it is a
conditional statement. We use the "If Else" statement.

On the other hand, if the program selects multiple paths to proceed, it uses nested
conditional statements (5).

What is the need for a nested conditional statement?

Imagine we have to write a program for reporting whether a number is positive,

200

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

negative, or none of the above. You can see that the numbers have to select from
three paths. The flowchart would look like this.

Given below is the code of the flowchart displayed above. Please note that there
must be a closing “fi” statement for every “if” statement that you will open. One
single “fi” is not enough for the multiple “if” statements and will throw a syntax
error.

#!/bin/bash
echo "Enter a Number"
read value
if [ $value -lt 0 ]
then
echo "The number is Negative"
elif [ $value -gt 0 ]
then
echo "The number is Positive"
else
echo "The number is Neither Positive Nor Negative"
fi

201

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Final Thoughts

Computer programs use a lot of logic and arithmetic calculations to arrive at proper
conclusions. If it were not for these logical and arithmetical operations, there
would be utter chaos. Thus, one can deduce that truth tables and conditional
statements are crucial aspects of shell scripting.

202

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Food for Thought

Can you go through this simple program below and see what the output of this
program is?

#!/bin/bash

num1=10

if [[ $num1 -eq 5 ]]

then

echo "exit_status is: $?"

echo "$num1 is equal to 5, the number is matched


in if block"

elif [[ $num1 -eq 10 ]]

then

echo "exit_status is: $?"

echo "$num1 is equal to 10, the number is matched


in elif block"

else

echo "$num1 is neither equal to 5 nor 10, no match


found"

fi

203

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Answer:

The exit_status will be zero. Since 10 is equal to 10, the output will be that the
number is matched in elif block.

References

1. The Editors of Encyclopedia Britannica, Truth Table, Britannica,


https://www.britannica.com/topic/truth-table
2. Boolean Values and Expressions,
http://www.cs.ecu.edu/karl/3300/spr16/Notes/C/Elementary/boolean.html
3. Vasminelsale, Scripting: If Comparison Operators In Bash, 27th October 2016,
100TB, https://blog.100tb.com/scripting-if-comparison-operators-in-bash
4. Review: Logic and If Statements, Khan Academy,
https://www.khanacademy.org/computing/computer-
programming/programming/logic-if-statements/a/review-logic-and-if-
statements#:~:text=We%20sometimes%20want%20to%20combine,are%20true
%22%20in%20our%20programs.&text=Now%20let's%20return%20to%20if%
20statements.
5. Pamela Fox, Nested Conditionals, Khan Academy,
https://www.khanacademy.org/computing/ap-computer-science-
principles/programming-101/boolean-logic/a/nested-conditionals

204

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Chapter 14

Decision Control Structure & Conditional Statements - Explained


All programming languages allow us to make decisions that are based on
certain pre-set conditions. The term condition refers to an expression that
evaluates a Boolean value – True or False. Thus, the decision and logic that a
programmer put in his script define how smart the program turns out. The
decision statements which bash shell supports are the if and switch (case)
statements. We will cover two detailed examples of each of these in this chapter.

Conditional Statement Explained with An Example

Description of the problem

Let us start by taking the example of a simple if conditional double decision


problem. In this problem, we must compare two numbers, and if they are equal,
display YES, and if they are not equal, display NO.

Pseudocode

The following code will output "Yes" if the two numbers are equal and "No" if
they are not.

205

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Take the first number from the user


Take the second number from the user
if number 1 equal number then
print response
"True"
otherwise
print response
"FALSE"

Flowchart

206

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Final code.

#!/bin/bash

echo "Please enter the first number"

read first

echo "Please enter the second number"

read second

if [ $first == $second ]

then

echo "YES"

else

echo "NO"

fi

Practice Problems
Problem-A

Now, let us move to an example to illustrate how to construct a file-based


decision in a bash script. This example will allow the user to input a script name
and determine the given file's permissions.

• We will use the if-then-fi decision-making structure in this program.


• For determining the permission of a file, we will use the file-test operators.
• The syntax of the if-then-fi structure is:

207

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

if [expression];

then

code if 'expression' is true.

fi

• Note that the 'expression' will get executed only if the if condition evaluates
to true. People often get confused when it comes to writing the if statement:

if (condition)

if ((condition))

if [condition]

if [[condition]]

• (…) parentheses indicate a subshell. They contain a list of commands and


not an expression like in many other languages.
• ((…)) double parentheses contain arithmetic instructions.
• [ … ] single brackets are used for conditional expressions.
• [[ … ]] double brackets form a for conditional expressions, with a few
additional features
• We use single brackets [ ] to enclose the conditional expression.
• Make sure there is a space between the expression and the squared brackets;
otherwise, there will be a syntax error.

208

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

• We will use the cd command to ensure the shell returns to the home
directory regardless of its current directory.
• The Is command will allow us to verify if the file exists.
• We have used multiple if conditions for solving the problem.

Problem-B

The next example requires the user to input a student's marks and check if marks
are greater or equal to 80 then print "Very Good". If marks are less than 80 and
greater or equal to 50, then print "good" and so on.

• In this example, we need to make the correct decision from multiple


conditions.
• We will use the if-elif-fi statement, which is the advanced control statement
in Shell.
• We can use if-elif-if when we want to execute one out of many blocks of
code.
• We will use && to test more than one conditional expression at one time.
• It will check expression 1 and execute statement 1 if it is true.
• If expression 1 is false, it will check expression 2 and execute its statement,
and so on.

209

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Problem-C

In this example, we focus on the switch case statement in Bash. The program will
allow the user to input a month name. It will then display the international event
in the chosen month. If there is no defined pattern in the script, it will display "No
match found."

• The case statement will start with the 'case' keyword, followed by the case
expression (the month name), and the in keyword. The statement will end
with the esac keyword.
• The | operator can separate multiple patterns.
• The ) operator will terminate a pattern list.
• There can be special characters in a pattern.
• A pattern, including its associated commands, is called a clause.
• Each clause terminates with ;;.
• The commands which correspond to the first pattern, which will match the
expression, get executed.
• (*) acts as the final pattern that defines the default case when no other
cases match.
• We use the "shopt -s nocasematch" to match the pattern irrespective of its
case.

210

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Problem-D

It will allow the user to choose from the three-car brands, namely, Mercedes,
Audi, and BMW, and display the selected car company's headquarters.

• The switch case statement in Bash allows the script to compare different
values against a variable, easier than the if conditional statement.
• It has a similar concept to the C or JavaScript switch statement. The Bash
case statement is different from the other two. It stops searching for the
pattern match after it has executed statements associated with a matched
pattern.
• In this example, we will first display a menu using the printf command and
ask the user to key-in the brand's name.
• After that, the case conditional will follow, similar to the previous example.
• Note that we do not use the wildcard asterisk symbol (*) as the final
pattern in this example.

211

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Problem-A Solution

Pseudocode

The following code will read the file name and display the permissions it has:

Take the file name from the user

If file name exist then -e


print “file exists”
if file has read permission, then -r
assign "readable " to the status variable
if the file is writable, then -w
assign "writable " to status variable
if file is excecutable then -x
assign " executable " to status variable
print "file permission: "$status
otherwise
print "The file does not exist"

212

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Flowchart

213

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Shell Script
#!/bin/bash
cd
ls -l
read -p "Enter a file name: " file_name
if [ -e $file_name ]
then
echo "file exists!"
if [ -r $file_name ]
then
status="readable "
fi
if [ -w $file_name ]
then
status=$status"writable "
fi
if [ -x $file_name ]
then
status=$status"executable"
fi
echo "file permission: "$status
else
echo "file does not exist"
fi

214

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Problem-B Solution

Pseudocode

The following program will input a student's marks and check if marks are greater
or equal to 80 then print "Very Good". If marks are less than 80 and greater or
equal to 50, then print "good" and so on.

Take the marks from the user


if marks greater than 80 then
message is "Very Good"
if marks between 51 to 79 then
message is "Good"
if mark greater then 33 and less then 50 then
message is "Need to work hard"
otherwise
message is "You are fail!"

215

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Flowchart

216

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Shell script

#!/bin/sh

echo "Please enter the marks out of 100"

read marks

if [ $marks -ge 80 ]

then

echo "Very Good"

elif [ $marks -lt 80 ] && [ $marks -ge 50 ]

then

echo "Good"

elif [ $marks -lt 60 ] && [ $marks -ge 33 ]

then

echo "Need to work hard"

else

echo "You are fail!"

fi

217

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Problem-C Solution

Pseudocode

The following program will read the input month from the user and display
important events in the chosen month (until July).

Ask the user to enter the month


In case month is 1
print response "24th January is the International Day of Education"
in case month is 2
print response" 20 February is the World Day of Social Justice."
In case month is 3
print response "8th March is the International women's day."
In case month is 4
print response "7th April is The World Health Day"
in case month is 5
print response "The 15 May is the International Day of Families"
in case month is 6
print response "20th June is the World Refugee Day"
in case month is 7
print response "11th July is the World Population Day"
in any other cases (default)
print response "No matching information found"

Flowchart

218

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

219

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Shell Script

shopt -s nocasematch
echo "Enter name of the month"
read mnth
case $mnth in
January)
echo " 24th January is the international Day of
Education."
;;
February)
echo " 20 February is the World Day of Social
Justice ."
;;
March)
echo "8th March is the International women’s day."
;;
April)
echo "7th April is The World Health Day";;
May)
echo "The 15 May is the International Day of
Families"
;;
June)
echo "20th June is the World Refugee Day"
;;
July)
echo "11th July is the World Population Day"
;;
*)
echo "No matching information found"
;;

220

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Problem-D Solution

Pseudocode

The following program will allow the user to choose from the three car brands,
namely Mercedes, Audi, and BMW, and display the selected car company's
headquarters.

display the menu [a] mercedes [b]audi [c]bmw


get user input (name of car) cars
case $cars = mercedes
print response "Headquarters - Affalterbach, Germany"
case $cars = audi
print response "Headquarters - Ingolstadt, Germany"
case $cars = bmw
print response "Headquarters - Chennai, Tamil Nadu,
India"

221

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Flowchart

222

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Shell script

#!/bin/bash

clear

printf "Menu: \n[a] mercedes [b]audi [c]bmw "

read-p “Name of the Brand you chose:” CARS

case "$CARS" in

mercedes) echo "Headquarters - Affalterbach, Germany" ;;

audi) echo "Headquarters - Ingolstadt, Germany" ;;

bmw) echo "Headquarters - Chennai, Tamil Nadu, India" ;;

esac

223

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Final Words

In this chapter, we learned how to incorporate conditions in our Shell script to


undertake different actions when a command succeeds or fails. We learned that
the if statement can be used to determine various actions. It is suitable for writing
programs concerning input and files, string comparisons, arithmetic operations,
etc. On the other hand, a case statement incorporates more complex definitions
of the user's conditions.

224

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Food for Thought

Write a program using Bash to check if a directory exists or not

Hint: It is an if-else single decision problem. Use the '-d' file-test operator.

Solution:

if [ -d "/path/to/dir" ]
then
echo "Directory /path/to/dir exists."
else
echo "Error: Directory /path/to/dir does not exists."
fi

225

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

References

1. Educative, The if-else condition in shell script.


(https://www.educative.io/edpresso/the-if-else-condition-in-shell-script)

2. HowtoForge, Shell Scripting Part 3: Decision Control Structures in Shell


Scripts. (https://www.howtoforge.com/tutorial/linux-shell-scripting-
lessons-3/)

3. GeeksforGeeks, How to write a pseudocode.


(https://www.geeksforgeeks.org/how-to-write-a-pseudo-code/)

4. Tutorialspoint, The if-elif-statement.


(https://www.tutorialspoint.com/unix/if-elif-statement.htm)

5. GeeksforGeeks, Conditional statement shell script.


(https://www.geeksforgeeks.org/conditional-statements-shell-script/)

6. Cyberciti, How To Check If a Directory Exists In a Shell Script.


(https://www.cyberciti.biz/faq/howto-check-if-a-directory-exists-in-a-bash-
shellscript/)

226

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Chapter 15

Defining and Understanding Iterations (Loops) In Bash Scripting


In computer programming, iteration refers to a process where the program
repeats a set of structures or instructions in a sequence, the number of times
specified by the user, or until the program meets a particular pre-set condition.
When the program executes the first set of instructions again, it is called
iteration. Similarly, when the program executes a sequence of instructions
repeatedly, it is known as a loop. In this chapter, we will study the loops in Bash
in detail.

What is Iteration

Most languages, including Bash, uses the concept of loops. For example, it will
become cumbersome to type the same code with slight variations twenty times if
we want to repeat a task twenty times. Instead, we can use the FOR and WHILE
loops in Shell!

227

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

FOR loop

FOR loops in Shell keep iterating a set of values until the list gets exhausted.

Syntax

for VARIABLE in 1 2 3 4 5 .. N

do

command1

command2

commandN

done

for VARIABLE in file1 file2 file3


do
command1 on $VARIABLE
command2
commandN
done

Using lists in FOR loop

A list refers to a list of names. If you omit the "in", the list will default to the
quoted command-line arguments, or "$@". "$@" is a positional parameter that
treats all parameters as a quoted string. In simple words, all the parameters in the
quoted string will be seen as separate words. It is preferable to define the "in" list
for clarity in the code. For example:

for user in nick john harry leo bob jacob

do

echo $user

done

228

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

The example follows the list of values that are received from the command line. If
'in list' is missing, your loop will operate on '$@'

#file name – forloop.bash

# recieve argument from the command line

for i in "$@"
do
echo $(($i * 2))
done

#without “$@”

for a
do
echo -n $(($a * 3)) " " # -n don't add new line
done

#Call the script from the command line

Forloop.bash 1 2 3

You may also save a list in a variable and iterate through the variable, and access
each element using a FOR loop, as it is shown in the following example.

users=" nick john harry leo bob jacob "

for user in $users ; do

echo $user
done

229

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

We can also use filename globbing (using wildcards to perform filename


expansion) in the FOR loop list. The * construct is a wildcard, which means all the
files in a directory. It should not be confused with $*. $* refers to all the
parameters quoted as a single word.

#list all files in the current director

for file_name in * ; do
if [ -d "$file_name" ]
then
echo "directory $file_name"
else
echo -e "\t$file_name"
fi
done

Using ranges in FOR loop

There is built-in support to set-up ranges using {…} in the Bash version 3.0+

#!/bin/bash
for var in {1..10}
do
echo "Welcome $var times"
done

You can set-up a step value by using the {START..END..INCREMENT} syntax in


Bash v4.0+.

#!/bin/bash
echo "Bash version is ${BASH_VERSION}..."
for var in {0..10..2} do
echo "Welcome $var times"
done
230

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

The above code will increment the value by 2. Output:

10

In the earlier versions of Bash, users could programmatically generate simple


sequences by using the seq command.

#!/bin/bash
for i in `seq 1 10`; do
echo $i
done

C-style FOR loop Syntax

Users who are using the latest Bash version (version 2.04 and above) can use the
latest FOR syntax, which uses double parenthesis ((…)) to perform iteration. It is
similar to the C language.

The generalized form of the new FOR loop:


for (( initialization ; test ; step )) ;

do

commands ;

done

231

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Double parenthesis means that programmers can use the ((…)) syntax construct to
write the script's expressions. The program executes the initialization part once
when the loop starts. The on any iteration, it evaluates the test part. If the test
evaluation result is true, the program will execute the loop body's commands and
finally update the step part. If the test is false, the loop terminates.

Following is the code to print numbers from 1 to 10 using the new FOR loop.

for (( var=0 ; var <= 10 ; var++ )) ;

do

echo $var ;

done

For Loop Flowchart And Code Example

Problem Definition:

Write a program using the FOR loop for spanning through a given list of numbers
(0 to 9)

232

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Flowchart:

Code:

#!/bin/sh

for var in 0 1 2 3 4 5 6 7 8 9

do

echo $var

done

233

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Explanation:

• #!/bin/bash – It shows that the code will be a bash script


• var– We use it as a placeholder for a variable. It is important to distinguish
it from $var, which refers to the variable's individual value.
• in – It is used for separating the variable from the items which follow.
• 0 1 2 3 4 5 6 7 8 9 – It refers to the items that the user wants to perform the
instruction on.
• do – It is the keyword that will start the loops. It will execute the instruction
n times, where n is the total number of items. In this example, the value of n
is 9.
• echo "$var" – It is the code that will get repeated n times.
• done –It will stop the loop.

Output

0
1
2
3
4
5
6
7
8
9

234

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

While and Until Loops

You can execute a particular set of commands continuously until you reach
specific conditions using the WHILE loop. Programmers generally use this loop
when they want to manipulate the value of a variable repeatedly.

Programmers use the WHILE loop to execute a series of commands, WHILE a


condition is true. But sometimes, they need to execute the commands UNTIL a
condition becomes true. (The Shell will execute the statement if the resulting
value is false.)

Syntax
while command
do
Statement(s) which must be executed if the command is true
done

Until command
do
Statement(s) to be executed until command is true
done

235

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

The following code snippet will print 1 to 10 using a while loop.

echo "Using while loop..."


i=1
while [ $i -le 10 ]
do
echo -n "$i "
i=$((i + 1 ))
done
echo “End of while loop”

Breaking Statement

The break command causes the iteration to stop and exit the loop.

#!/bin/bash

val=1

while [ $val -lt 5 ];

do

if [ $val -eq 4 ];

then

break

fi

echo "Iteration: $val"

val=$(($val + 1))

done
236

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Explanation:

• The expression if [ $val -eq 4 ] will check the number value.


• The loop may stop if the if statement condition becomes TRUE, and the
break statement gets executed.

Continuing Statement

In Bash, you can use the CONTINUE command to skip the remaining statements
in the loop body and continue to the next iteration. In simple words, CONTINUE
in Bash will mean proceeding to the next iteration of the loop. Traditionally, this
statement is called CONTINUE, similar to C language.

In the following example, when the current iterated item reaches the value 2, we
use the CONTINUE statement to make the program skip the remaining statements
and return to the loop's start and continue the subsequent iteration.

var=0

while [[ $var -lt 5 ]]; do

((var++))

if [[ "$var" == '2' ]]; then

continue

fi

echo "Number: $var"

done

echo 'All Done!'

237

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Output:
Number: 1

Number: 3

Number: 4

Number: 5

All Done!

Infinite loop

An infinite loop is an endless loop that never meets its condition. An infinite loop
runs forever unless an unexpected event such as shutting down a computer occurs.
An infinite loop can waste computer resources such as memory and CPU time,
preventing other programs from running smoothly.

An infinite loop can be suitable when a program's goal is to execute a set of


instructions with no end condition.

Example of an infinite loop

while :
do
echo "Pres CTRL+C to stop..."
sleep 1
if [ 0 -eq 1 ] #bad condition
then
break #Stop this loop
fi
done

238

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

While Loop Flowchart And Code Example

Problem definition:

Write a program to increment the value of a variable from 0 to 10.

Flowchart

Code

i=1
while [ $i -le 10 ]
do
echo "$i"
((i++))
done

239

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Explanation:

As seen above, we have defined variable i, whose value will increment with each
iteration. The condition part will test its value and will display its value as long as
the condition is True. When the loop is executing, the value of i is checked to
ascertain if it has a value less than 10. If the value is less than 10, i.e., the condition
is TRUE, the exit status is zero. In such cases, the program will display the current
value of i and increment it by 1 later.

Output

1
2
3
4
5
6
7
8
9
10

Problems to Solve

• Q.1 Use the FOR loop to print numbers from 1 to 50, which are divisible
by 9.

• Q.2 Use the WHILE break statement to add two numbers and skip the while
loop when the user enters -1.

• Q.3 Explain by modifying the simple example of WHILE loop (2.b.4), what
this WHILE with "do" keyword behaves if the condition is False upfront?

240

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Solutions

Q1-Solutions

for x in {1..50}; do

if [[ $(( $x % 9 )) -ne 0 ]]; then

continue

fi

echo "Divisible by 9: $x"

done

For numbers that are not divisible by 9, the CONTINUE statement will skip the
echo command, and the control passes to the next iteration in the loop.

Output

Divisible by 9: 9

Divisible by 9: 18

Divisible by 9: 27

Divisible by 9: 36

Divisible by 9: 45

241

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Q2-Solutions

#!/bin/bash

while :

do

read -p "Enter the two numbers ( - 1 to quit ) : " x y

if [ $x -eq -1 ]

then

break

fi

ans=$(( x + y ))

echo $ans

done

Output:

242

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Q3-Solutions

i=11

while [ $i -le 10 ]

do

echo "$i"

((i++))

done

echo "Execution is out of while loop"

Output:

Execution is out of while loop

As you can see from the output, the program will not display the variable's value at
all. Since the loop's condition is initially false, none of the statements inside the
loop will be executed.

243

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Final Words

In this chapter, we saw how you could perform basic iterations using the Bourne
Shell programming. We learned that there are two types of loops used in Bash, i.e.,
the FOR loop and the WHILE loop. We also reviewed different kinds of FOR
loops in various Bash versions plus how-to utilize break and continue statements.

244

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

References

1. Tutorials Point, FOR-Loop, from: https://www.tutorialspoint.com/unix/for-


loop.htm
2. Hostinger, BASH FOR loop guide and examples, from:
https://www.hostinger.com/tutorials/bash-for-loop-guide-and-examples/
3. Cyberciti, BASH FOR Loop examples, from:
https://www.cyberciti.biz/faq/bash-for-
loop/#:~:text=A%20'for%20loop'%20is%20a,files%20using%20a%20for%2
0loop.

4. Tutorials Point, WHILE-Loop, from:


https://www.tutorialspoint.com/unix/while-loop.htm
5. Linuxize, Bash Continue Statement, from: https://linuxize.com/post/bash-
break-continue/#:~:text=Bash%20continue%20Statement,-
The%20continue%20statement&text=When%20%5Bn%5D%20is%20given
%2C,continue%20with%20the%20next%20iteration.

245

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Chapter 16

Advanced Examples of Iterations (Loops) In Bash Script


We learned in the previous chapter about iterations in Bash script. One can use
the FOR, WHILE, or UNTIL loops to define iterative statements or loops in
Bash. In this chapter, we will supplement our knowledge of iterations by looking
at some advanced examples.

'Computers' gained popularity and widespread adoption than any other


technology or device in the world because a computer was capable of executing
repetitive tasks much faster than any other machine or human being. And hence
iterations or loops are the most important constructs of any programming language.
Bash scripts, like any different programming language, allows the user to create
various complex situations.

The iterative statements assume greater significance in such a scenario. In


simple terms, we can define an iterative statement as a command which helps users
execute a portion of the code repeatedly (which is also known as the loop body)
until it reaches a specific value of the controlling expression (or a condition). For
example, you will use an iterative statement to read and process every line of a
particular file repeatedly.

246

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Problem A

Use the FOR loop in Bash to write a program without a list and read command-line
arguments.

Steps:

1. We can use the FOR loop without any list/command output/array.


2. This loop iterates on the defined command-line arguments.
3. We use the $stp variable for finding the step of the loop.
4. Each step will increment the value of $stp by 1.
5. When the $stp is 1, the script will print the message "I like chocolates."
6. When the $stp is 2, the script will print the message "My favorite color is"
7. When the $stp is 3, the script will print the message "I love Git Bash."
8. do indicates the start of the loop
9. echo $stp is used to display the stored value in the stp variable.
10.; will terminate the echo statement.
11.done will indicate the end of the loop.
12.The command-line arguments to run the script are $ bash script_name

Problem B

Use the infinite FOR loop to display a five lists menu and display a specific
message for each number (5 to exit).

Steps:

1. We use the infinite FOR loop to perform repetitive tasks multiple times.
2. The loop terminates when a particular condition appears.
3. We will not define a termination condition in this loop.
4. The loop will display a menu for five lists until the user presses the number
5.
5. For other numbers, the program will display a specific message (from 1 to
4).
6. After that, it will display the menu again.
7. The empty for expression (( ; ; )) is used to define an infinite loop.
8. Since we are using the case command inside an infinite loop in this example,
we will use the exit command to terminate the loop.

247

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Problem C

Use the CONTINUE statement in the WHILE loop to display a set of 5 numbers
and omit the third step.

Steps:

1. In this program, we will use the CONTINUE statement in the WHILE loop.
2. The program will iterate five times without printing all of the five positions.
3. We will define the condition [ $i -le 5 ] inside the WHILE loop.
4. The program will check the condition [ $i -le 5 ] before executing the
commands.
5. The program will execute the commands between do and done for as long as
the condition [ $i -le 5 ] is true.
6. We will use the CONTINUE statement in the third position. Thus, the loop
will skip the text of the third position and continue to the next iteration.
7. We will define the expression inside the if..then..fi statement within the
WHILE loop.
8. If the expression is true; [ $i == 3 ], the loop will execute the CONTINUE
statement and omit the third step.
9. If the expression is false, then the program will continue to the next iteration.

Problem D

Use a variable in the UNTIL loop to decrement a number initialized at ten until it
reaches the value 5.

Steps:

1. In this program, we will use the $var variable for controlling the iteration of
the loop.
2. We will initialize the loop at 10.
3. The loop will carry on the iteration six times.
4. We use the $echo command for printing the value of $var after each step.
5. To reach the UNTIL loop's termination condition, the value of $var will
decrement by 1 in each step.
6. We will define the condition [ $var – lt 5 ] inside the UNTIL loop.
7. The loop will check this condition before executing the commands.

248

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

8. It will only execute the commands if the condition evaluates to false.


9. The loop will get terminated when the condition evaluates to true (the value
reaches less than 5 in this case).

Problem A Solution:

Pseudocode

The following code will use the FOR command to create a program without a list

Define a variable stp=1


loop through text
if stp is equal to 2
set disp variable = "My favorite color is "
else if stp is equal to 3
set disp variable = "I love "
else
set disp variable = "I like "

Print the result "$disp $text"


Increment the variable stp by 1 using the + operator

249

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Flowchart

Script
stp=1
for text
do
if [ $stp -eq 2 ]
then
disp="My favorite color is "
elif [ $stp -eq 3 ]
then
disp="I love "
else
disp="I like "
fi
echo "$disp $text"
((stp=$stp+1))
done

250

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Output

Problem B Solution:

Pseudocode
The following code will use the FOR command to create a program to allow the
user to choose from 1 to 5 and display different results.

define the infinite FOR loop


do
Print the message "1. Print the success message."
Print the message "2. Print the information message."
Print the message "3. Print the Warning message."
Print the message "4. print the error message."
Print the message "5. To Exit"
Take the input from the user
define the case expression, followed by the "in" keyword
1) Print the result "The Task is Successfully completed.";;
2) Print the result "It is an Invalid input";;
3) Print the result "Your computer is running on low battery";;
4) Print the result "You submitted a Wrong number of arguments ";;
5) exit 0;;
*) print the result "Wrong selection";;
terminate the case statement using "esac"
done

251

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Flowchart

252

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Script
for (( ; ; ))
do
echo "1. Print the success message"
echo "2. Print the information message"
echo "3. Print the Warning message"
echo "4. print the error message"
echo "5. To Exit"
echo -n "Select a number from [1-5]:"
read ans
case "$ans" in
1) echo "The Task is Successfully completed." ;;
2) echo "It is an Invalid input";;
3) echo "Your computer is running on low battery";;
4) echo "You submitted a Wrong number of arguments
";;
5) exit 0;;
*) echo "Wrong selection";;
esac
done

253

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Output

Problem C Solution:

Pseudocode
The following program will use the CONTINUE statement in the WHILE loop to
display a set of 5 numbers and omit the third step.

Let variable i to be 10.


while i is less than or equal to 5.
increment the value of i by 1.
if i is equal to 3 skip the iteration using continue.
Print the result "Value of i: $i"

254

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Flowchart

Script
i=0
while [ $i -lt 5 ]
do
(( i++ ))
if [ $i == 3 ]
then
continue
fi

echo

Output:

255

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Problem D Solution:

Pseudocode
The following program will use a counter in the UNTIL loop to decrement the
value of a number 6 times.

Initialize the value of the variable var=10


Loop until var is less than 5
Print the result "The current value of the variable =
$var"
decrement the value of var by 1

Flowchart

Script
var=10
until [ $var -lt 5 ]
do
echo "The current value of the variable = $var"

256

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

((var--))
done

Output

Final Words

In this chapter, we saw some examples of iterations in detail. The explanations and
pseudocodes, coupled with detailed flowcharts, will help students grasp the idea
behind the code written for each problem. They can start practicing with these
codes only after getting their basics about iterations clear from the first chapter.

257

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Exercise:

Below are some additional examples for your practice, which will help bring
further clarity about iterations.

Exercise A:

Allow the user to enter from the following ways of saying hello: howdy, hello,
guten tag, bonjour, gday, and display the result of the language used.

You can use the WHILE loop in this example and include the CASE
statement to define different languages. The code will look something like this:

while read lang


do
case $lang in
howdy) echo American ;;
hello) echo English ;;
guten tag) echo German ;;
bonjour) echo French ;;
gday) echo Australian ;;
*) echo Unknown Language: $lang ;;
esac
done

258

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Exercise B:

Write a code to print even and odd numbers from 1 to 5.

You can use the FOR loop (( INITIALIZE; TERMINATE; INCREMENT)) to


write this code. It will look something like this:

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


do
if (( $i%2==0 ))
then
echo "$i is even"
else
echo "$i is odd"
fi
done

259

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Exercise C:

Demonstrate multiple conditions in an Until loop using two variables x and y.

The code will look something like this:

maximum=5
x=1
y=0
until [[ $x -gt $maximum || $y -gt $maximum ]];
do
echo "x = $x & y = $y."
((x++))
((y++))
done

260

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

References

• Linux-hint, Bash WHILE loop examples, from:


https://linuxhint.com/bash-while-loop-examples/

• Compciv, Loops, from:


http://www.compciv.org/topics/bash/loops/

• Shell-script, Part 7: Loops, from:


https://www.shellscript.sh/loops.html

• Linux-hint, Bash FOR loop examples, from:


https://linuxhint.com/bash-for-loop-examples/

• Javatpoint, Bash UNTIL loop, from:


https://www.javatpoint.com/bash-until-
loop#:~:text=Bash%20Until%20Loop%20in%20a,of%20commands%20are%
20executed%20iteratively.

261

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Chapter 17

Learning Function in Bash Scripting


A set of commands which users can call repeatedly is known as a Bash function.

The functions help in making a Bash script readable and avoid writing repetitive

codes. However, Bash functions are limited as compared to other programming

languages. In this chapter, we discuss the basics of functions in Bash..

What Is A Function?

Most people get confused about whether to call Bash functions as functions or
procedures. Strictly speaking, functions are used in programming languages to
return a single value and not any output. A procedure, on the other hand, may
produce an output but does not return a value. They can return a value in one of
the following ways:
• Change a single or multiple variable's states.
• Make use of the exit command to end the script.
• Can be used to update the contents of a file.

262

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

• Can use the return command for ending the function, and the supplied
value is returned to the calling section of the script.

How to Define A Function?

There is a straightforward procedure to declare a bash function; they can be


expressed in two formats.
A. The preferred and widely used format is the one that starts with a function
name and then followed by a parenthesis.
function_name () {
commands
}
Single line version of the above format is:
function_name () { commands; }

B. The second format uses the reserved word "function" to start, and then it is
followed by the function name.
function function_name {
commands
}

Single line version of the above format is:

function function_name { commands; }


Key points to note here are:
• The commands inside the {} are also known as the body of the function.
You must ensure to separate the curly braces from the body by using new
lines or spaces.
• If you define a function in Bash, it doesn't mean that it will get executed
automatically. It would be best if you used the function name to invoke a

263

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

function in Bash script. When you invoke a function, the body of the
function will get executed.
• You must define the function before placing any calls to the function.
• The compacted function or the single line versions must have a
semicolon after the function's last command.
• It is prudent to keep the function names descriptive, in line with the code.

The following example will help clear things better:


1) #!/bin/bash
2) example_git () {
3) echo 'hello, this is GIT Bash!'
4) }
5) example_git

Following is the line-by-line analysis of the above code:


• In line 2, we will define the function by assigning it a name
(example_git). The { will mark the beginning of the function's body.
• Line 3 represents the function body. It can contain multiple variable
declarations, statements, and commands.
• The } in line number 4 is defining the end of the example_git function.
• We are executing the function in line number 5. You can execute the
function any number of times you want.
• When you run the script, it will display the message 'hello, this is GIT
Bash!'

How To Call A Function?

You can call or trigger a function in a Bash script by invoking its name in the
script. Bash treats the function calls as a command. We discuss more on the
syntax of calling a function in section 5. “example_git”

264

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Built-In Functions and Shell Script Function Libraries.

Bash allows you to create function files that will store all your functions. These
function files are called function libraries. Then you can load all your functions
into the Bash script. The syntax to load all functions is as follows:

. /path/to/your/functions.sh

Syntax and Method Of Calling A Function

It is relatively easy to create a function in Bash script. As discussed earlier,


there are two different syntaxes for writing a function.

function_name () {
<commands>
}

or
function function_name {
<commands>
}

Key points to note about function syntax:

• You can use either of the above two methods to specify a function. Both
of them operate in the same manner, and it's a matter of choice, with no
advantage or disadvantage associated with one method or the other.
• The () brackets may contain arguments in other languages, whereas they
are just for decoration purposes in Bash!

265

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

• You must define the function in the script before making any calls to the
function.
• To invoke or call a function, type the function name.
The example shows how to define and write a tomrw() function to display
tomorrow's date.

tomrw(){ date ++date=’1 day after’;}

To call the function tomrw(), you will need to write:

tomrw

Your program will look like this in the end:

#!/bin/bash
tomrw(){
date ++date=’1 day after’;
}
tomrw

How to Return Values?

In many programming languages, users can call a function to return a value.


However, the functions in Bash do not return values.

The Bash function will return the exit status for the last command it executes,
captured in the $? variable. All non-zero positive integers between the range 1-
255 will indicate a failure, and zero will indicate a successful execution.
However, users can put a return statement inside the script for altering the

266

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

function's exit status. The following errorfunction script will help clear things
better:

#! /bin/bash
error_script () {
Hello World
return 0
}
error_script
echo "The return status of the error function is:
$?"
Now, when you run the errorfunction.sh bash script, the output will be:

The errorfunction would never return a non-zero exit status if we did not define
the return 0 statement. It is so because "Hello World" results in an error
"command not found."

Hence, we can alter the exit status of functions to return values even when we
know that Bash functions don't return values. The critical point to remember
here is that the return statement terminates a function immediately.

What Is an Attribute or Parameter?

Bash uses entities known as parameters to store values. It can either be a name,
number, or unique character. The parameter which is denoted by a name is also
called a variable. The variable includes a value and zero or more attributes. You
can assign the attributes with the built-in declare command.

267

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

There are two types of parameters in Bash:


• Positional parameters are denoted by one or more digits, in addition to the
single digit 0. You can assign positional parameters by invoking Shell's
arguments and reassign them using the built-in set command. They are the
arguments given to the Bash script when it is invoked. They can range from
$1 to $N. If N consists of more than one digit, you must enclose it in braces
like ${N}.
• Special parameters are those which the Shell treats specially. ($*), ($@),
($#), ($?), ($$), etc are the examples of special parameters in Bash.

Global and Local Variables

In Bash scripts, you can define some variables available throughout the script,
known as global variables, and others that are only visible within the block of
the code, known as local variables. The following example will help clear
things better.

#!/bin/bash
pprint()
{
local locvar="Local variable"
echo -e "Value of the Local variable within the function"
echo $locvar
glovar="Global variable changed"
echo -e "Value of the Global variable within the function"
echo $glovar
}
glovar="Global variable"
echo -e "Value of the Global variable before calling function"
echo $glovar
echo -e "Value of the Local variable before calling function"
echo $locvar
pprint
echo -e "Value of the Global variable after calling function"

268

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

echo $glovar
echo -e "Value of the Local variable after calling function"
echo $locvar

The output of the above code will be:

Hence, it is clear from the output that before and after calling the pprint()
function, the local variables have only empty values. Its scope is limited to only
within the function, and it gets vanished outside the function. However, the
global variable updates its value even after the execution of the function.

Recursion

The local function variables offer one feature called self-containment. Any self-
contained function will only use the script's variables to pass to it in the
command line, and it will not use any resources outside the function.

It is the feature that will allow the user to call the function recursively.
Recursion means the function will call itself to reach an answer. Mostly, there is
a base value to which the recursive function iterates down. Advanced

269

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

mathematical algorithms require recursion for reducing complex equations


down to the level, which is defined by the base value.

So, what is the example of a recursive algorithm? The classic example is


calculating factorials. As you might be aware, the factorial of a number refers to
the number multiplied by the preceding numbers' values. The factorial of 5 will
be given as:

5!= 5 * 4 * 3 * 2 *1 = 120

We can reduce the above equation to the following format using recursion:

x! = x * (x-1)!

Now, let us see how to define factorial through a recursive script:

#!/bin/bash
factorial_num() {
if [ $1 -eq 1 ]
then
echo 1
else
local var=$(( $1 - 1 ))
local res=$(factorial_num $var)
echo $(( $res * $1 ))
fi
}
read -p "Enter a number: " input
factorial=$(factorial_num $input)
echo "The factorial of $input is: $factorial"
Key points to note are:
• You must define a base case to begin a recursive function. It becomes
necessary for ending the chain of calls to the recursive function. In the
factorial () function, we have defined the base case as follows:

270

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

if [ $1 -eq 1 ]
then
echo 1
• The next step is deriving the recursive case of the factorial function. As seen
above, to find the factorial of a given positive number greater than 1, x,
multiply it with the factorial of x-1.
factorial(x) = x * factorial(x-1)
• Hence, you can derive the recursive case of the script as:
local var=$(( $1 - 1 ))
local res=$(factorial_num $var)
echo $(( $res * $1 ))

Following will be the output of the script as mentioned above:

Common Errors with Declaring and Using Functions

As you are aware, Bash does not need you to declare a variable. When you use
a variable inside the script, it will create a variable automatically. Although it is
more convenient, it may lead to unfortunate consequences. An example is a
spelling error that may create an extra variable you did not wish to create.

Other common errors include:

• Not using the proper syntax to define a function.

271

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

• The function call has a different function than the one you defined.
• Other syntax errors like space between function name and {, case
sensitivity, forgot to use ", etc.

Problems to Solve

1) Write a program to define a function that accepts parameters John and Smith
while calling the function. Represent these parameters by $1 and $2.

2) Use the above example to define a function that will return a value of 10.

3) Write a code to demonstrate the nesting of two functions.

Solutions

Q1-Solutions

#!/bin/sh
example1 () {
echo "Hello World $1 $2"
}
example1 John Smith

Q2-Solutions

#!/bin/sh
example2() {
echo "Hello World $1 $2"

272

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

return 10
}
example2 John Smith
ret=$?
echo "The Return value is $ret."

Q3-Solutions

#!/bin/sh
func_one () {
echo "This is the first function speaking..."
func_two
}
func_two () {
echo "Now, this is the second function
speaking..."
}
func_one

273

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

References

1. Linuxize, "Bash functions", from:


https://linuxize.com/post/bash-functions/

2. Ryans Tutorials, "Bash Scripting Tutorial," from:


https://ryanstutorials.net/bash-scripting-tutorial/bash-functions.php

3. Cyberciti, "Calling Functions", from:


https://bash.cyberciti.biz/guide/Calling_functions

4. Linuxhandbook, "Bash functions," from:


https://linuxhandbook.com/bash-functions/

5. TISWWW, "Shell Parameters", from:


https://tiswww.case.edu/php/chet/bash/bashref.html#Shell-Parameters

274

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Chapter 18

Advanced Examples on Functions


In the previous chapter on functions, we discussed the syntax and basics of
using functions in a Bash script. This chapter will help you apply the gained
knowledge from the previous chapter to write scripts using functions. This
chapter will cover four crucial areas of functions that an aspiring Bash
programmer must be aware of. These are: Passing arguments to a function, set
up a return status for the function, declare local and global variables, and
recursion.

First, let us brush up on our knowledge about functions. You can think of functions
as small scripts within a script. It is a small code that you can call many times in
your script. Functions come in handy when you have certain tasks to perform
several times. They save you from the hassle of writing the same code over and
over again! With that definition in mind, let's get down to business.

Problem A

Write a simple program using functions to pass multiple arguments to the program
and return the values.

275

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Learning Outcome: After this exercise, you will gain knowledge about how to
pass arguments to the script. You can use arguments when you want to write a
script that will perform different functions by using these arguments' values.

For passing any number of arguments in the Bash function, you must insert them
right after the function's name. It is important to put spaces between the function
name and the arguments. It is also suggested to use double quotes to prevent the
misspacing of arguments.

• We will define the arguments as $1, $2, $3 ... $n. The console will access the
given arguments in the same sequence, corresponding to the arguments'
position after the function's name.

• You cannot define an argument with $0 because it is reserved for the


function's name.

• You can use the $# variable for holding the positional arguments/ parameters
provided to the function.

• To hold all the arguments/parameters provided to the function, use the $*


and $@ variables.

o $* with double quotes (i.e., "$*" ) will expand to a single string which
is separated by the space, example, "$1 $2 $n etc".
o $@ with double quotes (i.e., "$@" ) expands to the separate string, for
example, "$1" "$2" "$n" etc.
o $* and $# without any double quotes are the same.

276

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Problem B

Write a simple program to set up a return status for a function. Use it to return a
value of 8 for a function.

Learning Outcome: In most programming languages, you can return a value


for the functions meaning the function will route the data back to the original
calling location. However, Bash does not offer support for returning a value
when a function is called. This exercise will help students define the return
status of a function.

You can set a return status, which makes the program similar to the one with an
exit status. Thus, after the function is complete, it will show the last executed
statement's status as the return value. For success status, it will return 0, and for
failure, it will return any number between 1-255 range.

• In this program, we will use the 'return' keyword to indicate the return
status.
• We will use the $? variable to display the stored return value (8 in this
case).
• The return statement will terminate the function, and it will work as the
function's exit status.

Problem C

Write a program using functions in a Bash script to declare two variables of the
same name – one global and one local.

277

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Learning Outcome: As you are already aware, we can declare a variable inside
a function as a local variable using the local keyword. Bash variables have
dynamic scope. When you declare a variable local to a function, its scope
remains the same until the function returns and calls to other functions. This
exercise will provide a deeper understanding of declaring the local variables
and their use in a Bash script.

• This program will define two variables: one inside the function and the
other outside it.
• Both of these variables will have an identical name, i.e., $tmp.
• The key point to note here is that since one of the $tmp variables is inside
the function and the other $tmp variable is outside the function, they will
not affect each other, even if they have an identical name.
• Thus the $tmp variable inside the function will not affect the $tmp
variable outside the function.
• The local variable is only available to the function and its children
(associated functions which the said function may call). It doesn't affect
the global state of the caller.
• When we define a local variable of a similar name as the global variable
inside the function body, it takes precedence over the global variable.

Problem D

Use functions in a Bash script to show the recursion of a number till it reaches the
maximum value of 5.

278

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Learning Outcome: This exercise will allow you to understand recursion


better, saving you time from the hassle of writing the same script repeatedly.

• First, we need to decide the base case for the recursion. We will add
declare -i counter=0 in the beginning.
• The declare command in Bash allows you to update the attributes applied
to the variables in your script. Additionally, you can use it to declare a
variable.
• Now, wrap the recurse command in the function with an if statement for
limiting the recursion.
• We define the condition of the if statement as $counter -lt 5.
• The function will recurse as long as the counter is less than 5.
• We need to increment the count to ensure that it is increasing. Thus, we
will add ((counter++)). Add it before the recurse command.
• A common mistake done by many is adding incrementation after the
recurse command. If you add ((counter++)) after the recurse command, it
will be of no use. It is so because the script will keep recursing before it
reaches the incrementation. The count will never increase, and shell will
never exit the recursion.

279

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Problem-A Solution

Pseudocode

The following is a simple program that will pass multiple arguments to the shell
and return the values later.

Define the function name()


{
Pass argument number 1 to the function
Pass argument number 2 to the function
}

invoke the function and assign values to argument 1 and argument 2

Define the function name()


{
assign local value to argument 1
assign local value to argument 2
assign local sum = arg 1 + arg 2
return the value of local sum
}

Define the function name()


{
Pass argument number 1 to the function
Pass argument number 2 to the function
return the value of sum

280

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

}
assign value to n1
assign value to n2
invoke the function by assigning values n1 to argument 1 and n2 to
argument 2
Display the result

Flowchart

281

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Script

function foo(){
echo $1
echo $2
}

foo 10 20;
foo john doe

function foo(){
local a=$1
local b=$2
local sum=$((a + b))
return $sum;
}

function foo(){
echo $1
echo $2
return $(($1+$2));
}

n1=10
n2=20
foo n1 n2;
echo "$n1 + $n2 = $?";

Output

10

20

10 + 20 = 30

282

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Problem-B Solution

Pseudocode

The following is a program that will display 8 as the return status of the function.

Define the function name (){


Use echo statement to pass argument number 1 to the function
Use the return variable to specify the function's status = 8
}
Invoke the function with User
Invoke the function with Reader
Use the $? variable to display the stored return value.

Flowchart

283

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Script

#!/bin/bash
func_stat () {
echo Greetings $1
return 8
}

func_stat User
func_stat Reader
echo “The previous function returned a value of $?”

Output

Problem-C Solution

Pseudocode

The following program will declare two variables with a similar name – one local
and one global, and assign the value 10 to the local variable and 4 to the global
variable.

Define the function name(){


define the condition for the local variable inside the function $tmp
display the value of the local variable $tmp
}
Assign the value to the global variable=4
Invoke the function

284

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Display the value of the global variable tmp.


Flowchart

Script

#!/bin/bash
myfunc() {
local tmp=$(($tmp + 10))
echo "The Temp from inside the function is $tmp"
}
tmp=4
myfunc
echo "The temp from outside is $tmp"

Output

285

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Problem-D Solution

Pseudocode

The following script will recurse a number until it is less than 5 and will stop
executing when the number reaches the value 5.

Use the declare command to decide the base case for the recursion, i.e.,
counter=0
define the function name()
{
increment the counter
define the condition (counter less than 5) inside the if statement
then
display the value of the counter
invoke the function
fi
}
invoke the function

286

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Flowchart

Script

declare -i counter=0
script_recurse()
{
((counter++))
if [ $counter -lt 5 ]
then
echo $counter
script_recurse
fi
}

script_recurse

287

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Output

Exercise:

Below are some additional examples for your practice, which will help bring
further clarity about iterations.

Exercise A: In problem D given above, write a program to remove the declaration


of counter and simply pass a parameter into the function.
script_recurse()
{
if [ $1 -lt 5 ]
then
echo $1
script_recurse $(($1 + 1))
fi
}
script_recurse 1

288

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Exercise B: Write a program to return a value of 55 for the function class


average.

#!/bin/bash
class_function () {
echo "class average"
return 55
}
class_function
echo $?

Exercise C: Use function in a Bash program to allow the user to enter two
numbers and print their sum.

#!/bin/bash
func_addition(){
sum=$(($1+$2))
return $sum
}
read -p "Enter a number: " inp1
read -p "Enter a number: " inp2
add $inp1 $inp2
echo "The result is : " $?

Final Words

In this chapter, we have covered the various types of functions that you, as an
aspiring Bash programmer, must be aware of before writing meaningful scripts
containing functions. These well-explained examples will help students gain

289

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

confidence about writing scripts on any scenario – be it declaring an argument,


setting up a return value, or a recursive script.

290

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

References

1. Javatpoint, "Bash Functions", from:


https://www.javatpoint.com/bash-functions

2. Likegeeks, "Local Variables," from:


https://likegeeks.com/bash-functions/#Local-variables

3. Michael-Herbst, "Advanced Bash Scripting," from:


https://michael-herbst.com/teaching/advanced-bash-scripting-
2017/advanced-bash-scripting-2017/notes.pdf

4. Amayem, "Bash recursion examples," from:


http://ahmed.amayem.com/bash-recursion-examples-and-experiments-
with-local-variables/

5. Linuxize, "Bash functions", from:


https://linuxize.com/post/bash-functions/

6. Hostinger, "Bash functions tutorial with examples," from:


https://www.hostinger.in/tutorials/bash-function-tutorial-with-examples/

291

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Chapter 19

Bash Script: File Handling Commands in GitBash


Writing a Bash script is not only about performing arithmetic operations or
building recursive scripts. In advance Bash scripting, file handling plays a
crucial role in completing administrative tasks. This chapter discusses some file
handling and directory commands.

We have covered a long way in learning Bash scripting. In the previous chapters,
we covered the basics and conditional operators. Then, we moved to the
intermediate level and learned about functions and iterations in Bash scripts. Next
in the ladder comes advanced scripting, which involves learning about
administrative and file handling commands. What if you wrote a script and wanted
to locate it quickly? Or you wanted to change its contents without opening it? We
cover these topics in this chapter, addressing various file handling operations in
GitBash.

Read a File

Suppose you have a file named carcompany.txt, which includes the following
content:

Audi

292

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Volkswagen

Mercedes

BMW

Hyundai

How to read file content directly from the command line?

To read carcompany.txt line by line without using the cat command, you need
to run the following command:

$ while read line;


do
echo $line;
done < carcompany.txt

The while loop in the above command will read from the file carcompany.txt
line by line and store it in the $line variable. It will print the content later.

How to read the file content using Bash script?

You can write the following code to read the contents of carcompany.txt.

#!/bin/bash
file_name='carcompany.txt'

293

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

n=1while read line;


do
echo "Line No. $n : $line"n=$((n+1))done <
$file_name

The $file_name variable will store the existing filename, and the $n
variable will maintain the value of the line number. The output of the above
script:

If you run the carcompany.txt file with the cat command, the terminal will
display its original content.

Create a New Directory

You can create a new directory in Git Bash by using a simple command. It is
the same command used in Linux systems too. To create a new directory in Git
Bash:

• Open Git Bash.


• Open the directory where you wish to add a new folder. (Bashtutorial)
• Type the command mkdir <folder name>.

294

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

• Press enter, and you have created a directory!


• Note: If you do not add quotation marks for folder names with two
words, Git Bash will create two directories, for example, Sample and
Folder for the code given below.

View all the directories

Now that we have created a folder successfully, we must know how to view the
folder inside the working directory. Following are the steps to view all
directories:
• Navigate to the working directory (Bashtutorial)
• Type the command Is.
• Press enter. You can now see all the directories.
• If your directory contains hidden folders, you need to use the command
Is -a.

Remove a directory

In the previous example, we needed to create only one folder with the name
'Sample Folder,' but the Is command shows two folders. So how to delete the
extra folder. Simply write the rmdir <filename> command. The example
is shown below. To create the required folder, we need to enclose the sample
folder in quotation marks.

295

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Write to a File

Whenever you run a command in the Bash shell, it prints the command's output to
the terminal, and you can read it immediately. However, you can also redirect it to
a Log file from where you can review it later. You can either use the > (right angle
bracket sign) or >> (double right-angle sign).

a) > (right angle bracket sign): It is used for writing the command output to a
disk file. It will create a file if there is no file with the name you specified.
However, if the specified filename is present, it will overwrite its contents.
b) >> (double right-angle sign): It is used for writing the command output to a
file and then appends the output to the file's existing contents. It will create
a new file if the one with the specified name is not present.

Technically, both the > and >> operators redirect the standard output (stdout) to a
file. Here are the instructions for when to use these operators:

• When you are writing the file the first time and want the file to be fresh,
without any previous data, use the > sign. It will overwrite any previous data
in the file.
• You can further use the >> sign for appending the data to a file.

For example, We will use the Is command in conjunction with the > sign. Instead
of printing the complete file and folders list to the screen, the Is command, coupled
with > will save the output on the specified file name.

Bash Script

296

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

#!/bin/bash
output=output_file.txt
ls > $output
[edit or gedit] output_file.txt

Output:

As seen above, the Is command redirects the output into a file. For printing the
file's contents to the terminal, you can use the cat command as shown below:

Bash Script

#!/bin/bash
output=output_file.txt
ls > $output
cat $output

Output

297

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

If you don't want to delete the available data in a file but want to redirect multiple
command outputs to it, then use the >> operator. In the following example, we will
append the system information in the specified file.

Bash Script

#!/bin/bash
output=output_file.txt
ls > $output
uname -a >> $output
[edit or gedit] output_file.txt

Output

298

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

You can repeat the process multiple times for appending the output towards the
file's end.

Append to a File

We have already seen how to use >> operator to append a file. Another way to
append to a file is by using the tee command. The tee command can be used to
both read from the standard input and write to the standard output and multiple
files simultaneously.

• The tee command will overwrite the specified file by default. For appending
the output to the specified file, you can use -a(--append) with tee:

echo "this one is the new line" | tee -a file.txt

• You can redirect it to /dev/null if you don't require tee to append to


standard output.

echo "this one is the new line" | tee -a file.txt


>/dev/null

299

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

• If you want to append to multiple files, specify them as arguments following


the tee command.

echo "this one is the new line" | tee -a file.txt


file1.txt file2.txt

The advantage that the tee command has over >> operator is that it allows users
to append to multiple files.

Update a File

Bash offers you the ability to edit files without opening them. You can use the sed
command to find and replace text in the file.

Syntax:

sed OPTIONS... [SCRIPT] [INPUTFILE...]

Example:
Consider the following text file as input.

$cat > samplefile.txt

unix is a great os because unix is opensource.


Another advantage of unix is that it is a free os.

learn operating system.

unix or linux which one will you choose.

unix is super easy to learn and unix is a multiuser


os. Learn unix because unix is powerful.

300

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

• If you want to replace or substitute a string in the above file, use the sed
command. Replace unix with linux:

$sed 's/unix/linux/' samplefile.txt

"s" will specify the substitution operation and / are delimiters. "Unix"
refers to the search pattern, and the replacement string is "Linux".

Output

linux is a great os because unix is opensource. Another advantage of unix


is that it is a free os.

learn operating system.

linux or linux which one will you choose.

linux is super easy to learn and unix is a multiuser os. Learn unix because
unix is powerful.

The key point to note here is that the sed command will only replace the
pattern's first occurrence in every line and not the subsequent occurrences.

Other File Handling Commands

• Copying files
System administrators need to regularly copy files and directories from one
location to another in the filesystem. They can use the cp command to
achieve this smoothly. It will use two parameters in its basic form: the
source and destination object. The syntax is as follows:

301

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

cp source destination

• Renaming files
In a Bash script, renaming files is also called moving. You can use the mv
command to move files and directories from one location to another.
Moving the file will change its filename, but the timestamp value and inode
number will remain the same.

Exercise:

Exercise A: Write a bash script to track the number of times the current script
is executed. Use an external file to keep the number (Hint: You need to ensure
that you can write to and read from the file)

Exercise B: Write a bash script to copy the text files (.txt extensions) in the
current directory to a subdirectory called textDir in the current folder. Your
script should create the textDir if the directory doesn’t exist.

302

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Exercise A Solution:

Before wring the script, you need to create a file and the
initial number in the file and save it.

- Create a file called counter.text


- Enter number 1 and save the file.

#!/bin/bash
COUNTER_FILE="counter.txt"
count=`cat $COUNTER_FILE`
((count++))
echo $count > $COUNTER_FILE
echo $count;

Exercise B Solution:

#!/bin/bash
if [ ! -d "textDir" ]
then
echo "Directory doesn't exist. Creating now"
mkdir "textDir"
echo "Directory created"
fi
echo "Moving text files to TextDir"
mv *.txt textDir

Final Words

Thus, we have seen the basic file handling and directory commands in this chapter.
These commands are inclined towards the advanced side and are easy to grasp
once the student has completed the basic and intermediate chapters.

303

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

References

1. Fahmida Yesmin, "How to read file line by line in Bash script", from:
https://linuxhint.com/read_file_line_by_line_bash/

2. ToolsQA, "Common Directory commands on Git Bash", from:


https://www.toolsqa.com/git/common-directory-commands-on-git-bash/

3. Wisdom Jobs, "File Handling in Shell Scripting", from:


https://www.wisdomjobs.com/e-university/shell-scripting-tutorial-174/file-
handling-in-shell-scripting-2972.html

4. Cyber Citi, "Search for files in Bash", from:


https://www.cyberciti.biz/faq/search-for-files-in-bash/

5. Javatpoint, "Bash Write File", from:


https://www.javatpoint.com/bash-write-file

6. Geeksforgeeks, "Sed command in linux", from:


https://www.geeksforgeeks.org/sed-command-in-linux-unix-with-examples/

304

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Chapter 20

Advanced Examples On File Handling In Bash


In the previous chapter, we saw how different file handling commands could
help users perform complex administrative and file editing tasks with ease. This
chapter will cement our knowledge of the file handling commands by solving
some interesting questions related to file handling in Bash

You will often encounter situations where you will need to use the file
handling commands. It can either be checking if a file exists or not, create a
new directory, move files to different folders, or delete files. The bash shell
offers you the option to use various commands to manipulate the file system.
The most crucial file handling command is mkdir, which is used for creating
new directories. The mv command helps in situations where you need to move
multiple files to a new directory. Additionally, if you have created a wrong file
or delete a particular file to free up disk space, the rm command comes in
handy. We discuss these essential file handling commands in this chapter, with
detailed discussions, pseudocodes, and flowcharts for a deeper understanding of
the topic.

305

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Practice Problems
Problem-A

You have downloaded many of your favourite instrumental songs from the
internet, and now you want to save them in a new directory. Write a Bash script
demonstrating how you can create a new parent directory

'music/instrumental/best' (best is the directory you want to create)

• The current working directory in Bash is the one from where you will run
the commands.
• According to the problem, you need to create a new directory in the
directory "music"
• You will need to provide the relative or absolute path to the parent directory
if you need to create a directory in a separate location.
• In this case, you need to create a new directory in "music"
• Thus, you will write:
mkdir music/newdir
• You will get the error "Permission denied" if you try to create the directory
in the parent directory where you don't have permission to create a file.
• In Bash, the parent directory is the one that is above other directories in the
directory tree.
• To create the directory mentioned in the question, write:
mkdir music/instrumental/best
• If any of the above-mentioned parent directories don't exist, you will get an
error:

306

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

mkdir: cannot create directory


‘music/instrumental/best’: No such file or
directory
• Thus, you will think that you need to create all the missing directories one
by one. Thankfully, Bash provides you with a simpler way.
• Instead of writing separate codes to create the missing directories one by
one, you can use the mkdir -p command:
mkdir -p music/instrumental/best
• However, it would help to be careful when invoking mkdir with -p. With the
-p option, mkdir will only create a new directory if it doesn't exist.
• If you don't invoke mkdir -p and try to create a directory that already exists,
it will throw an error. For example:
mkdir best
mkdir: cannot create directory 'best': File exists

Problem-B

You are running a teaching institute and want to organize the teaching
content according to various courses. Write a Bash script to create a folder
structure for the lessons taught in your institute: Science, Maths, Applied
Mathematics, English, and Social Science. Each folder must contain sub-folder
named slides, observations, notes, past papers.

• We will create the directories (folders) using the mkdir -p command already
discussed in the previous example.
• Use your favourite editor to create the file by the name of
coursematerial.bash

307

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

• The mkdir -p command will allow the creation of folder/subfolder.


• You can use / to delineate the folders and sub-folders with respect to the
command.
• Remember, there should be no spaces in the folder names so you can use _.
For example, for the subfolder named past papers, you can use past_papers.
• It will give you five folders named Science, Maths, Applied Mathematics,
English, and Social Science. Each folder will contain sub-folders named
slides, observations, notes, past papers.

Problem-C

It's Binge-watch season, and you are downloading the episodes of your
favourite shows Gotham and Arrow and saving them to the "downloads" folder.
Write a Bash script that will run when the downloads complete, look for specific
file names in the "downloads" folder and move them to a different directory based
on the file name.

• We will use the mv command, which is short for move, to solve the above
problem. It is used for renaming and moving files from one location to
another. Its syntax is:
mv [OPTIONS] SOURCE DESTINATION
• The SOURCE will represent one or multiple files/directories.
• DESTINATION will represent a single file/directory.
• If you give multiple files or directories as the SOURCE, you must specify a
directory as the destination. We are moving multiple files from the
"downloads" folder to the specified directory in our problem.

308

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

• If you specify single files for both SOURCE and DESTINATION, then the
script will rename the file.
• If the DESTINATION is non-existent and you specify SOURCE as a
directory, the script will rename the SOURCE to DESTINATION. If the
DESTINATION exists, the SOURCE will be moved inside it.
• A crucial point to consider is that you must have write permissions for
SOURCE and DESTINATION; otherwise, you will get a permission denied
error.
• We need to move files in the downloads folder to the TVshows/ folder.
• First, we will use the cd command to change the working directory to
downloads.
• We will then use the for loop and invoke the mv command to move each file
("$filename") to its respective episode directory.
• It is crucial to include the / after destination. If the script detects that the
destination directory doesn't exist (because of misspelling), it will create the
directory as a file.

Problem-D

Suppose while downloading the episodes of "arrow," there was an internet


disruption, and you could only download one episode. There's no use in watching a
single episode, right? Write a Bash script to remove the file "arrowep1.avi," which
sits in TVshows/arrow/.

• We have learned in the earlier chapter that the rm command helps us remove
any file. So, we will use the rm command to delete the file.

309

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

• First, we need to change the working directory to TVshows/arrow/ using the


cd command
cd <From Current Directory To>TVshows/arrow/
• Then we will run the bash script, which we will create.
• You can name the file as remove_file.bash
• It will allow the user to input the filename which he wants to remove.
• You can add the -i command after rm to request the user permission when
removing the file.
• For running the command, you can first invoke ls. It will display all the files
in the folder "arrow."
• Then, execute the file "remove_file.sh" which you created.
• You can again invoke the ls command to check if the required file is deleted.

Problem-A Solution

Pseudocode

Program to create a new parent directory.

Start

- Use the cd command for navigating to the required working directory.


- Invoke the mkdir command with -p to create the required parent
directory list.

End

Flowchart

310

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Bash Script

#!/bin/bash
cd "/home/e”
#Replace /home/e with music parent directory."
mkdir -p music/instrumental/best

Output

311

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Problem-B Solution

Pseudocode

Program to create multiple directories with sub-folders inside them.

Start

- Invoke the mkdir command with -p. (Use commas to separate the
folder names and / to separate the list of subfolders within the created
directories)

End

Flowchart

Bash Script

#!/bin/bash

312

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

mkdir -p
{Science,Maths,Applied_Mathematics,English,Social_S
cience}/{Slides,Observations,Notes,Past_papers}

Output

Problem-C Solution

Pseudocode

Program to move multiple files to required directories according to file names.

313

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Start

- Use the cd command for navigating to the working directory.


- Open the for loop to enter the file name.
- Open case statement within the for loop
▪ Invoke the mv command to define case 1 (moving files with the
name gotham)
▪ Display result “Moved file to $home/TVshows/gotham”
▪ Invoke the mv command to define case 2 (moving files with the
name arrow)
▪ Display result “Moved file to $home/TVshows/arrow”
▪ Define the final case statement
- End the case statement
- End the for loop

End

Flowchart

314

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Bash Script

#!/bin/bash

cd "$home/Downloads"
#Replace $home with Downloads and TVShows parent
directory."
#!/bin/bash

for file_name in *;

do

case "${filename,,*}" in

gotham*) mv "$file_name"
"$home/TVshows/gotham/" ;;

echo “Moved file to $home/TVshows/gotham”;

arrow*) mv "$file_name" "$home/TVshows/arrow/"


;;

echo “Moved file to $home/TVshows/arrow”;

*) echo "don't know where to put $filename";;

esac

done

Output

315

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Problem-D Solution

Pseudocode

Program to remove a file from the specified directory

Start

- Display "Enter the filename to remove"


- Read the input from the user.
- Invoke the rm command with -i (to take permission from the user when
removing the file).

End

Flowchart

316

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Bash Script

#!/bin/bash
echo "Enter the filename to remove"
read filename
rm -i $filename

Output

317

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Problems to Solve

1) Write a code to check whether a given directory exists before using the mkdir
command to create a new directory. (hint: use the -d command)

2) You have a file named Learning_Bash.txt, which contains the following


chapters:
Basics
Operators
Functions
Iterations
Use the read command to read the contents of the file

3) Use the file test operator (-f) to check if a file exists or not. (Hint: input the file
name from the command line)

318

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Solutions

Q1-Solutions

Bash script for file name check_directory.sh

#!/bin/bash
echo "Enter the directory name"
read name_dir
if [ -d "$name_dir" ]
then
echo "Directory exists"
else
`mkdir $name_dir`
echo "Directory is created"
fi

Run check_directory.sh from the command line, and you will get the
following output.

Q2-Solutions

Bash script for file name read_text.sh

319

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

#!/bin/bash
value=$(<Learning_Bash.txt)
echo "$value"

Run read_text.sh from the command line, and you will get the following
output.

Q3-Solutions

Bash script for file name file_exist.sh

#!/bin/bash
file_name=$1
if [ -f "$file_name" ]; then
echo "File exists"
else
echo "File does not exist"
fi

Run file_exist.sh from the command line, followed by the file name you
want to search, and you will get the following output.

320

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

Final Words

We have dwelled upon the various file handling commands which you can use to
manipulate the file system. The interesting examples with detailed discussions and
graphically illustrative flowcharts will surely make learning these commands a fun
experience.

321

Troy Benson - [email protected]


THE BASICS OF A COMPLICATED CONCEPT (PROGRAMMING LOGIC)

References

1. Linuxize, "How to move files in linux with mv command." from:


https://linuxize.com/post/how-to-move-files-in-linux-with-mv-command/

2. Pietro, "Create multiple folders and subfolders from bash script" from:
https://pietropassarelli.com/bash_script.html

3. Stack Overflow, "SH script to move files from one dir to another depending
on the filename" from:
https://stackoverflow.com/questions/7573815/sh-script-to-move-files-from-
one-dir-to-another-depending-on-the-filename

4. Ask Ubuntu, "How to make a shell script to move files to individual folders
based on the filename?" from:
https://askubuntu.com/questions/1188803/how-to-make-a-shell-script-to-
move-files-to-individual-folders-based-on-the-file

5. Linux Hint, "30 Bash Script Examples" from:


https://linuxhint.com/30_bash_script_examples/#t23

322

Troy Benson - [email protected]

You might also like