0% found this document useful (0 votes)
2 views55 pages

Cte 114 Intro. To Computer Programming Lecture Note

A computer program is a set of ordered instructions that enables a computer to perform specific tasks, akin to a recipe with variables and statements. Programs can be categorized into low-level languages, which are closer to machine code, and high-level languages, which are more user-friendly and abstract. Additionally, computer programming involves writing, testing, and maintaining these instructions, with various types of language translators like compilers and interpreters facilitating the conversion of high-level code into machine-readable format.

Uploaded by

mosestommyedward
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)
2 views55 pages

Cte 114 Intro. To Computer Programming Lecture Note

A computer program is a set of ordered instructions that enables a computer to perform specific tasks, akin to a recipe with variables and statements. Programs can be categorized into low-level languages, which are closer to machine code, and high-level languages, which are more user-friendly and abstract. Additionally, computer programming involves writing, testing, and maintaining these instructions, with various types of language translators like compilers and interpreters facilitating the conversion of high-level code into machine-readable format.

Uploaded by

mosestommyedward
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

What is a Computer Program?

In computing, a program can be defined as a set of ordered instructions that enable the
computer to carry out a specific task. That is, it usually consists of many instructions that
tell the computer what to do.

A program can also be defined as a set of instructions written to perform a specified task
for the computer.

Generally, a computer program can be defined as a set of instructions that allows the
computer to carry out a specific task.

A program is like a recipe. It contains a list of ingredients (called variables) and a list of
directions (called statements) that tell the computer what to do with the variables. The
variables can represent numeric data, text, or graphical images.

John von Neumann in his outline of a modern computer indicated that, program contains
a one-at-a-time sequence of instructions that the computer follows. Typically, the program
is put into a storage area accessible to the computer. The computer gets one instruction
and performs it and then gets the next instruction. The storage area or memory can also
contain the data that the instruction operates on.

A program is prepared by first formulating the task and then expressing it in an


appropriate programming language.

Everything done on a computer is done by using a computer program. Without programs,


computers are useless. A computer requires programs to function, typically executing the
program's instructions in a central processor.

A computer program is written by a programmer. It is very difficult to write in ones and


zeroes, which is what the computer can read, so computer programmers write in a
programming language. Once it is written, the programmer uses a compiler to turn it into
a language that the computer can understand.

Class work:
1. Write a program that will assist your computerized robot in the cooking of jollof
rice. Tips: what are the things needed and how would you go about it.
2. Write a program that will assist your computerized robot to perform the task of dry
cleaning your cloths.

DEFINITION OF COMPUTER PROGRAMMING

1 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
Computer programming (often referred to as coding), is the process of writing, testing,
debugging and maintaining a set of instructions given to the computer for solving a
particular problem.

Computer Programming Languages

There are two major types of computer programming languages. These are Low Level
Languages (LLL) and High Level Languages (HLL). The LLL is further divided into Machine
language and Assembly language.

Low Level Languages


The term low level here refers to the closeness of the language to the language that the
computer understands and the remoteness of the language from from languages spoken
by human beings. Low level languages are machine oriented and require extensive
knowledge of computer hardware and its configuration. Low-level languages are further
classified into machine language and assembly language.

(a) Machine Language


Machine Language is that which is written in 0 (zero)’s and 1(one)’s. that is, it is expressed
as a combination of 0’s and 1’s. The 0’s and 1’s designates the electrical states in the
computer that is, on or off. It is the only language that is directly understood by the
computer. When this sequence of codes is fed to the computer, it recognizes the codes and
converts it in to electrical signals needed to run it. It does not need any translator program.
And it is the only language that has this characteristic. It is considered as the first (1st)
generation language. For example, a program instruction may look like this:
1011000111101
Advantages
1. Programs written in machine language run very fast because no translation
program is required for the CPU.
2. Storage space used for storing the program is minimized, thus storage is saved
3. User has direct control of machine instruction

Disadvantages
1. It is very tedious and difficult to program in machine language.
2. Programmer’s fluency is affected, thereby making the programs developed
inefficient.
3. The developed programs are error prone and difficult to debug.
4. It is machine dependent. A program written for one computer might not run in other
computers with different hardware configuration.

2 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
Assembly Language

This is a programming language in which instructions were written using mnemonics and
symbols. It was developed to relieve programmers the arduous task of writing in machine
language. Assembly language uses easy-to-remember commands that are more
understandable to programmers than machine-language commands. It is very much
similar to machine language but instead of writing in series of numbers, convenient
symbols and abbreviations are used and a translator program is required to translate the
Assembly Language to machine language. This translator program is called Assembler'. It
is considered to be a second-generation language.

Advantages:

1. The symbolic programming of Assembly Language is easier for programmers to


understand and thus saves a lot of time and effort of the programmer.
2. Use of assembly language lets a programmer interact directly with the hardware
(processor, memory, display, and input/output ports). This allows him to understand
the internal structure of the hardware and its registers.
3. It is easier to correct errors and modify program instructions than machine language.
4. Assembly Language has the same efficiency of execution as the machine level language.
Because this is one-to-one translator between assembly language program and its
corresponding machine language program.

Disadvantages:

1. One of the major disadvantages is that assembly language is machine dependent. A


program written for one computer might not run in other computers with different
hardware configuration.
2. The programmer has to remember a lot of codes to write a program which results in
program errors
3. Program development is slow as the programmer must have detailed knowledge of
the hardware structure.
4. Program maintenance is slow and error prone.

HIGH LEVEL LANGUAGES

High level languages are programming languages that use English like language that is
understandable to humans and mathematical symbols like +, -, %, / etc. for its program
construction.

While assembly language and machine level language require deep knowledge of computer
hardware, in HLL, all the programmer needed to know is how to contruct instructions in
English words and logic of the problem irrespective of the type of computer you are using.

Just like the assembly language, higher level language has to be converted to machine
language for the computer to understand. This is done using an interpreter or a compiler.

3 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
Higher level languages are also referred to as problem-oriented languages because the
instructions are suitable for solving a particular problem. Examples are: COBOL (Common
Business Oriented Language) which is mostly suitable for business oriented problems,
FORTRAN (Formula Translator) and BASIC (Beginners All-purpose Symbolic Instruction
Code), Java, C++ and so on.

Advantages of High Level Languages

1. One of the major advantages of HLLs is that they are not machine dependent. A
program written for one computer will run in other computers with different
hardware configuration.

2. HLLs also have a major advantage in that they are easier to understand and use
because that they are similar to the languages used by humans.

3. High level instructions are faster to code

4. Error detection and correction of the program is easier

Disadvantages of High Level Languages

1. More time is required to run the program as it has to be translated.

2. Machine code instructions are produced and that requires more storage spaces.

Language Translators
These are computer programs designed to convert programs that are not written in
machine language to machine codes, that is, into a form directly usable by a computer.
Common types of language processors are Assembler, Compilers and Interpreters.

1. Assembler:
This is a translator that convert program written in Assembly language to machine code
and vice-versa.

2. Compiler:

This is a translator that convert program written in High Level Language to machine code
and vice-versa, and the translation in done all at once. That is, it reads the entire program
first and then translates it into machine code.

4 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
The programs written by the programmer in higher level language is called source
program/code. After this program is converted to machine languages by the compiler it is
called object program/code.

It is this object code that is called executable code. A compiler can translate only those
source codes, which have been written, in that language for which the compiler is meant
for. For example FORTRAN compiler will not compile source code written in C++ language.
Also, an object code generated by the compiler is machine dependent. Thus, for a compiler
to achieve machine independence, it must be able to run on different machines. Examples
of HLLs that are translated using compiler are FORTRAN, C++, Java, COBOL, Visual Basic
e.t.c.

3. Interpreter:

This is a translator that convert program written in High Level language to machine code
and vice-versa, but the translation is done line by line. That is, interpreters reads one line
of program, translates it into machine language and immediately execute it, then it reads
second line, translates and executes it and so on.. Translation and execution are carried out
for each statement. It differs from compiler, which translate the entire source program into
machine codes before it does its execution. Example of language translated by Interpreter
is QBASIC.

Advantages of interpreter
1. Interpreter will execute all the lines before error and will stop at the line which
contains the error, thus an error is found immediately. So the programmer can
make corrections during program development.
2. Interpreters are easy to write and do not require large memory in computer since
no object code is generated
3. It is fast in its response to changes in the source program as it eliminates the need
for a separate compilation after changes to the source program

Disadvantages of interpreter
1. Program executes slowly as the interpreter translates the program line by line.
2. Interpreters cannot optimize the program or make it efficient since interpreter does
not produce an object program. They only read program line by line, thus they
cannot get the overall picture of the program.

Advantages of Compilers

5 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
1. Compiled program runs much faster than an interpreted program.

