CSC 201 New Lecture Note
CSC 201 New Lecture Note
Late 1600’s - Leibnez extended Pascal’s design to include multiplication and division
Early 1800’s - Workers feared mechanical devices would take their jobs
- Ned Ludd organized groups to destroy machines (“luddite”ex/ Ted
Kazinski)
Mid 1800’s - Charles Babbage invented the difference engine that had multiple step
application (early program) & designed the analytical engine.
- Hired Ada Byron, first programmer and daughter of Lord Byron
1
Theory - Largely comprises of mathematics (algorithms, formal proofs, theoretical boundaries of
computing, etc) -- some scientists in this field rarely even touch a computer.
Hardware - Designing and building CPUs (Central Processing Units), Memory cards (RAM,
ROM, Flash), Networking (Routers, NICs (Networking Interface Cards)), Graphics Cards, Hard
Disk Drives (HDDs), etc. This field is also called "Computer Architecture."
Software - Creating practical, real-life programming based on the concepts studied in classes
such as ours. "Software Engineering" is the most popular field for those studying programming.
Systems - This field comprises both Operating Systems (OSs) and their administration as well as
aspects of computer security and interoperability between systems.
AI (Artificial Intelligence) - One of the younger fields of Computer Science, it includes Model
Learning, Predictions, Machine Learning, Natural Language Processing, and Planning.
Programming Languages & Compilers - The theory and design of creating languages used by
computers.
In 1945, a German scientist named John von Neumann working at the University of
Pennsylvania codified the basic structure of modern computer architecture. He proposed the
stored program concept that says that a program can be electronically stored in binary-number
format in a memory device so that instructions could be modified by the computer as determined
by intermediate computational results. In other words, a stored-program computer includes, by
design, an instruction set, and can store in memory a set of instructions (a program) that
describes the computation.
C = Computer
CC = "Central Control" unit, presently part of the CPU but other functions lie on the
2
motherboard
I/O = "Input / Output" devices (Printers, keyboards, mice, computer screens, NICs,
HDDs)
M = Memory (RAM)
BINARY COMPUTING
Ultimately, the fundamental unit of computer science is the "bit", or "BInary digiT."
Where we can think of this Bit as being a digital representation of either a Zero or a One (0/1) it
can also mean "Off" or "On", "Closed" or "Open," "False" or "True."
A single bit can represent two values, either 0 or 1. By stringing bits together into larger
sequences you can represent even larger values. The number of "bits" concatenated together is
represented by the use of a carat (^) signifying "powers of two":
The practical unit of computer science is the "byte", which is comprised of 8 bits (2^8) and can
represent up to 256 values (0 thru 255)
To compute a number from a string of binary digits we needs to multiply each 0 or 1 by ever
increasing powers of two (2^n) starting with zero on the far right.
2. 11.112 to decimal
= [1 * (21)] + [1 * (20)] + [1 * (2-1)] + [1 * (2-2)]
= [2] + [1] + [1* (1/2)] + [1* (1/4)]
= 2 + 1 + 0.5 + 0.25
11.112 = 3.7510
3
We can also add and subtract using traditional rules:
00101012 5
+0101102 +22
---------- -----
011011 27
1
3 15 78
+ 4 58
---------
4 2 48
1
3 1B C16 note B = 11, C =12, D = 13, F = 15
+ 4 D F16
---------------
8 9 B16
Programming
Computer science is centered on programs. The study of networks only exists because we want
programs that communicate over networks; the study of artificial intelligence only exists because
we want programs that exhibit intelligent behavior; and so on. The writing of programs and the
languages in which programs are written is a key concern for any computer scientist.
Fundamentally, we are going to study how programming languages "work", i.e. how it is that a
programmer writes code using high-level constructs, load and store in the computer then the
logic/arithmetic instructions of assembly languages, can translate it into machine instructions.
We rely on this kind of thing every time we write a program, and the theoretical principles
behind how this is done shape the structure of all the languages we use.
At present there are literally thousands of programming languages. Some of the most popular
are: Java, C++, Perl, LISP, Python, Visual Basic (VB), Pascal, FORTRAN (Used in maths.),
4
COBOL (popular with business and old 'Mainframe' computers), and Assembly (A low-level
language interfacing with the hardware).
Programming Paradigms
A paradigm can be termed as the methods or ways of solving some problems or performing some
tasks. Programming paradigm is an approach to solving problem using some programming
languages. Or we can say, programming paradigm is the preferred approach to programming that
a language supports. It is a style or way of programming based on a set of basic principles and
concepts or it is a method to solve a problem using tools and techniques that are available in a
programming language following a particular approach. Each paradigm supports a set of
concepts that makes it the best for a certain kind of problem. Programming is a rich discipline
and practical programming languages are usually quite complicated. Solving a programming
problem requires choosing the right concepts and this is why programming languages should
support many paradigms.
A language should support many programming paradigms, so that the programmer can choose
the right concepts whenever they are needed without being encumbered by the others.
The major paradigms are imperative, declarative, functional paradigms and object-oriented.
5
Object-oriented The programmer writes a program that treats data Lisp, C++, C#, Java,
fields as objects manipulated through predefined Kotlin, Python PHP,
methods only. The data and the methods to Ruby, Scala,
manipulate the data are kept as one unit called an JavaScript
object. Thus, an object's inner workings may be
changed without affecting any code that uses the
object.
COMPUTER LANGUAGES
To write a program for a computer, we must use a computer language. Over the years computer
languages have evolved from machine languages to natural languages.
Machine Language
In the earliest days of computers, the only programming languages available were machine
languages. Each computer has its own machine language which is made of streams of 0‘s and
1‘s. The instructions in machine language must be in streams of 0‘s and 1‘s that way the machine
can directly understand the programs.
Advantages:
Disadvantages:
1) Machine dependent
6
Example Addition of two numbers
2 0010
+ 3 0011
--- ---------
5 0101
Advantages:
3) High efficiency
Disadvantages:
2) Requires translator
Example:
7
MOV RESULT, AL
High-Level Languages
The symbolic languages greatly improved programming efficiency but still required
programmers to concentrate on the hardware that they were working with. The programmer must
still do the hard work of translating the abstract ideas of a problem to the card readable and
machine-dependent notation of a program. A second shortcoming of assembly language is the
fact that each computer hardware requires its own machine language instruction set. Therefore
one assembly program written for a particular computer cannot be ran on another computer
without making changes to it. The desire to improve programmer efficiency and to change the
focus from the computer to the problems being solved led to the development of high-level
languages.
High-level languages are portable to many different computer allowing the programmer to
concentrate on the application problem at hand rather than the intricacies of the computer.
JAVA - Object oriented language for internet and general applications using basic C
syntax
Advantages:
4) Easy to maintain
5) Better readability
7) Easier to document
8) Portable
Disadvantages:
1) Needs translator
8
2) Requires high execution time
4) Less efficient
Example: C language
#include<stdio.h>
void main()
int a,b,c;
scanf("%d%d%",&a,&b);
c=a+b;
printf("%d",c);
Language Translators
These are the programs which are used for converting the programs in one language into
machine language instructions, so that they can be executed by the computer.
1) Compiler: It is a program which is used to convert the high level language programs into
machine code or bytecode. The name "compiler" is primarily used for software that translate
source code from a high-level programming language to a low-level programming language to
create an executable program. The compiler performs several tasks such as error detection and
prevention, flow control, syntax analysis, type checking, and optimization.
9
2) Assembler: It is a program which is used to convert the assembly level language programs into
machine language. An assembler is a program that takes basic computer instructions and
converts them into a pattern of bits that the computer's processor can use to perform its basic
operations.
3) Interpreter: It is a program that takes one statement of a high level language program,
translates it into machine language instruction one line at a time and then immediately executes
the resulting machine language instruction.
Compiler Interpreter
A Compiler is used to compile an entire An interpreter is used to translate each line
program and an executable program is of the program code immediately as it is
generated through the object program. entered
The executable program is stored in a disk for The executable program is generated in
future use or to run it in another computer RAM and the interpreter is required for each
run of the program
The compiled programs run faster The Interpreted programs run slower
Most of the languages use compiler A very few languages use interpreters.
Operating Systems
The operating system is a software portion of the computer system that manages all the hardware
and all other software. The operating system (OS) is the system software that manages the
computer hardware and software resources and provides common services for computer
programs. It controls every file, every device, every user, every section of main memory,
networking and the processing time. Every time a user sends a command on the computer, the
OS makes sure the command is executed and if there is a failure, the OS sends back a report to
the user.
10
User Interface
Memory Manager
Processor Manager
Device Manager
File Manager
Figure 1: Abstract representation of the operating system and its major components. (Mchoes &
Flynn, 2011)
The operating system is made up of the user interface, the memory manager, the processor
manager, device manager and the file manager.
The User Interface is the portion of the OS that users interact with. From the user interface you
can send a command from your keyboard which is displayed on the monitor. The two basic
functions of the UI is to take inputs from the user and to provide output to the user.
The GUI allows the user to interact with the operating system by a method of pointing and
clicking operations. The GUI includes icons, pictorial files, and shortcuts.
The CLI allows the user to interact with the operating system by typing commands on the
command line interpreter. The user would need to remember the right commands that give access
to the right location and file.
Another name for the UI is a shell. A shell is an interface between the user and the operating
system which allows users to run programs, manipulate file, and perform a number of other
operations. All OS use either a graphical shell or a text-based shell to run commands. Some have
both the graphical and the non-graphical shells.
11
Graphical shells are GUI used in Microsoft Windows and Linux Gnome while text-based shells
allow us to communicate with the OS with different commands. We have the command prompt,
PowerShell, and terminals.
Memory Manager
The memory manager is responsible for managing the Random Access Memory (RAM) which is
the main memory of the computer. It checks if the RAM size is large enough for a command or if
a memory location in the RAM is currently in use. It sets up a table which keeps tracks of who is
using which section of memory and reclaims the memory when the command is completed. It
also protects the space in main memory which is occupied by the operating system (OS).
Processor Manager
The processor manager is responsible for the decision of how the central processing unit (CPU)
is allocated. It also keeps track of the status of each computer process. A process could be
opening a document in a storage location or executing a program. The processor manager
monitors if the CPU is executing a process or waiting for a READ/WRITE command to finish
execution. It can be compared to a traffic controller.
12
Device Manager
The device manager monitors every device, channel or control unit. It is responsible for choosing
the most efficient way of allocating system devices and de-allocating system devices for a
process execution. System devices include printers, ports, disk drives etc.
File Manager
The file manager keeps track of every file in the system which includes the data files, program
files, compilers and applications. It also enforces restrictions on who has access to which file.
The file manager controls what a user is allowed to do with a file that they have access to. For
example a user can have read-only access, read-write access, create and delete access.
13
Types of Operating Systems (OS)
Operating Systems fall into five basic categories; they are batch, interactive, real-time, hybrid
and embedded system.
The batch operating systems date to the earliest computers that used stack of punched cards or
magnetic tape as input devices. In batch operating systems, users do not interact with the
computer directly. Each user prepares their job on an off-line device like punch cards and
submits it to the computer operator. The operating system collects the programs and data together
in a batch before processing starts. Then all jobs with similar needs are batched together and run
as a group.
An interactive operating system is a type of computer system that allows users to interact
directly with the operating system while one or more programs are running. Interactive systems
allow users to enter data or commands and view the results as their output. Programs such as
word processors and spreadsheet applications are interactive because the user interface in MS
Windows allows such interaction.
A real-time operating system (RTOS) is an operating system (OS) for real-time computing
applications that processes data and events that have critically defined time constraints. The real-
time systems were used in critical environment because they perform task within a tight time
boundary. They are used for space flights, airport traffic control, critical industrial processes and
for some medical equipment. Real-time operating systems have similar functions as other OS but
are designed so that a scheduler in the OS can meet specific deadlines for different tasks.
A hybrid operating system is a type of operating system that allows two operating systems to
execute on a single device. The two operating systems may be interactive operating system and a
batch operating system that fulfill different sets of tasks depending on their capabilities. They
appear to be interactive as users get fast responses but they run batch programs in the
background. A hybrid system takes advantage of the free time between processing to execute
another users command.
Assignment: The following are popular operating systems Windows, Linux, UNIX, QNX, Lynx
and Android. You are to come up with a table containing their different characteristics under the
following heading
14
b. File system structure
c. Security
d. Kernel
e. User Interface
f. Ease of use
g. Compatibility.
h. Scripting language
i. Type
Introduction to programming
A script is another name for scripting language, it tells the computer what to do. A scripting
language is a programming language that is interpreted rather than compiled. We earlier
discussed that some languages are compiled before execution while others are interpreted line by
line.
When a program written in a compiled language like C++ or Java is to be executed, the text that
represents the command of the program is processed through a compiler and turned into machine
code that is directly executed by the CPU. The output from the CPU is not human-readable
therefore any changes we would need to make to our command will involve compiling the code
again to produce a new executable file.
In interpreted languages like Python and Perl, the texts of our commands is read by the
interpreter that does the conversion to a machine code as it is running the script. The text is still
human-readable and does not have to be recompiled if changes are made to it. Scripting
languages have their own interpreters such as JavaScript and PHP. Python is an easy to learn
scripting language that is object-oriented with a large number of helper modules.
Bash Programming
A bash script is a plain text file that contains a series of commands. These commands are a
mixture of instruction that is run on the command prompt of a Linux terminal. The scripts is
typed on the gedit app and are saved in a file with a .sh extension (for example class03.sh). The
scripts are usually used by administrators to run several commands together on a Bourne Again
Shell (BASH). Before we can execute the script, the gedit file must have the execute permission
set. If this permission is not set before running the script, you will get an error message telling
you permission is denied. To change the permission on the script above, type the following
command at the location where the script is, at the terminal
15
chmod is a Linux operating systems command that is used to change the access mode of a file. It
will add execute permission for the user that owns the file. The name is an abbreviation of
change mode.
To write a script, you open the gedit and type the following commands.
#!/bin/bash
course="CSC201"
Line one is composed of two parts. The first part is ‘#!’ and is known as the shebang. It tells the
operating system that this is the line that specify the interpreter for the script.
The second part ‘/bin/bash’ shows that the interpreter is a bash shell which is located in the ‘bin’
folder.
The second line declares a variable called ‘course’ with a value stored in it.
The third line is the output line which uses the ‘echo’ command to print an output to the screen of
the computer.
Variables
A variable is a storage area that can be used to hold a value in a computer memory. This storage
area can easily be reused and the information that is stored in it can be changed that is why it is
called a variable. Variable names are case sensitive and can be defined in the following manner:
NAME=value
16
NAME defines the memory location while value defines the argument that is store in NAME.
The assignment token, =, should not be confused with equality, which uses the token = =. The
assignment statement gives a value to a NAME by binding a name, on the left-hand side of the
operator, to a value, on the right-hand side.
When defining a variable in Bash, the NAME and value must touch the equality sign (=). A
variable name must start with a letter; it should not begin with a number and must have at least
one alphabet. A variable name can be made up of letters, numbers and an underscore ( _ ). A
variable name should not be a reserved word like ‘echo’, ‘read’, ‘let’ etc. A variable is called
with the ‘$’ sign like in the example ‘$course’.
Types of Variable
Local variables are those that are in scope within a specific part of the program (function,
procedure, method, or subroutine, depending on the programming language employed).
Global variables are those that are in scope for the duration of the programs execution. They can
be accessed by any part of the program, and can be read write for all statements that access them.
Constants
Constants are values that are hard-coded into a program, and which do not change value. E.g.
"3.14159".
• Because of their inflexibility, constants are used less often than variables in programming.
• A constant can be :
17
4. While in the folder type the following commands to confirm the content of the folder and
to know if the script is executable. “ ls –l “. This will display all the files in the folder.
5. Then run the your script by putting “ ./ “ in front of the filename like so “ ./class03.sh “
then press enter on your keyboard.
The ./ command tells the interpreter to execute this script that is stored in this current
folder.
18
Running the hello code
To get an input from a user, we use the ‘read’ command. This command takes the input you type
on your keyboard and saves it as a value in your variable location. The read command can also
be used to get input from a file. The syntax is
read <variable_name>
19
#!/bin/bash
greetings=’Good morning’
read user
We can also enter more than one input using a single read command.
Arithmetic
Integer arithmetic can be performed using the built-in ‘let’ command. It can be written in this
format:
20
let <arithmetic expression>
When writing the let command there should be no spaces between the operand and the arithmetic
operator. For example,
let summation=3+6
echo $summation
Program Output
#!/bin/bash Enter two numbers
echo "Enter two numbers" 40 7
read num1 num2 Addition = 47
let addition=num1+num2 Sub = 33
let subtration=num1-num2 Mul = 160
let division=num1/num2 Div = 5
Mod = 1
let multiplication=num1*4
let modulus=num2%2
echo "Addition = " $addition
echo "Sub = " $subtration
21
echo "Mul = " $multiplication
echo "Div = " $division
echo "Mod = " $modulus
22
Please note you can click on these urls to run your bash code
https://www.tutorialspoint.com/execute_bash_online.php
https://www.mycompiler.io/new/bash
Control Statements
Control statements allow the programmer to control the flow of execution of the scripts based on
the outcome of a test statement. There are many control statements in programming languages
and they are mainly divided into conditional statements and looping statements. We have various
conditional operators that are used in conditional expressions; some are used for string variables
while others are used for numeric variables. Each operator returns true if the condition is met and
false if the condition is not met.
23
arg1 –eq arg2 -eq Numeric equality True if arg1 is equal to arg2
arg1 –ne arg2 -ne Numeric inequality True if arg1 is not equal to arg2
arg1 –lt arg2 -lt Less Than True if arg1 is less than arg2
arg1 –le arg2 -le Less than or equal to True if arg1 is less than or equal
to arg2
arg1 –gt arg2 -gt Greater Than True if arg1 is greater than arg2
arg1 –ge arg2 -ge Greater Than or equal to True if arg1 is greater than or
equal to arg2
Boolean Operators
Boolean operators combine two or more conditional operators. A Boolean operation can check if
multiple conditional operations are true or if one of the conditions is true.
Conditional Statements
Conditional statements allow you to change the way a program behaves based on the input
received, the content of the variable or any other factor. The most common condition statement
in bash is the “if” statement. There are several variants of the ‘if’ statement used for testing
various types of conditions. These variants are
Variant 1
if [test]
then
stmt …….
fi
Variant 2
if [test]
then
24
stmt 1…….
else
stmt2…….
fi
Variant 3
if [test]
then
stmt1…….
elif[test2] then
stmt2…..
else
stmt3…….
fi
When writing an’ if …then…else’ statement you can follow these rules
1. For an ‘if’ statement, put the condition inside square brackets, with spaces around the
brackets and the operators (such as equals)
2. Put quotes around the variables to keep them from being interpreted as multiple values in
case there is a space in the value.
3. You can put ‘then’ on a new line, or use a semicolon and a space
4. It is recommended to indent all statement within an if block
5. Put ‘else’ on a new line
6. Note that ‘if’ statements can be nested within each other.
7. Don't forget to finish the whole block with fi
Indentation
25
Programming Examples
Program Output
#!/bin/bash Hello, Sam
user1=Sam
if [ "$user1" = "Sam" ] [Execution complete with exit
then code 0]
echo "Hello, $user1"
fi
echo "Enter your name" Enter your name
read user1 Sam
if [ "$user1" = "Sam" ] Hello, Sam
then
echo "Hello, $user1"
fi
echo "Enter your name" Enter your name
read user1 Mabel
if [ "$user1" = "Sam" ] You are not Sam
then
echo "Hello, $user1"
fi
echo "You are not Sam"
echo "Enter a number between 0 and 5" Enter a number between 0 and 5
read num1 4
if [ $num1 -eq 5 ] Try again
then
echo "You entered the number, $num1" Enter a number between 0 and 5
fi 5
echo "Try again" You entered the number, 5
Try again
#!/bin/bash Enter a number between 0 and 5
echo "Enter a number between 0 and 5" You entered the number greater
read num1 than 5. Try again
if [ $num1 -le 5 ]
then Enter a number between 0 and 5
echo "You entered the number, $num1" You entered the number, 4
else
echo "You entered the number greater than
5. Try again"
fi
#!/bin/bash How old are you? 16
echo "How old are you?" You are not eligible to vote!
26
read age1
if [ $age1 -lt 18 ] How old are you? 18
then Kindly cast your vote!
echo "You are not eligible to vote!"
else How old are you? 24
echo "Kindly cast your vote!" Kindly cast your vote!
fi
echo "What was your exam score?" What was your exam score?
read score1 50
if [ $score1 -lt 50 ] You passed the course!
27
then
echo "You failed the course!" What was your exam score?
43
elif [[ $score1 -ge 50 && $score1 -lt 80 ]] You failed the course!
then
echo "You passed the course!" What was your exam score?
79
else You passed the course!
echo "You did excellently well!!!"
fi
What was your exam score?
80
You did excellently well!!!
#!/bin/bash Enter a number between 1 and 6
echo "Enter a number between 1 and 6" 4
read num1 You entered the number, 4
if [ $num1 -eq 1 ] Good game
then
echo "You entered the number, $num1"
elif [ $num1 -eq 2 ]
then
echo "You entered the number, $num1"
elif [ $num1 -eq 3 ]
then
echo "You entered the number, $num1"
elif [ $num1 -eq 4 ]
then
echo "You entered the number, $num1"
elif [ $num1 -eq 5 ]
then
echo "You entered the number, $num1"
elif [ $num1 -eq 6 ]
then
echo "You entered the number, $num1"
else
echo "You entered the number, $num1 Try
again"
fi
echo "Good game"
28
29
Looping
Often we would need to perform a repetitive action. that continues until a condition is met or
until all the data is processed. This type of operation is referred to as looping. The program
iterates through a list of values and continues executing the body of the loop for each element
until the list is empty. There are basically three types of loops in Bash, the for loop, while loop
and until loop
For Loop
The for…loop takes each element in the list, assigns the value to variable ‘var’, then executes the
commands between do and done. After execution, the program goes back to list and checks if
there are more variables left, then it performs the process all over again. This is repeated
processing is what is called iteration. Iteration in programming is a process where a set of
instructions executed repeatedly a specified number of times or until a specific outcome occurs.
Loops constitute the most common language constructs for performing iterations.
Program Output
#!/bin/bash List of Students
echo "List of Students" Paul
students="Paul Ali Sarah Ada Emeka Osas Angou" Ali
for studentname in $students Sarah
do Ada
echo $studentname Emeka
done Osas
Angou
#!/bin/bash 1, 1
echo "Range of Numbers" 2, 4
for num1 in {1..10} 3, 9
do 4, 16
echo $num1, $((num1**2)) #converting a string to numbers 5, 25
6, 36
done 7, 49
8, 64
9, 81
10, 100
30
#!/bin/bash Get even numbers
echo "Get even numbers between 0 and 10 and find their between 0 and 10
square" and find their
for num1 in {0..10..2} #Increasing from 1-10 step 2 square
do 0, 0
echo $num1, $((num1**2)) #converting a string to number 2, 4
4, 16
done
6, 36
8, 64
10, 100
While Loop
while [condition]
do
{ body }
done
A while…loop is a control flow statement that iterates over a block of code till the condition
specified evaluates to false. As soon as the condition becomes false, the loop exits, then the
command following the done statement is executed.
Program Output
#!/bin/bash Using while..loop
echo "Using while..loop" Enter your friends name
counter1=1 John
while [ $counter1 -le 4 ] My friends name is John
do Enter your friends name
echo "Enter your friends name" Mary
read friends My friends name is Mary
echo "My friends name is " $friends Enter your friends name
let counter1++ Joy
done My friends name is Joy
31
Enter your friends name
Frank
My friends name is Frank
#!/bin/bash Using while..loop for
echo "Using while..loop for factorial of a factorial of a number
number" Enter a number 7
echo "Enter a number" 6, 7
read counter1 5, 42
factorial=1 4, 210
while [ $counter1 -gt 0 ] 3, 840
do
2, 2520
let factorial=$((factorial*counter1))
1, 5040
let counter1--
echo $counter1, $factorial 0, 5040
done
Until Loop
until [condition]
do
{ body }
done
until...loop statement are used to execute a block of statements repeatedly until the condition in
an expression becomes true. The blocks of statements are executed until the expression returns
true. The until loop is similar to the while loop but with reverse logic. Instead of looping while a
condition is true you are assuming the condition is false and looping until it becomes true.
Program Output
echo "Program to determine university Program to determine university admissions
admissions" What was your Jamb score?
echo "What was your Jamb score?" 100
read jamb1 How many credits have you?
echo "How many credits have you?" 2
read credit1 100 2
echo $jamb1 $credit1 Kindly wait for next year
until [[ $credit1 -ge 5 || $jamb1 -ge 200 ]] Credits 3 , Jamb score 120
do Kindly wait for next year
echo "Kindly wait for next year" Credits 4 , Jamb score 140
let credit1++ Kindly wait for next year
let jamb1=$((jamb1+20)) Credits 5 , Jamb score 160
echo "Credits" $credit1 "," "Jamb score" Welcome to College
$jamb1
done
echo "Welcome to College"
32
Functions
Functions are for writing code that you can call later. Function calls can take different arguments
and create local variables. When a function is called, the commands within the braces are
executed. The purpose of a function is to help make bash scripts more readable and to avoid
writing the same code repeatedly. When a function is defined, the code inside the function won't
run until the function is called.
Functions improve the programmability significantly, for two main reasons. First, when you
invoke (call) a function, it is already in the computer’s memory; therefore it runs faster. The
other advantage of functions is that they are ideal for organizing long shell scripts into modular
"chunks" of code that are easier to develop and maintain.
The process of writing a function is called defining the function and you can define a function
using this format
function NameofFunc {
<commands>
You precede the definition with the word ‘function’, followed by the name you want to call your
function. This is followed by two curly braces that define the body of the function. The body can
contain any number of declarations, variables, loops, or conditional statements.
Program Output
#!/bin/bash Enter a number
function numbercheck 888
{ This number is even
if [ $(($avalue%2)) -eq 0 ]
then
echo "This number is even" Enter a number
else 234567
echo "This number is odd" This number is odd
fi
}
33
Principles of Good programming
The most important skill a programmer should have is the ability to solve problems. Problem
solving means the ability to originate problems, think creatively about solutions, and provide a
solution clearly and accurately.
A Program
A program is a sequence of instructions that specifies how to perform a computation. The
computation might be something mathematical, such as solving a system of equations or finding
the roots of a polynomial, but it can also be a symbolic computation, such as searching and
replacing text in a document or solving a complex engineering task.
When programming to solve any computation you would need to identify the following
parameters.
Input - the data you would be getting from the user, the server, the network, or any other device
that communicates with that program.
Output – the information your program would send back to the user, another computer, a
network, or any other device that receives information from the program.
Operations – the operational sequence of the program would be a serial execution of a task,
conditional execution of a task, or repetitive execution of a task.
Arithmetic Logic – Would the program perform mathematical calculations or logical operations
to achieve its objective?
Debugging
All programs have bugs whether these bugs can be easily identified or hidden until they are
exploited that is why large tech companies keep releasing patches and updates for their
applications.
Programming errors are called bugs and the process of correcting these bugs is called debugging.
There are different types of programming errors and they are
1. Syntax errors
2. Runtime errors
3. Semantic errors
Syntax errors
Syntax in computer programming means the rules that control the structure of the symbols,
punctuation, and words of a programming language.[] Syntax also refers to the structure of a
program and the rules about that structure. While Syntax error is an error in which the source
code for a program or function fails to adhere to the rules of the source language[]. Python is
known for its simple syntax, when the interpreters execute a Python program at runtime the
code will fail if the syntax is incorrect. When you run your Python program, the interpreter will
first parse it to convert it into Python byte code, which it will then execute
34
All programs can be executed only if they are syntactically correct. If the interpreter cannot parse
into byte code successfully, it means there is an invalid syntax somewhere in the code. The
interpreter will attempt to show you where that error is.
Syntax error can occur when
1. Inappropriate usage of an operator.
2. Misuse or missing Python keywords
3. Misuse or missing parentheses, brackets, and quotes
4. Wrong indentation
5. Improper definition of Functions
Runtime Error
A runtime error is a program error that occurs while the program is running. They are also called
exceptions because they usually indicate that something exceptional had occurred even when the
program is syntactically correct. They are discovered when a program is being executed and
Python normally indicates what type of exception has been raised by the interpreter.
Runtime errors or exceptions can occur when
1. Opening a file that is not found in a location
2. Dividing by zero
3. Import a module that is not found
4. When a variable does not exist or when a variable name is badly spelt
5. When there is a type mismatch.
Semantic Error
These are errors with a program that executes properly but doesn’t give the expected output. It is
also called logical errors because the logic of the output is different from its expected outcome.
This usually occurs when
1. Improper usage of operators
2. Improper definitions of loops
3. Incorrect usage of brackets in calculations
4. Using the wrong data type for an operation
5. Incorrect program design.
Data Type
Every variable has a data type. The value stored in a variable determines the data type
it gets. Data is stored in box-like locations in a computer’s memory. The size of the memory
space (box) a variable gets is referred to as a data type. If the value assigned to a variable has
decimal places you store that data in a float data type. If you want to store a series of characters,
numbers, and any other symbol within a single, double or triple quote you get a string data type.
If you store counting numbers without any decimal and without quotes, you get an integer.
Common Data Types
35
Data Type Represents Examples
integer whole numbers that can have -5, 0, 123
a positive, negative, or zero
value
floating point (real) Numbers that contain -87.5, 0.0, 3.14159
decimals and fractions
string A set of characters that can "Hello world!"
include spaces and numbers
enclosed in quotation marks.
Boolean Logical expressions that true(1), false(0)
compare values using
AND,/OR . Their output is
True or False.
nothing No data Null
Date, Time and Timestamp These data types are used to Year, Month, Day, Hour,
work with data containing Minute, Second and
dates and times Microsecond
36