Cte 114 Intro. To Computer Programming Lecture Note
Cte 114 Intro. To Computer Programming Lecture Note
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.
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.
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.
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.
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:
Disadvantages:
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.
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.
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.
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
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
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 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.
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
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
Types of Variable
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
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!
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
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
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:
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
Class Work
(b) COMP = A2 + B2
(c) DIVN = C + A2 + B2
COS A + SIN B
(d) Area= (4/3) πr3h3
(e) Z = y2 + x
q
Relational operators
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.
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.
Expression NOT
EXAMPLES
If a=2 , b= 5 , c = 7,
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.
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.
• 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.
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:
Associativity determines the order in which operators of the same precedence are
processed. For example, consider an expression:
a OPERATOR b OPERATOR c
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.
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 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?
Pseudocode can also be defined as an artificial and informal language that helps
programmers develop algorithms.
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.
Note the three types of instructions: input (enter), process/calculate (=) and output
(display)
Method 1
SUM = X + Y
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
Example 2: Develop an algorithm to find the average of four numbers stored in variables
A, B, C, and D.
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
Where S = a + b + c
1
3. Write an algorithm for calculating the area of a trapezium. Hint: Area = (a + b)h
2
FEATURES OF ALGORITHM
INTRODUCTION TO FLOWCHARTS
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.
1. Start and end symbols: This is represented as ovals or rounded rectangles, usually
containing the word "Start" or "End" or “Return”.
1. In drawing a proper flowchart, first, develop the algorithm for the problem.
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.
Example of a flowchart:
Algorithm: START
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 calculate the area of a trapezium. Hint: Area =
1
(a + b)h
2
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.
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.
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
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.
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.
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:
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
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.
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.
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:
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
CLS
Area = .5 *(a+b)*h
PRINT “ The result for the calculation of area of the trapezium is”; Area
END
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
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
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.
CLS
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
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.
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
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
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
CLS
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
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
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 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
4 3 12 7
4 4 16 8
5 2 10 7
5 3 15 8
4 4 20 9
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
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 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.
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)
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.
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
1. start
2. input mark
3. if mark >= 40 then
4. Print "passed"
5. else
6. Print "failed"
7. Endif
8. End
1. start
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
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
end
NOTE: THE LAST TESTING PARAMETER BEFORE ENDIF IS ELSE AND NOT ELSEIF.
Example 1
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
CLS
Start:
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."
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
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.
N$(0) = "Ted"
N$(1) = "Jack"
N$(2) = "Jill"
N$(3) = "Fred"
FOR i = 0 TO 3
PRINT N$(i)
NEXT i
24 31 15 67 34 87 92 14 34 62
A(1) = 24
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.
Programming Errors
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.
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.
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.
SOFTWARE MAINTENANCE