2. Compiled programs are optimized and are thus more efficient.

Disadvantages of Compilers
1. It is slow in its response to changes in the source program as it requires a separate
compilation for every change to the source program
2. Compilers use more memory space since object code is generated
3. Errors are not easily detected until after the compilation process

CLASSIFICATION OF COMPUTER PROGRAMS

Computer programs may be categorized along functional lines as system software and
application software.

System software is computer software designed to operate the computer hardware and
to provide a platform for running application software.

The most basic types of system software are:

1. The operating system

An operating system (commonly abbreviated as OS) is the software component of the


computer system that is responsible for the management and coordination of activities
and sharing of the limited resources of the computer. The operating system acts as a host
for applications that are run on the machine. As a host, one of the purposes of an operating
system is to handle the details of the operation of the hardware. This relieves application
programs from having to manage these details and makes it easier to write applications. It
performs tasks like:
• Controlling the allocation and usage of hardware resources such as memory,
Processor’s time, disk space, and peripheral devices.
• Transferring data between memory and disks
• Rendering output onto a display device.
The operating system is the foundation on which applications, such as word processing
and spreadsheet programs, are built. Prominent examples are Microsoft Windows OS such
as Windows XP, Windows 7; Mac OS, and Linux.

2. The Basis Input and Output System (BIOS)

6 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
BIOS is defined as the set of control software which drives the hardware devices in the
system directly. These types of programs are normally called device drivers, so in essence,
the BIOS is a collection of all the core device drivers used to operate and control the system
hardware . The operating system actually uses the drivers in the BIOS to control and
communicate with the various hardware and peripherals in the system.

The BIOS contains drivers for items that are built into the board (the actual BIOS code)
and usually a system setup program (often called the CMOS setup) for configuring the
system and the initial POST routine, bootstrap loader (which loads the operating system).

3. Utility software

Utility software are those programs that performs a very specific task, usually related to
managing system resources. They help to analyze, configure, optimize and maintain the
computer. Examples are: System restore, Disk cleanup, Disk defragmentation, (usually
found as options in System tools of Accessories pull-down menu). For instance, whenever
you write a file and save it to the disk, Compression Utility compresses the file
(reduce the file size) and write it to the disk and when you request this file from the disk,
the compression utility uncompressed the file and shows its contents. It is used to manage
memory spaces. Also, Disk Defragmentation utility is used to remove fragmentation on
the disk. The data is stored on the disks in chunks, so if we are using several files and are
making changes to these files then the different portions of file are saved on different
locations on the disk. These chunks are linked and the operating system knows how to
read the contents of file from the disk combining all the chunks. Similarly when we delete
a file then the place where that file was stored on the disk is emptied and is available now
to store other files. As the time goes on, we have a lot of empty and used pieces on the
disk. In such situation we say that the disk is fragmented now. If we remove this
fragmentation the chunks of data on the disk will be stored close to each other and thus
reading of data will be faster.

Application Software
Application software are programs that enable the end-user to perform specific, productive
tasks, such as word processing or image manipulation. That is, application software is a
subclass of computer software that employs the capabilities of a computer directly and
thoroughly to a task that the user wishes to perform.

Below are few examples of application software:

7 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
• Application Suite consists of multiple applications bundled together. They usually
have related functions, features and user interfaces, and may be able to interact
with each other, e.g. open each other's files. For instance, business
applications[Link] often come in suites, e.g.
Microsoft Office[Link]
[Link] which bundle together a word
processor, a spreadsheet, etc. Also suites exist for other purposes, e.g. graphics or
music.
• Enterprise software which addresses the needs of organization processes and
dataflow, often in a large distributed environment. (Examples include financial
systems, customer relationship management (CRM) systems and supply-chain
management software).

FEATURES OF A GOOD PROGRAM

1. Reliability: This refers to how often the results of a program are correct. This
depends on conceptual correctness of algorithms, and minimization of
programming mistakes, such as mistakes in resource management and logic errors
(such as division by zero or off-by-one errors). A program is said to be reliable if it
performs to its specifications under all conditions.
2. Robustness: This refers to how well a program anticipates problems not due to
programmer error. This includes situations such as incorrect, inappropriate or
corrupt data, unavailability of needed resources such as memory, operating system
services and network connections, and user error. That is, the ability of the Program
to easily detects errors. E.g. detection of typographical errors in word processing
package such as MS Word.
3. Usability: This is the ease with which a person can use the program for its intended
purpose, or in some cases even unanticipated purposes. This involves a wide range
of textual, graphical and sometimes hardware elements that that make a program
easy and comfortable to use. It can also be referred to as the ergonomics of a
program.
4. Efficiency/performance: the amount of system resources a program consumes
(processor time, memory space, slow devices such as disks, network bandwidth and
to some extent even user interaction): the less, the better. This also includes correct
disposal of some resources, such as cleaning up temporary files and lack of memory
leaks.
5. Portability: the range of computer hardware and operating system platforms on
which the source code of a program can be compiled/interpreted and run. This
depends on differences in the programming facilities provided by the different

8 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
platforms, including hardware and operating system resources, expected behavior
of the hardware and operating system, and availability of platform specific
compilers (and sometimes libraries) for the language of the source code.
6. Writability: this is the measure of how easily a language can be used to create
programs for a chosen problem domain. It refers to the expressivity. Expressivity
has to do with accomplishing a great deal of computation with a very small program.
7. Maintainability : this refers to the ease with which a program can be modified by
its present or future developers in order to make improvements or customizations,
fix bugs/errors and security holes or adapt it to new environments. That is,
constant maintenance and updating is a must so that performance can be
enhanced, bugs can be fixed, and additional features can be inserted.

STAGES OF PROGRAM DEVELOPMENT


Before computer program is successfully written, documented and installed, it must
have passed through some stages in which each stage has something to contribute to
the accomplishment of the whole task.
The stages are:
Stage 1: Problem definition:
Before any reasonable and meaningful program could be written, the problem that
prompted it must have to be defined. No one solves a problem he does not know. The
problem to be solved by computer should be well stated and understood before the
solution could be worked out. This entails having an idea of the expected output of
the solution to the problem and preparing the input to arrive at the output.
Stage 2: Develop the algorithm
This stage involves unambiguous stating of the procedures and steps necessary to
transform the input data into output since an algorithm is a well defined set of
instructions that is used to solve a particular problem in a finite number of steps. This
stage posses a little difficulty to the program planner but once accomplished
successfully, the rest of the solution follows easily.
Stage 3: Plan the logic of the program/flowcharting:
A flowchart is a pictorial view of the program logic. It is used to organize the thought of
the program planner and to check for any logic error or misrepresentation.
Stage 4: Write the computer program and Key in the program into computer
After the design or planning of the logic of the program using the flowchart, the next
stage is the actual writing of the program using any of the programming languages in a
proper sequence. This is called coding of the program. Coding is done by strictly obeying
the language syntax or the established rules of the programming language. This is

9 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
usually done by directly keying- in the program into the computer or writing it on
a sheet and later transferring it. Any program that will be executed by the computer
must be resident in the computer memory. The typing is generally made one line after
the other.
Stage 5: Execution
This is the stage where the computer process the program by converting it to the
machine language that the computer understands. This is also referred to as the
computer running the [Link] example, for a program written in QBASIC
programming language is executed using the command RUN or by pressing F5 on
the keyboard.

Stage 6: Test and debug the program:


This stage involves checking the program to see if it is working to expectation. If
any rule of the programming language is broken, the program will not work. The
errors must be removed before the program will start producing the output. Testing is
very necessary to ensure that the correct and required answers are produced as the
output.

Stage 7: Documentation
Documentation helps the user to understand the program better. It identifies exactly the
purpose of the program. It is always referred to whenever changes are to be made in the
program to suite new development. It contains the following parts.
1. A statement of the problem
2. Algorithm and program plans (ie flowchart, hierarchy chart or pseudocode).
3. Description of input and output
4. Program listing
5. Test data and results
6. Technical details and instruction for the user.
The program development stages illustrated in the diagram below;

Problem Definition

Algorithm
Development
10 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET
Not for Sale
PROGRAMMING BASICS

A. THE CONCEPT OF VARIABLE


In computing, a variable can be defined as a memory location where data is stored. That
is, it is a place in memory where data can be stored.
A variable has three essential attributes
1. a symbolic name also known as identifier
2. a data location in memory (which could be identified by length or address)
3. value represented by the data in the memory location
Note: Be careful not to confuse variables with identifiers
What is an identifier?
Identifiers are only the names given to variables but VARIABLES are the actual memory
location used to store data. Thus, we used identifiers to identify the particular memory
location.
Also, values of variables can vary just as its name implies but that of constants cannot
change. E. g PI= 3.142,

Types of Variable

11 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
1. Scalar variable: This is a type of variable that can only store one value. It identifies
just a single location in memory at a time. e.g. A=3
2. Array variable: This is the type of variable that stores multiple values, that is, it
identifies multiples locations in memory at a time. Here, auxiliary variables i, j ,k
are used along with the variable name.
e.g. A(i), where i ranges from 1 to 10
A(i), i= 1 to 10

A(1) A(2) A(3) A(4) A(5) A(6) A(7) A(8) A(9) A(10)
7 48 13 86 75 64 39 57 25 18

Meaning , A(2) = 48
A(7)= 39

Classification of Variables According to Data Type


Variables can also be divided into two types depending on the data type, that is, the type
of the information stored at the memory location, as numeric or string.
A string variable is a name representing a memory location which contains text or
character. String variable names must end with a dollar sign ($) and the value of the
string variable must be enclosed in quotation marks.
For example, Name$ = "John Smith"

Note: Strings can contain numbers, but when they do, mathematical formulas do not work
on the numbers as they would with numbers stored in variables designed for numbers.
For example, Value$ = "25"
Here, the value 25 is considered to be a text in this variable. And th4s, Value$ + Value$
would equal 2525 and not 50!

A numeric variable is a name representing a memory location which contains a number.


Numeric variables can either be integer or floating-point number. Floating-point refers
to numeric value with decimal point while integers are numeric values that does not have
decimal point. Integers could either be negative or positive whole numbers.

The following is a set of symbols which represent each variable type:

12 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
1. $ - String: this refers to non-numeric values such as text or character.
2. % - Integer: this refers to smaller integer values e.g 36, 235, -128
3. & - Long: this is also used for integer values and it refers to larger integer
values such as 36578, -873560, 436598
4. ! - Single: this is used for floating-point numbers. Single is used for smaller
numbers with a longer decimal place. For example, when using 3.1415 (pi),
one would express it's variable as a single variable.
5. # - Double: this is also used for floating-point numbers. Double are larger
numbers with smaller decimal places. For examples, 475213.64

This is expressed using the format below:


variable% - The % specifies the variable is an integer e.g ade%= 213
variable# - The # specifies the variable is a Double
variable$ - The $ specifies the variable is a String;
that is, the symbol are used as suffixes
e.g, Numb% = 4; Numbers# = 1027.25; brand$ = "Avon Lady"

Rules on Variable Names


Variables names for QBasic can be whatever fits into the following rules:
1. The first character must be a letter from the alphabet
2. After the first letter, a variable name can have letters, digits or underscores
3. Variable names cannot be words already used by QBasic (reserved) for other
Purposes
The following are valid variables:
Y, num, VALUE2, xYz_wed, abc123, Room_23
While the following are invalid variables:
23Chicago, PRINT, Room 23, Springsteen~45

Note: the principles of variable in programming do not directly correspond to the principles
of variable in mathematics.

For instance, the expression, X = X + 1, which means take the current value of X, add 1
to it and store the result back in X, would be termed to be incorrect in mathematics.

If a=5
a=a+1, means add 1 to the current value in a which is 5, thus a = 5+1=6
therefore, a=6
Exercices
If A=5, B=2, evaluate the following:
A=A+1

13 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
C=A-B
Result=C+A
Output A, B, C, Result
solution
A=5, B=2
A=A+1=5+1 = 6
C=A-B= 6 – 2 = 4
Result= C + A= 4+6 = 10. Therefore, A = 6, B = 2, C = 4, Result = 10
Class work

1. If X = 10, Y = 8, evaluate the following:


X=X+Y
Y=Y-5
Z=X+Y
OUTPUT X, Y, Z
2. If E = 5, F=13, evaluate the following:
F = F +E
E=E+2
G=F–E
OUTPUT E, F and G
3. If A = 20, B = 13, evaluate the following:
A=A+2
B=B+A+4
C=A+B
OUTPUT A, B and C

B. MATHEMATICAL EXPRESSIONS IN PROGRAMMING


An expression is a combination of variables, constants and operators written according to
the syntax of a particular programming language.

Operators and operands

Operators are special symbols that represent computations like addition and
multiplication. The values the operator is applied to are called operands.
Arithmetic Operator Representation In Examples
Programming
ADDITION: + + A+B
SUBTRACTION: - - A–B
DIVISION: / A/B

14 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
MULTIPLICATION: X * A*B
EXPONETIATION AB ^ OR ** A ^ B or A ** B

Examples: 20+32 hour-1 hour*60+minute minute/60 5**2 (5+9)*(15-7)

Exercise: Convert the following arithmetic expression to its programming representation:


1. Y = pqr(p+q-r)
2. 𝐴 = 𝜋𝑟 2
3. 𝑎2 + 𝑏2 = 𝑐 2
−𝑏
4. 𝑥 = 2𝑎
P+Q−R
5. 𝑥 = PQR

Mathematical Functions:
These are mathematical tools that are provided in the library of the QBASIC programming
language for calculation. The commonly used ones are specified below:

1. SQURE ROOT(√) Function


Syntax: SQR(X); returns the square root of the X. e.g. SQR(25) gives 5

2. COS, SIN, TAN, and ATN Function


COS(X) calculates the cosine. If PI = 3.141593, COS(PI / 4) = . 7071067
SIN(X) calculates the sin, SIN(PI / 3) = .8660254
TAN(X) calculates the tangent, TAN(-PI / 2) = . 6137956
ATN(X) calculates the inverse of TAN, ATN(TAN(-PI / 2)) = 1.570796 (Same as PI / 2)

3. FIX Function
Syntax: FIX(X): removes the decimal part and returns integer part of X. e.g. FIX(9.88)
returns 9; FIX (-3.90) returns -3

4. CINT Function
CINT(X) rounds off the integer number. E.g. CINT(9.8) returns 10; CINT(5.3) returns 5

5. ABS Funtion
ABS (X) returns the absolute value of a number. In other words, ABS converts a
negative number to a positive number (if you pass a positive number, ABS does
nothing). E.g. ABS(12) = 12; ABS (-12) = 12

6. SGN Function

15 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
SGN(X) is used to determine the sign of number. If X is positive, SGN returns +1; if
X is negative, SGN returns -1; if number is 0, SGN returns 0. E.g. SGN(45) = 1
SGN(-68) = -1 , SGN (0) = 0

Class Work

Convert the following arithmetic expression to its programming representation:


(a) Z = (COS X)2 + TAN-1Y

(b) COMP = A2 + B2

(c) DIVN = C + A2 + B2

COS A + SIN B
(d) Area= (4/3) πr3h3
(e) Z = y2 + x
q

C. RELATIONAL / LOGICAL OPERATORS

Relational operators

OPERATOR SAMPLE RELATIONSHIP RESULT


= 7=5 Equality. Compares the value on the No
left whether it is equal to the value on
its right.
< 7<5 Less than. Compares the value on the No
left whether it is less than the value on
its right
> 7>5 Greater than. Compares the value on Yes
the left whether it is greater than the
value on its right
<= 7<=5 Less Than or Equal To. No
>= 7>=5 Greater than or Equal To. Yes
<> or != 7<>5 Not Equal To. Compares the value on Yes
the left whether it is not equal to the
value on its right

16 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
Logical Operators

When a comparison statement (relational expression) evaluates more than one


relationship, then we use the logical operators AND, OR, NOT to compare the logic.

AND. When we use AND to combine two relational expressions, then both expressions
have to be TRUE for the AND operator to return a TRUE value. When either one is FALSE,
then AND will return a FALSE.
OR. When at least one of the expressions is TRUE, the OR will return TRUE. When both
expressions are FALSE, then OR will also return a FALSE.

AND operates like the multiplication operator


e.g. 1*1 = 1
1*0 = 0
0*1 = 0
OR operates like addition operator
e.g. 1+1 = 1
1+0 = 1
0+1 = 1
0+0 = 0

LOGICAL CONDITION COMPARISIONS/ TRUTH TABLE


Expression 1 Expression 2 AND OR
T T T T
T F F T
F T F T
F F F F

NOT. When the logical expression is TRUE, NOT will reverse it and return a FALSE. When
the expression is FALSE, NOT will reverse it and return a TRUE.

LOGICAL CONDITION COMPARISIONS/


TRUTH TABLE

Expression NOT

17 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
T F
F T

EXAMPLES
If a=2 , b= 5 , c = 7,

1. a < c AND c >= a + b ' TRUE AND TRUE —> TRUE


2. c >= a + b AND c < a ' TRUE AND FALSE —> FALSE
3. c < a AND b = a * 3 ' FALSE AND FALSE —> FALSE
4. c>= a + b OR c < a ' TRUE OR FALSE —> TRUE
5. c < a OR b = a * 3 ' FALSE OR FALSE —> FALSE
6. NOT (c - b = a) ' NOT (TRUE) —> FALSE
7. NOT (b >= c) ' NOT (FALSE) —> TRUE

[Link] PRECEDENCE AND ASSOCIATIVITY

Two operator characteristics determine how operands group with operators: precedence
and associativity.

Precedence is the priority for grouping different types of operators with their operands. An
operator's precedence is meaningful only if other operators with higher or lower
precedence are present. Operator precedence determines the order in which operators are
evaluated. Operators with higher precedence are evaluated first. The grouping of operands
can be forced by using parentheses.

The Rules of Precedence is As Follows:

P = Parentheses
E = Exponents
M = Multiplication
D = Division
A = Addition
S = Subtraction
The acronym PEMDAS is a useful way to remember the rules:

• Parentheses have the highest precedence and can be used to force an expression
to evaluate in the order you want. Since expressions in parentheses are evaluated
first, 2 * (3-1) is 4, and (1+1)**(5-2) is 8. You can also use parentheses to make an
expression easier to read, as in (minute * 100) / 60, even if it doesn’t change the
result.

18 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
• Exponentiation has the next highest precedence, so 2**1+1 is 3, not 4, and 3*1**3
is 3, not 27.

• Multiplication and Division have the same precedence, which is higher than
Addition and Subtraction, which also have the same precedence. So 2*3-1 is 5, not
4, and 6+4/2 is 8, not 5.

• Operators with the same precedence are evaluated from left to right. So in the
expression degrees / 2 * pi, the division happens first and the result is multiplied
by pi. To divide by 2 π, you can use parentheses or write degrees / 2 / pi.

Or the sentence: Please excuse my dear Aunt Sally.

Note: When an expression contains logical operators, relational operators and


arithmetic, then it is evaluated in the following sequence.
a. Arithmetic operations are performed first
b. Relational operations are compared from left to right
c. Logical operations are performed in the order (NOT, AND, OR)
d. Brackets can be used to over-ride the default order.

Associativity

Associativity is the left-to-right or right-to-left order for grouping operands to operators that
have the same precedence.

A common example:

8 - 3 - 2 is calculated as (8 - 3) - 2, giving 3, and and not as 8 - (3 - 2), giving 7.

Associativity determines the order in which operators of the same precedence are
processed. For example, consider an expression:

a OPERATOR b OPERATOR c

Left-associativity (left-to-right) means that it is processed as (a OP b) OP c, while


right-associativity (right-to-left) means it is interpreted as a OP (b OP c).

Operator type Associativity Individual operators

19 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
multiplication left-to-right *
division left-to-right /
modulus left-to-right %
addition left-to-right +
subtraction left-to-right -
<
<=
relational left-to-right
>
>=

General Rules for evaluation of expression

1. When Parenthesis are used, the expressions within parenthesis assume highest
priority.

2. If parenthesis are nested, the evaluation begins with the innermost sub
expression.

3. The precedence rule is applied in determining the order of application of


operators in evaluating sub expressions.

4. The associability rule is applied when two or more operators of the same
precedence level appear in the sub expression.

FUNDAMENTALS OF PROGRAMMING

Introduction to Algorithm

An algorithm can be defined as a step-by-step procedure of solving a problem usually with


the requirement that the procedure terminate at some point. It has to do with defining the
actions to be executed and the order in which those actions are to be executed.

An algorithm is a detailed sequence of steps taken to solve a problem, that’s why it is being
referred to as a step-by-step method of solving a problem.

What is pseudocode?

20 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
Pseudocode consists of short, English phrases used to explain specific tasks within a
program's algorithm. Thus, an algorithm is a collection of pseudocodes and when one is
talking about the Pseudocode for a program, he is referring to the algorithm.

Pseudocode can also be defined as an artificial and informal language that helps
programmers develop algorithms.

Why is pseudocode necessary?

1. The purpose of using pseudocode is that it is easier for humans to understand than
conventional programming language code.
2. Writing pseudocode WILL save one’s time later during the construction & testing phase
of a program's development.
3. It allows the designer to focus on the logic of the algorithm without being distracted by
details of language syntax.
4. The programming process is a complicated one. The programmer must first understand
the program specifications, then organize his thoughts and create the program. This is
a difficult task when the program is not easy, so one must break the main tasks that
must be accomplished into smaller ones in order to be able to eventually write
fully developed code and this can be achieved with pseudocodes.

Rules guiding Pseudocode

1. Each statement of instruction should be numbered. This is to enforce the notion of


an ordered sequence of ... operations. Furthermore we introduce a dot notation (e.g.
3.1 come after 3 but before 4) to number subordinate operations for conditional and
iterative operations
2. Each instruction should be unambiguous and effectively computable. That is,
anyone who reads it should be able to understand it and possibly translate it to a
programming language of choice.
3. It should be complete. Nothing should be left out.
4. All statements showing "dependency" are to be indented. These include while, do,
for, if, switch. Examples below will illustrate this notion.
5. Flowcharting symbols should not be used when writing psedocode. Indentation can
be used insteadto show the logic in the pseudocode.

HOW TO WRITE AN ALGORITHM

1. First, define the formulas to be used to solve the problem

21 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
2. Define the inputs and the outputs i.e. list out the variables where your data is to
be stored (extract the variables from the formula)
3. Then, define the steps

Note the three types of instructions: input (enter), process/calculate (=) and output
(display)

Example 1: Write an algorithm for calculating the sum of two numbers.

Method 1

SUM = X + Y

Variables: X,Y, SUM

1. Start
2. Prompt the user to enter the first integer
3. Prompt the user to enter a second integer
4. Compute the sum of the two user inputs
5. Display the result
6. End

OR

Method 2

1. Start
2. input X
3. input Y
4. sum = X + Y
5. output Sum
6. End

NOTE: Method 2 will be used throughout this course

Example 2: Develop an algorithm to find the average of four numbers stored in variables
A, B, C, and D.

22 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
Variables: A,B,C,D, Sum, AveDiv
Solution
1. Start
2. Input A,B,C,D
3. Sum = A+B+C+D
4. AveDiv = Sum/ 4
5. Output Sum, AveDiv
6. End

Example 3: Write an algorithm to compute Sales Tax

Sales tax= price of item*sales tax rate

Final price = price of item+ sales tax

Variables: price of item, sales tax rate, sales tax, final price

1. start
2. input price of item
3. input sales tax rate
4. sales tax = price of item * sales tax rate
5. final prince = price of item + sales tax
6. display final price
7. end

Class Work

1. Develop an algorithm to calculate simple interest (SI) on X, principal at Y% rate and


Z years. Hint: Simple Interest = Principal x Rate x Time
2. Given the Heron’s formula for finding the area of a triangle in terms of its three
sides area = S (S-a) (S-b) (S-c)

Where S = a + b + c

2 , write an algorithm to find the area of a triangle.

1
3. Write an algorithm for calculating the area of a trapezium. Hint: Area = (a + b)h
2

FEATURES OF ALGORITHM

23 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
1. Finiteness: this means it should terminate after a finite number of steps. It should
involve finite number of steps.
2. Definiteness: this means that it should be clear, simply understandable with no
ambiguity. That is it must be unambiguously specified.
3. Efficiency: this means it should lead to a unique solution of the problem. For
input operation, valid inputs should be clearly specified while for output operation,
it can be proved to produce the correct output given a valid input
4. Effectiveness: it means that the steps should be sufficiently simple and basic. The
effect of each statement of an algorithm must be clearly defined. Examples of
properties of algorithms. E.g. Simple basic operation: “Open the bottle of wine” this
is the knowledge required for the Open.
5. Flexibility: It should have the capability to handle some unexpected situations
which may arise during the solution of a problem.

INTRODUCTION TO FLOWCHARTS

A flowchart is a graphical representation of an algorithm. It is a type of diagram that


represents an algorithm by showing the instructions therein as boxes of various kinds
(symbols), and their order by connecting these boxes with arrows. This is why a
Flowchart is first defined as a graphical representation of an algorithm.

Flowcharts play a vital role in the programming of a problem and are quite helpful in
understanding the logic of complicated and lengthy problems. Once the flowchart is
drawn, it becomes easy to write the program in any high level language because it
represents the step-by-step solution to a given problem. The boxes used in flowcharts
are referred to as symbols.

COMMONLY USED FLOWCHART SYMBOLS

1. Start and end symbols: This is represented as ovals or rounded rectangles, usually
containing the word "Start" or "End" or “Return”.

2. Input/ Output symbol: Input/Output: this is represented as a parallelogram. It


is used for input and output operation. Examples: input X.

24 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
3. Arrows: these are used for showing "flow of control". An arrow coming from one
symbol and pointing to another symbol means that control is being passed to the
symbol the arrow is pointing to.

4. Decision making and Branching Symbol: Represented as a diamond (rhombus)


showing where a decision is made such as a Yes/No question or True/False test.
The conditional symbol is peculiar in that it has two arrows coming out of it,
usually from the bottom point and right point, one corresponding to Yes or True,
and one corresponding to No or False. (Note: its arrows should always be labeled.)

5. Computational/ Process symbol: Represented as a rectangle. It is used for


representing all arithmetic or computational expressions. That is, anything that has
to do with calculation. Examples: X = X+ Y / Z.

6. Connector symbol: Represented as a small circle. It is used as a continuation


symbol to represent a point at which the flowchart connects with another segment
of the program. It is required that the name or reference for the segment should
appear within the symbol.

How to Draw a Flowchart

1. In drawing a proper flowchart, first, develop the algorithm for the problem.

25 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
2. The usual direction of the flow of a procedure or system is from top to bottom or
left to right.
3. Only one flow line should come out from a process symbol.

or

4. Only one flow line should enter a decision symbol, but two or three flow lines, one
for each possible answer, should leave the decision symbol.

5. Only one flow line is used in conjunction with terminal symbol connector symbol.

6. If the flowchart becomes complex, it is better to use connector symbols to reduce


the number of flow lines. Avoid the intersection of flow lines if you want to make it
more effective and better way of communication.
7. Ensure that the flowchart has a logical start and finish.

Example of a flowchart:

26 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
Problem 1: Write an algorithm and draw the flowchart for finding the average of two
numbers

Algorithm: START

Input: two numbers x and y


Input X
Output: the average of x and y

Steps: Input Y

1. start
Sum = X+Y
2. input X
3. input Y
4. Sum = X + Y
Average = Sum/2
5. Average = Sum /2
6. output Average
7. end Output
Average

END

Class work

1. Draw the flowchart for an algorithm to calculate simple interest (SI) on X, principal at
Y% rate and Z years. Hint: Simple Interest = Principal x Rate x Time

2. Given the Heron’s formula for finding the area of a triangle in terms of its three sides
area = S (S-a) (S-b) (S-c)

Where S = a + b + c

3 , draw the flowchart of the algorithm to solve this problem.

3. Draw the flowchart of the algorithm to calculate the area of a trapezium. Hint: Area =
1
(a + b)h
2

Advantages of Using Flowchart

27 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
1. Communication flowcharts are visual aids for communicating the logic of a
system to all concerned.
2. Documentation: flowcharts are a means of documentation because the analyst or
programmer may forget the logic of the program. It’s a mean to quickly remember
the logic of the program.
3. Changes or modifications to the program are more easily catered for.
4. Flowchart can be understood by someone else, other than the programmer, who
may be interested in the programming project.
5. In terms of analysis, flowcharts help to clarify the logic of the problem being
solved.
Disadvantages of Using Flowchart

1. Alterations: If alterations are required the flowchart may require redrawing


completely.
2. Reproduction: As the flowchart symbols cannot be typed, reproduction of
flowchart is often a problem.

INTRODUCTION TO QBASIC PROGRAMMING LANGUAGE

Computer Programming Languages were designed to allow humans to work in a language


more similar to what we are used to. The human writes the English like commands based
on the Programming Language and the translator software such as compiler or
interpreter convert these instructions into the 0’s and 1’s that the computer can
understand.

Computer programming languages have grammar rules, commonly termed “Syntax” which
determines the meaning of the instructions.

BASIC is an acronym for Beginner’s All-purpose Symbolic Instruction Code and the Q
stands for Quick. It was designed for use as simple language to teach programming to
college students. It was invented in 1963, at Dartmouth College, by the mathematicians
John George Kemeny and Tom Kurtzas. The version that shall be used in this class is
known as the QBasic.

QBASIC EXPRESSIONS, COMMANDS AND STATEMENTS

28 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
Commands are reserved words that are used in a programming language to execute or
carry out a particular special task. They are otherwise referred to as reserved words
because they are reserved for a special purpose or keywords because of the special role
they perform. Just as the name implies, it tell the QBasic interpreter to do something.
E.g. PRINT, INPUT, CLS, SQRT, etc.

Expression: An expression is something the interpreter calculates or evaluates. If an


expression is passed to a variable, the expression is evaluated and the variable is set to
that value. It usually have the “=” symbol.

Statement on the other hand, refers to executable instructions given to the computer to
perform specific tasks. Every statement should have at least one QBasic command word.

COMMONLY USED COMMANDS IN QBASIC

1. CLS command

CLS is a command used to clear the screen. This tells QBasic to send to the Screen the
instructions required to clear whatever was there previously.

It makes the run-time screen completely blank. When programs are run without clearing
the screen before it starts, it shows the remains of the program run previously. Clearing the
screen at the beginning of the program will make the output screen look clean and neat.

2. REM command

REM stands for “remark”. The REM command is used to add comments to the program
without the texts being treated like an executable instruction. That is, QBasic statements
that begin with the REM command are ignored and treated as non executable statements.
Its use involves giving the program a name at the beginning of a program and commenting
on what the program is doing thereby making the program more understandable to the
reader. Apostrophe ( ’ ) is also used to represent a remark statement. When the QBasic
interpreter encounters a REM statement or apostrophe, it ignores that line of instruction
and moves to another line. REM can be used anywhere and many times in a program.

3. INPUT command

The input command allows user to enter a value for the variable during run time. The
input command is usually followed by the variables. While running the program, a
question mark (?) appears on the output screen waiting for the user to enter a relevant

29 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
data and then press the enter key. Once the Enter key is pressed, the data is stored in the
variable.
Syntax: INPUT variables
E.g. INPUT a
INPUT a, b, c

4. PRINT command

Print command is used to display the output of the variable or some messages on the run
time screen. It is usually followed by the variables to be printed. The question mark
character “?” also represents the Print command and can be used instead of writing Print.
If there is more than one variable to print, they should be separated by a comma but
whenever a text is to be printed, such text must be in quotes ("). Typing only Print
command without a variable after it will leave a blank space.
Syntax: PRINT Variables or
PRINT “text”
E.g.
Print A, B, C
? A, B, C
Print “MY NAME IS CHARLES DIKKO”
? “MY NAME IS CHARLES DIKKO”
Print “80 * 8”

5. END command

The END command tells the computer that the program is over, and it should stop reading
lines. That is, whenever the QBasic interpreter encounters it, it assumes the program is
over, and stops it.

The syntax for END is simply END.

FORMATTED INPUT /OUTPUT COMMAND

This is a concept used with input and output command to give messages to the user that
will make the program more interactive and more user friendly. It also helps in giving
relevant message to the user at run time to avoid erroneous data input.

Method I: Separate Instruction method

30 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
CLS
e.g. PRINT “TYPE THE FISRT VARIABLE”
INPUT a
PRINT “TYPE THE SECOND VARIABLE”
INPUT b
Area = a * b
PRINT “THE OUTPUT IS”
PRINT Area
END

Method II: combined instruction method


Here, semicolon character “;” is used for separating the prompt message for the actual
variable. That is, mixing INPUT and OUTPUT commands, using the ";" semi-colon is a tool
for communicating with the user, formatting the output of our program onto the screen.
The semi-colon is used in QBasic to tell the INPUT/PRINT command to put statement on
the same line.

CLS
INPUT "ENTER THE FIRST VARIABLE"; a
INPUT "ENTER THE SECOND VARIABLE"; b
Area = a * b
PRINT "THE OUTPUT IS”; Area

QBASIC DATA

Data is a collection of facts and figures that is entered into the computer through the
keyboard. Data is of two types: constant and variables.

CONSTANT: refers to data whose value does not change or remains fixed. There are two
types of constants:

(a) Numeric Constant: Numbers - negative or positive used for mathematical


calculations. E.g. –10, 20, 890
(b) String or Alphanumeric Constant: Numbers or alphabets on which one cannot
perform an arithmetic operations. They are written within double quotes (inverted commas
“ ”). E.g. “CTE114”, “Operating System”, “820”

VARIABLE: refers to a memory location where data whose value is not constant and may
change due to some calculation during the program execution is stored.
(a) Numeric Variable: The variable that holds a Numeric Constant for arithmetic

31 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
calculations. E.g. A = 50, here A is the Numeric Variable
(b) String Variable or Alphanumeric Variable: The variable that holds an Alphanumeric
Constant, which cannot be used for arithmetic calculations, is called Alphanumeric
Variable or String Variable. An Alphanumeric variable must end with a dollar $ sign
and the Alphanumeric constant must be enclosed in inverted commas. E.g. Name$ =
“Mohammed”, here Name$ is an Alphanumeric Variable.

RULES OF QBASIC
As earlier mentioned, every programming language has a set of rules that have to be
followed while writing a program, the following are some rules of QBASIC language:

1. Every statement should have at least one QBasic command word. The words that
BASIC recognizes are called keywords.
2. All the command words have to be written using some standard rules, which are
called “Syntax Rules”. Syntax is the grammar of writing the statement in a
language. Syntax Errors are generated when improper syntax is detected.

TIPS IN WRITING GOOD PROGRAMS


The following are tips to be followed in writing good programs

1. Always try to write remarks in the program using REM command. Writing remarks
makes the program easier to understand, by oneself and other programmers.
2. While using Print or Input statement, always use formatted input/output style,
otherwise the program would not be able to interact with the users properly.
3. Always select the variable name that is most suitable for the calculation and easy
to remember. E.g. If you want store average marks of students in a variable then
try to use variable like Avg_Student or Avg_Mark etc.
4. While writing conditional statement and loops first write their opening and closing
command and then insert the statements in between them.
5. Try to select the most suitable loop for your program.
6. If you are writing a lengthy and complicated program then try to break it into small
sub programs.

CONTROL STRUCTURES: A Key Instrument Used In Designing Algorithm and Writing


Programs

32 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
Control structure can also be defined as a block of programming that analyzes variables
and chooses a direction in which to go based on given parameters. Hence it is the basic
decision-making process in computing.

That is, for any given program a programmer may want to write, there are three ways or
method that can be used to design the layout or the flow of the program and these are
what is referred to as the control structures. The choice of which one to use is usually
based on the analysis of the variables and the problem to be solved (whether there will be
need for branching, repetition or not).

Control structures are one of the most basic concepts in programming because they are
the elementary building blocks for all programs. The three control structures that all
programmers must learn what they are and how they can be used are:

1. Strictly Sequence control structures


2. Selection control structure
3. Iteration or Repetition control structure

STRICTLY SEQUENCE CONTROL STRUCTURES

This is the most common form of control structure. Here, each step is carried out in order
of their position and is only done once. That is, it does not include branching. In
algorithm, it always begins with ‘Start, then the steps are listed out and stops in ‘End’.
In flowchart, it begins with a (terminator), then the steps are shown by (process) and
ends with another terminator.

For example, in computing calculating the area of a trapezium, the algorithm, flowchart
and the Qbasic Program is as follows.

Algorithm

1. Start
2. input a, b, h
3. Area = .5*(a+b)*h
4. output Area
5. End
Flowchart
Start

Input a,b,h

33 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
Qbasic Program

CLS

REM PROGRAM TO CALCULATE THE AREA OF A TRAPEZIUM

REM PROGRAM WRITTEN BY OLLA OLLA

REM MATRIC NO 234700003721

REM DEPT. OF ELECTRICAL ENGR. / ND II

INPUT “ Type the values for a, b, and h separated by a comma”; a, b, h

Area = .5 *(a+b)*h

PRINT “ The result for the calculation of area of the trapezium is”; Area

END

ITERATION CONTROL STRUCTURE:

Iteration is also called repetition and this control structure is used when the execution
of some lines of the program is to be repeated over and over again, so, it has to do with
the program going round in a loop.

That is, this control structure carries out a particular action over and over again
until the condition to stop it is met. A loop is created to return the program to where
the repetition has started for as long as it takes until the condition is met. It is typically
programmed using the following methods:

1. COUNTER METHOD
2. FOR……NEXT METHOD
3. WHILE……DO or DO……LOOP UNTIL METHOD

A. Counter Method

34 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
Here, we normally use a variable called “Count” which counts the number of times the
line (s) of code is repeated. The value in it is check with the ‘number of times’ we want
the line(s) of code repeated. If the values matches, then the repetitions stops.

Example I

Write the algorithm and draw the flowchart for a program to calculate the areas of five(5)
trapeziums.

Algorithm

B. Start
C. Count = 0
D. input a, b, h
E. Area = .5*(a+b)*h
F. output Area
G. count = count + 1
H. Is count = 5?
I. If Yes, goto 9, If No goto 3
J. End

Flowchart

Start

Count = 0

Input a,b,h

Area =.5*(a+b)*h

Print Area

Count = CountTO
35 CTE 114 -- INTRODUCTION +1 PROGRAMMING ND I CET
Not for Sale
Example II: An algorithm for calculating the area of 10 rectangles.

1. start
2. Count = 0
3. Input len, brt
4. Area = len *brt
5. Output Area
6. Count = Count + 1
7. Is count =10?
8. If Yes, goto step 9, If No, 3
9. End

The Concept of Label

A label is a single word that is used in transferring control from one part of the program to
the other. That is, a label is used to tell the QBasic interpreter to jump to certain part of
the program and continue execution from there. It is now being used in place of line
numbers in QBasic. It is usually followed immediately by a colon “:”. A label is a way to
tell the computer where things are.

Example 1: Program to calculate the area of five trapeziums

CLS

REM PROGRAM TO CALCULATE THE AREA OF FIVE (5) TRAPEZIUM

REM PROGRAM WRITTEN BY OLLA OLLA

REM MATRIC NO 234700003721

REM DEPT. OF ELECTRICAL ENGR. / ND II

36 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
Count = 0
More:
INPUT “Ente r the values for a, b and h separated by commas”; a, b, h
AreaofTrap = .5*(a+b)*h
PRINT “The result of the calculation is”; AreaofTrap
Count = Count + 1
If (Count < 5) Then GOTO More
END

Note: instead of “=” symbol used in the algorithm, “<” symbol os used so thet we can
transfer control up.

Example II: Given the Heron’s formula for finding the area of a triangle in terms of its
three sides area = S (S-a) (S-b) (S-c)

Where S = a + b + c

Write an algorithm to find the area of 10 triangles.

Solution

1. start
2. C=0
3. Input a, b, c
4. S = (a +b + c) / 2
5. Area = Sqrt( S * (S-a) * (S-b) *(S-c))
6. Output Area
7. C = C + 1
8. Is C = 10?
9. If yes, goto 10, if no goto 3
10. End

Example III: Program to calculate the double and square of inter numbers from 3 to
7.

37 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
CLS
REM PROGRAM TO CALCULATE THE DOUBLE AND SQUARE OF INTER NUMBERS REM
FROM 3 TO 7.
REM PROGRAM WRITTEN BY OLLA OLLA

REM MATRIC NO: 234700003721

REM DEPT: COMPUTER ENGR.

REM CLASS: ND II

Number = 3
Again:
Double = Number * 2
Square = Number * Number
PRINT Number, Double, Square
Number = Number + 1
If (Number < 7 Then) GOTO Again
END

B. For...........Next Iteration Method

This is used to repeat a series of statements in a specified number of times. It is the most
common and convenient method of loop.
The syntax is:
FOR variable = initial value TO final value STEP increment
Statements
NEXT variable
Note: if the increment is by 1, the STEP statement will be ignore. Also to be noted is the
fact that the increment can either be a positive or negative value but if negative, initial
value must be greater than final value.
Examples
1. FOR X = 1 TO 5
PRINT X
NEXT X
Output for this will be: 1, 2, 3, 4, 5
2. FOR X = 1 TO 5 STEP 2
PRINT X
NEXT X

38 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
Output: 1, 3, 5
3. FOR I = 2 TO 20 STEP 2
PRINT I
NEXT I
Output: 2, 4, 6, 8, 10, 12, 14, 16, 18, 20
4. FOR J = 10 TO 2 STEP -2
PRINT J
NEXT J
Output: 10, 8, 6, 4, 2

FOR A = 50 TO 40 STEP –1
Print A;
NEXT A
Output: 50 49 48 47 46 45 44 43 42 41 40

CLASS WORK:
Determine the output of the following

(a) FOR X = 1 TO 15 STEP 3


PRINT X
NEXT X

(b) For I = 5 to 1 Step -1


Print I
Next I

SAMPLE PROGRAMS TO DEMONSTRATE FOR…. NEXT ITERATION METHOD

Example 1: Program to calculate the area of five trapeziums USING FOR…NEXT

CLS

REM PROGRAM TO CALCULATE THE AREA OF FIVE (5) TRAPEZIUM

FOR I = 1 TO 5
INPUT “Ente r the values for a, b and h separated by commas”; a, b, h
AreaofTrap = .5*(a+b)*h
PRINT “The result of the calculation is”; AreaofTrap

39 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
NEXT I
END

Example II: Program to calculate the double and square of integer numbers from 3
to 7.

CLS
REM PROGRAM TO CALCULATE THE DOUBLE AND SQUARE OF INTER NUMBERS REM
FROM 3 TO 7 using For…..Next

FOR Number = 3 TO 7
Double = Number * 2
Square = Number * Number
PRINT Number, Double, Square
NEXT Number
END

Example III: Program to calculate the sum of integer numbers from 2 to 9

CLS
REM PROGRAM TO CALCULATE THE SUM OF EVEN NUMBERS FROM 1 TO 15
REM using For…..Next
SUM = 0
FOR NUmber = 2 TO 15 STEP 2
SUM = SUM + NUmber
NEXT NUmber
PRINT "Sum of EVEN numbers from 1 to 15 is", SUM
END

Example IV: Program to calculate the product of integer numbers from 10 to 6


CLS
REM PROGRAM TO CALCULATE THE PRODUCT OF INTEGER NUMBERS FROM 10 TO
6
REM using For…..Next
PRODUCT = 1
FOR IntNumber = 10 TO 6 STEP-1
PRODUCT = PRODUCT * IntNumber
NEXT IntNumber
PRINT PRODUCT

40 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
END
Assignment
Rewrite the programs in execise III and IV using the counter method

NESTED FOR…NEXT LOOP


This is a situation whereby we to have an inner loop inside a particular loop. The inner
loop is completely executed at each execution of the outer loop.
Example
For I = 1 to 2
For J = 1 to 4
Print I, J
Next J
Next I
The output will be:
I J
1 1
1 2
1 3
1 4
2 1
2 2
2 3
2 4

Example II
For I = 3 to 5
For J = 2 to 4
K = I *J
L=I+J
PRINT I, J, K, L
Next J
Next I
The output will be:
I J K L
3 2 6 5
3 3 9 6

3 4 12 7

41 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
4 2 8 6

4 3 12 7

4 4 16 8

5 2 10 7

5 3 15 8

4 4 20 9

3. While……EndWhile Or Do……Loop Until Method

Here, the loop could either be:

i. Pre-test or Top-test loops


ii. Post-test or Bottom-test loops

In pre-test loops, the condition is tested at the start.

Example I
1. start
2. count = 0
3. While (count < 5)
4. Display "I love computers!"
5. Count = count + 1
6. Endwhile
7. END

Example II
1. start
2. x = 10
3. Do While x < 15
4. PRINT x
5. x=x+1
6. Loop
7. end

42 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
In Post-test loops, the condition is tested at the end of the loop. Uses DO … LOOP UNTIL
or DO……LOOP WHILE. The process in the loop is executed first whether it is true or
false and will keep repeating until the condition is met. Post-test loops end when the
condition is true but the loop always do the loop at least once, even if the end condition
is originally true. Post-test loops are also called unguarded loops because no check is
made before the algorithm begins the loop structure.

Example 1:

1. start
2. count = 5
3. Do
4. output "Computer Programming is interesting!"
5. Count = count - 1
6. Loop Until (count < 1)
7. end

Example 2:

1. start
2. count = 4
3. Do
4. Display "Blast off is soon!"
5. Count = count -1
6. Loop While (count > zero)
7. end

SELECTION CONTROL STRUCTURE

Selection is used to make a decision to go down one path or another. It allows a choice to
be made in an algorithm by deciding on a particular answer from a set of variable answers
and carrying out the steps that follows such answer. This concept introduces the
conditional control structure. On the basis of the true/false question asked in one line,
execution is transferred to another line. That is, a selection-control statement requires an
expression that can be evaluated into a "Yes/No" (or True/False) value.

One way of describing the difference is between selection and repetition is that when
making a selection, the condition is only ever tested once.

43 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
There are two types of selection control structures, they are;

1. Binary selection (Yes/No)

a. Ordinary If……..Then
b. Nested If………Then

2. Case selection (just pick anyone you like from multiple selection not
necessarily a yes/no situation)

1. Ordinary If …… Then Binary selection

Binary selection is where there are two possible choices to choose from. It uses If
...Then…. Else ... Endif statement. If the condition is met (true) then one path is taken,
if otherwise (false), the other path is taken. Here, we have just two conditions to choose
from.

Example I: An algorithm to determine voting based on age

1. start
2. input age
3. If (age > =18) then
4. Output “ you can vote”
5. Else
6. Output “you can't vote”.
7. Endif
8. End

Example II: Student grade

1. start
2. input mark
3. if mark >= 40 then
4. Print "passed"
5. else
6. Print "failed"
7. Endif
8. End

Example III: program to input departmental name “Computer Engineering”

1. start

44 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
2. input DeptName$
3. Tester$= “Computer Engineering”
4. IF DeptName$= Tester$ THEN
5. Output "Hello, " ; DeptName$;” ,student".
6. Output “How are you today?"
7. ELSE
8. Output "Go Away!"
9. END IF
10. end

Example IV: In Computing Weekly Wages, the variables are : hours worked, ray
rate, gross pay. Gross pay depends on the pay rate and the number of hours worked
per week. However, if you work more than 40 hours, you get paid time-and-a-half
for all hours worked over 40. Write an algorithm to compute the weekly wages.

Solution

1. Start
2. Input hours worked, pay rate
4. IF hours worked ≤ 40 THEN
5. gross pay = pay rate * hours worked
6. ELSE
7. gross pay = pay rate + (1.5 * pay rate * (hours worked - 40))
8. Output gross pay
9. ENDIF
10. end

2. Nested If……..Then Binary Selection Control Structure

NESTED IF……..THEN binary selection where we have more than two conditions to
select from but we select just [Link] will stop as soon as a condition is true. That's
why the most "likely" test is put first, for efficiency. It uses the
IF…..THEN….ELSEIF…….THEN…..ELSEIF-THEN….ELSE….EndIf structure.

Illustration

45 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
if condition then
-- statements;
elseif condition then
-- more statements
elseif condition then
-- more statements;
...
else
-- other statements;
end if;

end

NOTE: THE LAST TESTING PARAMETER BEFORE ENDIF IS ELSE AND NOT ELSEIF.

Example 1

Algorithm for Program age

1. start
2. Input age
3. If age <=0 Or age >120 then
4. ? “Do you think I am a fool?”
5. Goto 2
6. Else if age >0 AND age<18 then
7. ? “You are still a baby”
8. Else if age >=18 AND age<60 then
9. ? “You are grown up”
10. Else
11. ? “You are Old”
12. End if
13. End

Example 2

Program Arithmetic operations to illustrate Nested if structure

CLS
Start:

46 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
Input “Please supply me with two values”; a , b
Print “What do you want to do with these values? “
? “1.) Addition”
? “2.) Subtraction”
? “3.) Multiplication”
? “4.) Division”
Input “Enter your choice “; choice
‘Starting of the condition
If choice=1 then
Result = a + b
Else if choice=2 then
Result = a-b
Else if choice= 3 then
Result = a*b
Else if choice=4 then
Result = a/b
Else
Print “Please enter a valid choice”
Goto start:
End if
Print “The result of your operation is “; Result
End

CASE SELECTION (ALSO CALLED MULTIPLE SELECTION)

Case selection is where there is more than one possible choice to choose when trying
to solve the problem even though only one process can be carried out. The Syntax
for Case selection is CASE (parameter)

........ choices

ENDCASE.

Example I

1. start
2. input age
3. Case (age)
4. 0 to 17 Display "You can't vote."
5. 18 to 64 Display "You are in your working years."

47 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
6. 65 + Display "You should be retired."
7. Endcase
8. end

Example II

1. start
2. input day
3. CASE (day)
1. Monday: write out ‘first working day of the week’
2. Friday: write out ‘last working day of the week’
3. Saturday: write out ‘the first day of the weekend’
4. Sunday: write out ‘the second day of the weekend’
4. ENDCASE
5. end

Que: write an algorithm to find the roots of 5 quadratic equations and draw the
flowchart.
Solution
1. Start
2. C = 1
3. Input a, b, c
4. D = b**2 – 4 *a*c
5. If D < 0, goto 8
6. If D = 0, goto 9
7. If D > 0, goto 11
8. Output “no real solution”
9. X = - b / (2*a)
10. Output X
11. X1 = (-b + sqrt (D))/(2*a)
12. X2 = (-b - sqrt (D))/(2*a)
13. Output X1, X2
14. C = C + 1
15. Is C > 5
16. If Yes, goto 17, if No, goto 3

48 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
17. End

The Concept of Arrays or Subscripted Variables

An array can be described as a variable which usually contain more than one value. That
is, it is a variable which identifies more than one location in memory. It usually have a
subscript which is either a variable or a value enclosed in parenthesis. This is why it is
referred to as subscripted variable.

For instance, A (5) could either mean an array with locations ranging from 1 to 5 or 0 to
5. This could also be written as A (i), where i= 0 to 5 or i = 1 to 5. Also, just like the non
subscripted variable, an array could either hold a numeric or string values.

The following is a string array N$(i), where i = 0 to 3.

Ted Jack Jill Fred


N$(0) N$(1) N$(2) N$(3)

N$(0) = "Ted"
N$(1) = "Jack"
N$(2) = "Jill"
N$(3) = "Fred"

FOR i = 0 TO 3
PRINT N$(i)
NEXT i

Arrays can also store numbers. Here, we have A(i), where i = 1 to 10

24 31 15 67 34 87 92 14 34 62

A(1) = 24

49 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
A(2) = 31
A(3) = 15
A(4) = 67
A(5) = 34
A(6) = 87
A(7) = 92
A(8) = 14
A(9) = 34
A(10)= 62

FOR I = 1 TO 10
A(I) = I * 2
NEXT I

FOR I = 1 TO 10
PRINT A(I)
NEXT I

DIM statements

Arrays are limited to holding only 11 items (0 through 10). If you go over 10, you'll get a
"Subscript out of range" error. To make bigger arrays, you can use DIM to tell QBASIC
how big the array will be:

DIM A(20)

FOR I = 0 TO 20
A(I) = I * 2
NEXT I

FOR I = 0 TO 20
PRINT A(I)
NEXT I

Arrays are perfect for programs that need to keep a list of things. You could use arrays to
make a phone book program, or a program that keeps track of the people in your class at
school.

DATA 10, 24, 31, 15, 67, 34, 87, 92, 14

50 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
FOR I = 0 TO 8
READ A(I)
NEXT I

THE CONCEPT OF DEBUGGING AND MAINTAINING PROGRAM


In computer program/software, a bug is an error in coding or logic that causes a
program to malfunction or to produce incorrect results. Errors could occur in programs
as a result of wrong code/instructions, human error or system failure (hardware).

Programming Errors

1. Define syntax errors


Syntax error is a programming error in which the grammatical rules of the language are
broken. That is, program errors that occur due to violation or disobedience of rules of the
programming language. The syntax of a program refers to the rules defining the legal
sequences of symbolic elements in a particular language. When syntax error occurs, the
program execution is halt until the error or bug is detected, located and corrected. Syntax
errors can be detected by the compiler; this is why it is often referred to as compilation
error. That is, it is detected at the time when the translator program is translating the
program from HLL to machine language.
Syntax errors have the following basic characteristics;
1. Errors in the construction of executable statements such as misspelled word,
unmatched parenthesis, comma out of place
2. Detected by the computer at compiler time
3. Computer cannot correct error, so object program is not generated and thus
program is not executed
4. Computer (compiler) prints error messages, but continues to compile.

2. Run-time errors (execution error)


This is an error that occurs during the execution of a program. For a run-time error to
occur, the program must have been complied first successfully. It usually has the following
characteristics:
Run-time errors basic characteristics;
1. Program is compiled OK, but something goes wrong during execution e.g division
by zero or an attempt to read data that does not exist.
2. Detected by the computer run-time system

51 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
3. Computer usually prints error message and stops.

3. Logic/Semantic Errors
This is an error that occurs due to insufficient logic or erroneous logic. Such errors causes
a program to produce invalid output or to crash (lock up). Bad instruction logic misdirects
the computer to a place in the program where an instruction does not exist, and it crashes.
A program with bad logic may produce bad output without crashing, which is the reason
extensive testing is required. For example, if the program is supposed to add an amount,
but subtracts it instead, bad output results, although the program is executed.

Logic errors have the following basic characteristics;


1. Program compiles and executes OK but produces unexpected or incorrect results.
2. It is usually detected by programmer
3. Hardest to detect, locate and find.

THE CONCEPT OF DEBUGGING

Debugging is the art of diagnosing errors in programs and determining how to correct
them. It can also be described as identification and removal of localized implementation
errors from a program. Bugs come in a variety of forms, including: coding errors, design
errors, complex interactions, poor user interface designs, and system failures. Learning
how to debug a program effectively, then, requires knowing how to identify the problem
and applying the appropriate techniques to eliminate it.

Program debugging is often supported by a debug tool, a software tool that allows the
internal behavior of the program to be investigated in order to establish the existence of
bugs. To detect, locate, and correct a malfunction or to fix an inoperable system, the term
troubleshoot is more commonly used in hardware contexts.

Basic Debugging Techniques/Steps


Although each debugging experience is unique, certain general principles can be applied
in debugging. This section particularly addresses debugging software, although many of
these principles can also be applied to debugging hardware.
The basic steps in debugging are:
1. Recognize that a bug exists
2. Isolate the source of the bug
3. Identify the cause of the bug
4. Determine a fix for the bug
5. Apply the fix and test it

52 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
Step 1: Recognize a bug exists:
The goal of this step is to identify the symptoms of the bug. Observing the symptoms of
the problem, under what conditions the problem is detected, and what work-around, if
any, have been found, will greatly help the remaining steps to debugging the problem.
Step 2: Isolate source of the bug
This step is often the most difficult (and therefore rewarding) step in debugging. The idea
is to identify what portion of the system is causing the error. That is, where the error is
located. Unfortunately, the source of the problem isn't always the same as the source of
the symptoms. This step often involves iterative testing. For example, if an input record is
corrupted, an error may be detected if the program is processed with a different input
record. If the input was correct, but the output was not, then the source of the error is
within the module. By iteratively testing inputs and outputs, the debugger can identify
within a few lines of code where the error is occurring.
Step 3: Identify the cause of the bug
Having found the location of the bug, the next step is to determine the actual cause of the
bug, which might involve other sections of the program. A trained debugger can isolate
where a problem originates, but only someone familiar with the system can accurately
identify the actual cause behind the error. In some cases it might be external to the
software system. For instance, a situation where the input data was incorrect. In other
cases it might be due to a logic error, where correct data was handled incorrectly.
Step 4: Determine fix for bug
Having identified the cause of the problem, the next task is to determine how the problem
can be fixed. Here, the bug is removed and the program is modified. An intimate knowledge
of the existing system is essential because the fix will modify the existing behavior of the
system, which may produce unexpected results. Furthermore, fixing an existing bug can
often either create additional bugs, or expose other bugs that were already present in the
program, but never exposed because of the original bug.

In some cases, a fix is simple and obvious. This is especially true for logic errors where the
original design was implemented incorrectly. On the other hand, if the problem uncovers
a major design flaw that permeates a large portion of the system, then the fix might range
from difficult to impossible, requiring a total rewrite of the application.
In some cases, it might be desirable to implement a "quick fix", followed by a more
permanent fix. This decision is often made by considering the severity, visibility,
frequency, and side effects of the problem, as well as the nature of the fix, and product
schedules.

53 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
Step 5: Fix and test
After the fix has been applied, it is important to test the system to determine if the fix
handles the former problem correctly. After significant bug fixes, tests can be repeated at
any time to verify that the system still executes as expected. As new features are added,
additional tests can be included in the test suite.

SOFTWARE MAINTENANCE

Software maintenance is the modification of a software product after delivery to improve


performance or other attributes, to correct faults, or to adapt the product to a modified
environment.

Categories of Program maintenance


The three categories of maintenance as identified by E.B. Swanson are: corrective,
adaptive, and perfective maintenance
1. Adaptive maintenance: Modification of a software product performed after delivery
to keep the software product usable in a changed or changing environment.
2. Perfective maintenance: Modification of a software product after delivery to
improve performance or maintainability.
3. Preventive maintenance: Modification of a software product after delivery to detect
and correct latent faults in the software product.

Six Software Maintenance Processes


The international standard describes these processes as:
1. Implementation Process: The implementation process contains software preparation
and transition activities, such as the conception and creation of the maintenance plan,
the preparation for handling problems identified during development, and the follow-up
on product configuration management.
2. Problem and Modification Analysis Process: This process is executed once the
application has become the responsibility of the maintenance group. The maintenance
programmer must analyze each request, confirm it (by reproducing the situation) and
check its validity, investigate it and propose a solution, document the request and the
solution proposal, and, finally, obtain all the required authorizations to apply the
modifications.
3. Implementation Process: Having obtained all the required authorizations to apply the
modifications, this process sees to the implementation of the modifications.

54 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale
4. Acceptance of the Modification Process: This process acceptance of the modification
is done by checking with the individual who submitted the request in order to make sure
the modification provided a solution.
5. Migration Process: The migration process is exceptional as it is only used when the
software is to be ported to another platform without any change in functionality.
6. Retirement of a Piece of Software Process: This process is that in which the
maintenance process is certified as effective and thus ended until another request for
modification is made in the future.

Difference between program maintenance and debugging


Debugging has been defined as an art of diagnosing errors in programs and determining
how to correct them while software maintenance is the modification of a software product
after delivery to improve performance or other attributes, to correct faults, or to adapt the
product to a modified environment. This major difference is that while debugging is mainly
used for corrective actions, maintenance goes beyond to include improvement of the
performance of the software product.

55 CTE 114 -- INTRODUCTION TO PROGRAMMING ND I CET


Not for Sale

You might also like