Introduction To Program Com113
Introduction To Program Com113
For
INTRODUCTION TO PROGRAMMING
COM113
NATIONAL DIPLOMA
YEAR 1 SEMESTER 1
Week 1-13
1
WEEK 1
SPECIFIC LEARNING OUTCOMES
To understand:
Concept of programming
Features of a good program
Systems development cycle.
2
CONCEPT OF PROGRAMMING
A program is a set of instructions that tells the computer what to do. Computer programming (often
shortened to programming or coding), is the process of writing, testing, debugging/troubleshooting and
maintaining act of instructions (source code) for solving a problem with the computer. A source code is
written in an acceptable computer programming language. The code may be a modification of an
existing source or something completely new.
The purpose of programming is to create a program that exhibits a certain described behavior
(customization). The process of writing source code requires expertise in many different subjects,
including knowledge of the application domain. Alternatively, Programming is the craft of transforming
requirements into something that a computer can execute. Problem solving on computer is a task of
expressing the solution to the problem in terms of simple concepts, operations and computer code
(program) to obtain the results. To achieve this aim, you may proceed as follows:
1) First, understand the problem clearly:- Decide what you want to be calculated by the computer.
What will be the input data required? (If any). This is the problem formulation.
2) Write the steps of computation that are necessary to arrive at the solution. This is setting up the
algorithm.
3) Prepare a flowchart corresponding to the algorithm.
4) Develop the computer program. Test and run it on the computer.
There is an ongoing debate on the extent to which the writing of programs is an art, a craft or an
engineering discipline. Good programming is generally considered to be the measured application art,
craft and engineering, with the goal of producing an efficient and maintainable software (program)
solution. The discipline differs from many other technical professions in that programmers generally do
not need to be licensed or pass any standardized (or governmentally regulated) certification tests in order
to call themselves “programmers” or even “software engineers”.
FEATURES OF A GOOD COMPUTER PROGRAM
1) Accuracy: Any developed system has a purpose for which it is developed. A developed program
is a failure if it cannot meet the objectives for which it is proposed and designed. A good
program must performs the intended functions without errors.
2) Legibility: This involved writing code in a clear and understandable manner, making it easier for
others (or oneself) to read and maintain,
3) Understandability: The program codes will be easy for a programmer to read and understand
the logic involved in the programming.
3
4) Maintainability: A good program design will always be easy to change or modify when the
need arises. Programs should be written with the maintenance activity in mind. The structure,
coding and documentation of the program should allow another programmer to understand the
logic of the program and to make a change in one part of a program without unknowingly
introducing an error in another part of the same program.
5) Efficiency: The amount of system resources a program consumes (processor time, memory
space, slow devices, network bandwidth and to some extent even user interaction), the less the
better.
6) Reliability: Any developed program for a particular application can be depended upon to do
what it is supposed to accomplish. How often the results of a program are correct. This depends
on prevention of resulting from data conversion and prevention of errors resulting from buffer
overflows, underflows and zero division.
7) Generality: The program should be general within reasonable limits. Placing fixed values into
the program is not good programming practice. The program developed for a particular task, and
then it should also be used for all same purpose. For example, if a program is developed for a
particular organization, then it should suit all other similar organizations.
STAGES IN PROGRAM DEVELOPMENT
In other to produce a good program as previously described, the following steps in the order indicated
should be followed. Attempt to "save time" by skipping either of the steps or changing the order usually
end up costing more time and production of a faulty and inefficient program.
1. Problem definition and analysis
The programming problem should be studied carefully in order to understand what it is all about, it's
functions and requirements. In particular, the information (output) required, and the (input) data
supplied, if any. The study of all system design materials produced by the system analyst should be
carried out. Such materials include record layout charts, printer spacing charts and the program
specifications.
2. Providing method of solution
This step requires that you find necessary processing methods required to obtain the expected result
(output) from the given (input) data. You may have more than one way of solving a problem. This step
requires that you select the "best method". For example, to compute roots of a quadratic equation of the
form ax² + bx + c =0; you may use
Graphical method
i. Method of completing square
4
ii. The so-called "Almighty-formula".
iii. The “Almighty - Formula" is more amenable to computer solutions.
5
After the program has been tested and completely debugged the structure chart, detailed
flowchart program descriptions or pseudo-code, of the logic and coding, test data, test runs with test
output and source listings etc. should be assembled and saved for future maintenance purposes.
ARITHMETIC OPERATORS
The following are used for arithmetic operations.
SYMBOL EXAMPLE MEANING
+ A+B Addition
- A-B Subtraction
* A*B Multiplication
/ A/B Division
= A=B A equals B
> A>B A greater than B
< A<B A less than B
>= A>=B A greater than or equal to B
<= A<=B A less than or equal to B
= A<>B A not equal to B
6
WEEK 2
SPECIFIC LEARNING OUTCOMES
To understand:
The Concept of Algorithm
Definition of Algorithm
Features of an Algorithm
Methods of representing Algorithm
7
CONCEPT OF ALGORITHM
Algorithm is a step-by-step procedure which is used to solve a problem. Computer needs precise and
well-defined instructions for finding solution of problems. If there is any ambiguity, the computer will
not yield the right results. It is essential that all the stages of solution of a given problem be specified in
details, correctly and clearly moreover, the steps must also be organized rightly so that a unique solution
is obtained.
Algorithm is a well-defined computational procedure, which takes some value (or set of values) as input
and produces some value, or a set of values, as output.
9
stores the result into memory location R1. The old value of location R1 is destroyed but those of c and b
remain intact.
METHODS OF REPRESENTING ALGORITHM
Algorithms are statements of steps involved in solving a particular problem. The steps to the solutions
are broken into series of logical steps in English related form. Programs are written to solve real life
problems. There can‟t be a solution if there is no recognized problem and once a problem exist, one
must take certain step in order to get a desired solution. The following methods could be used to
represent an algorithm.
Methods of English Language
Methods of Flowchart
Methods of Pseudo code
Methods of Decision table
Methods of Data flow Diagram (DFD)
Pseudo Code
A pseudo code is the English-like representation of the program logic. It does not make use of standard
symbols like the flowchart. It is a sequential step by step arrangement of the instructions to be performed
to accomplish a task. It is an informal and artificial language that helps programmers develops
algorithms.
Structured programming is a universally accepted method of producing good program codes with
the properties of being.
- Less error prone
- Easy to read and understand
- Easy to debug
- Easy to maintain
Example 1
Write a pseudo code to find the area of a room.
Solution:
Begin process
Input room length
Input room breadth
Multiply length by breadth to get area
Print area
End process
10
Example 2
Write a Pseudo code for finding the greatest of 3 numbers represented as A, B, and C.
Solution:
Begin process
Input A,B,C
If A>B then big = A
Else big = B
If big >C then biggest = big
Else biggest = C
Example 3
Write an Algorithm to determine a student‟s final grade and indicate whether it is passing or failing.
The final grade is calculated as the average of four marks.
Solution:
Start
Input a set of 4 marks
Calculate their average by summing and dividing by 4.
If average is below 50
Print “Fail”
else
Print “Pass”
Pseudo code
Step 1: Input M1, M2, M3, M4
Step 2: Grade ← (M1 + M2 + M3 + M4)/4
Step 3: If (Grade < 50) then
Print “FALL”
else
Print “Pass”
End it.
Example 4
Write an Algorithm to compute and output the average of 3 numbers a,b and c.
Step 1: Start
Step 2: Input a,b,c
Step 3: Compute Sum = a+b+c
11
Step 4: Compute Average = Sum/3
Step 5: Output Sum, Average
Step 6: Stop
Pseudo code
1. Input a,b,c
2. Calculate sum = a + b + c
3. Calculate Average = sum/3
4. Output sum, Average
5. Stop
Example 5:
Write algorithm to compute and print the circumference of a circle
The required steps are:
Step 1: Start
Step 2: Input Radius
Step 3: let pi = 3.142
Step 4: area = pi *r*r
Step 5: Circum = 2 * pi * r
Step 6: Print area, circum
Step 7: Stop
12
WEEK 3
SPECIFIC LEARNING OUTCOMES
To understand:
The Concept of Algorithm
Definition of Algorithm
Features of an Algorithm
Methods of representing Algorithm
13
English Language
The English form of representing algorithm entails breaking down the solution steps of the problem into
single and sequential English words. The steps are represented in English to say what action should be
taken in such a step.
Example 1
Develop an algorithm to obtain a book on computer from your school library located on the fourth floor
of the building. You are to proceed to the library from your ground floor classroom.
1. Start from the classroom
2. Climb the stairs to the 4th floor and reach the library
3. Search a book on computer
4. Have the book issued
5. Return to your classroom
6. Stop.
Note: The above algorithm solution of example 1, has been written in simple and clear English way.
Example 2
Develop an algorithm to find the average of four numbers stored in variables A,B,C,D
Solution
1. Start
2. Read values in variables A,B,C,D
3. Calculate the average as (A+B+C+D)/4 and store the result in P.
4. Write the value stored in P
5. Stop.
Example 3
Develop and algorithm to find the average of four numbers stored in variables A, B, C, D. When the
value of variable A is zero, no averaging is to be done.
Solution
1. Start
2. Read values stored in variable A,B,C.D
3. If the value of A is Zero, then jump to step 6
4. Calculate the average of A, B, C, D and store the result in variable P.
5. Write the value of P
6. Stop.
14
Flowchart
Flowchart is a representation of the algorithm using standard symbols. Each symbols has a new
function. The Algorithm steps determine which symbol to use to represent it in the flow each step
is linked to another step by using the directional arrows.
15
Decision table
A decision table is a form of truth table that structures the logic of a problem into simple YES
and No form. It is easily adapted to the needs of business data processing. It is a rectangle
divided into four sections called quadrants. It provides a structure for showing logical
relationships between conditions that exist and actions to be taken as a result of these conditions.
The condition entries
Condition 1 2 3 4 5 6 7 8
Printer is unrecognized Y N Y Y N N Y N
Action
Example 2: A mobile service provider will allow a person to be a subscriber to their network
16
provided if the following conditions are met:
They must have a bank or building society account
They must have lived at the same address for at least a year
They must be a home owner
Condition 1 2 3 4 5 6 7 8
Is a home owner Y N Y Y N N Y N
Action
Can Subscribe X
Cannot Subscribe X X X X X X X
1) The number of condition is used to determine the number of entries by using the
formula, where n is the number of condition.
Condition stub:- This gives a list of all the conditions that are relevant to the system.
Action entry: - This quadrant indicates whether a specific action will be taken or will not
be taken
1) They are simple, practicable and economical .All that is regarded to developed a decision
table is a piece of paper and a pencil
2) It makes the system designer to express the logic of the problem in direct and concise terms,
which results in the development of an effective and efficient program.
3) It is useful in program documentation i.e decision tables provide a quick and easily
understood over view of the system.
17
4) It is an excellent communication device to breach the gap between the computer personnel
who are responsible for developing the system and the non data processing personnel who
use the output of the system.
7) The complexity and the amount of detail that can be handed by a decision table is un-
limited.
Disadvantages
1 Total sequence: The total sequence of an operation is not clearly shown in the
decision table i.e no overall picture is given as with flowcharts.
2 Logic: Where the logic of a system is simple flowcharts always serve the
purpose better.
ASSIGNMENT
Example 1: A website having the registration functionality and the vital information needed
include name, email, & address to register.
Use data flow diagram to show the three requirement that the registration depend on.
19
WEEK 4
SPECIFIC LEARNING OUTCOMES
To understand:
Definition of flowchart
20
FLOWCHART
A flowchart is a pictorial representation of an Algorithm or of the plan of solution of a problem. It
indicates the process of solution, the relevant operations and computations, point of decision and other
information that are part of the solution. Flowcharts are of particular importance for documenting a
program. Special geometrical symbols are used to construct flowcharts. Each symbol represents an
activity. The activity could be input/out of data, computation/processing of data, taking a decision,
terminating the solution, etc. The symbols are joined by arrows to obtain a complete flowchart.
FLOWCHART SYMBOLS
START
Following this, step in the pseudo code representation have corresponding flowchart symbol to
represent it dramatically. For example the step;
1. Output a,b will be represented dramatically as:
Input a,b
calculate A = b- c
The arrow symbol ( ) is used to connect 2 flowchart symbols together to indicate that the two
operation follow each other in sequence. For example assume the following 3 operations follow each
other in sequence:
22
2 input a,b
3 calculate c = a +b
4 output c
The flowchart represent of the 3 operations will be
Output a,b
2. Input a,b.........................................
Calculate C=a+b
3. Calculate c = a + b……………………
Output C
4. Output c ………………………………
More real life programming example are now given to illustrate design of algorithm using flowchart.
Example 1
Draw a flowchart to find the average of four numbers stored in variables A,B,C,D.
Solution
Start
Read numbers in
A,B,C,D
Stop
23
Example 2
A flowchart to find greater number between two numbers
Example 3
Write an algorithm and draw a flowchart that will read the two sides of a rectangle and calculate its area.
Solution
Pseudo code
Begin process
Input the Width(w) and Length(L) of a rectangle
Algorithm
Step 1: Start
Step 1: Input W, L
Step 2: A← L * W
Step 3: Print A.
24
Flowchart
Stop
Input W,L
A←L*W
Print A
Stop
Example 4
Flow chart to print a message if x is greater than 5 or less than 5
Start
Input x
Yes No
x>5
Output msg
Stop
25
Example 5
Write a pseudo code with flow chart to find the area of two squares and add them.
Pseudo code
Step 1: Start
Side A A + B Side B
Start
Side A Side B
Step 2: Input side A
Step 3: Input side B
Input side A
Step 4: calculate Area A = side A * side A Input side b
Step 5: calculate Area B = side B * side B
Step 6: calculate total = Area A + Area B
Calculate Area A = side A * side A
Step 7: Print total
Calculate Area B = side B * side B
Step 8: stop
Calculate total = Area A + Area B
Print total
Stop
Uses of flowcharts
3 It provides a tool for communicating i.e a flowchart helps to explain the system to others.
5 It allows us to see what will happen if we change the values of the variable in the system
ADVANTAGES OF USING FLOWCHART
3 The analyst/ programmers may leave the arrangement or they may forget the logic of the program.
6 Analysis: flowcharts help to clarify the logic of a system i.e the overall picture of the
26
organization can be seen.
27
WEEK 5
SPECIFIC LEARNING OUTCOMES
To understand:
Design algorithm for problems involving.
Strictly sequence control structure
Selection control structure
Iteration control structure
28
DESIGNING ALGORITHM FOR COMMON PROGRAMMING LOGIC STRUCTURES
Sequence Control Structure
Implicitly, by default, the normal order of executing program statements is sequential. That is,
statements are executed one after the other in the sequence they physically appear in the program.
Sequence control structure represents a processing steps to be executed by the computer one after
the other in sequence of the order they are written. This control structure is illustrated below:
Step 1
Step 2
Step - n
The operation in the inner most parenthesis will be carried out first.
These steps can be arithmetic operation, assignment operation, subprogram call statement etc. example
above shows that Step1 will be carried out before steps 2, steps 2 before step3 and so on. Examples of
specific statements of actions or commands to be carried out sequentially are:
Add 1 to A
Print Result
29
Assign A to B
Input values of A, B, and C.
Example
Write an algorithm to compute and output the average of 3 numbers a,b, and c. Before the required
information (i.e Average) can be calculated, the values of a, b and c must be given (input) to the
computer. After the calculation, the average' must be explicitly output to the user. Thus the required
steps in sequence are:
1. Input a,b,c.
2. Compute Sum = a+b+c
3. Compute Average = Sum/3
4. Output Sum, Average
5. Stop
Example
Write algorithm to compute and print the circumference of a circle with diameter d.
The required steps are:
1. Input d
2. Calculate circumference = 3.142*d
3. Output circumference
4. Stop
30
our discussion on selection structure. The structure of a binary selection is diagrammatically depicted as
shown below:
False True
?
False True
Action Action
Display calculation
End
Example 2: use a structured (pseudo-code) algorithm to compute and print a salesman's commission
giving that commission is 10% of sales provided sales > 50.00; otherwise, no commission is given.
Solution
1. Input sales
2. If sales < 50
2.1 comm = 0.0
3. Else
3.1 comm = (10/100) * sales
4. ENDIF
32
5. Print sales, comm
6. Stop.
Example 3
Below is a pseudo-code to accept 2 values x and y and output the greater of the number.
1. Input X,Y
2. if X >Y
2.1 PRINT X
3. ELSE
3.2 PRINT Y
4. ENDIF
5. STOP
Example 4
Below is a pseudo-code of a program to compute and display the profit or loss made by a
business man who bought Q units of certain goods at #C per unit and sold it at #S per unit.
1. Input Q, C, S
2. Calculate cost price =Q*C
3. Calculate selling Price = Q *S
4. Calculate Profit loss = Selling Price – Cost Price
5. If Profit-loss > 0
5.1 Print "Profit =", Profit-loss
6. ELSE
6.1 Calculate loss = Profit -loss * (-1)
6.2 Print "Loss =", Loss
7. ENDIF
8. STOP
MULTIWAY/MULTIPLE SELECTION
Multiway selection allows a user to select from more than two options. In Pseudocode, the
keywords used for multiway selection include CASEWHERE, OTHERWISE and ENDCASE.
CASEWHERE: Placed before the listing of conditions
OTHERWISE: What to do if none of the set conditions are met
ENDCASE: Concludes the case selection
After the use of the CASEWHERE statement, the next line is indented with each potential case on a new
line.
33
Pseudocode Example: Basic Calculator
A program is to be developed that allows a user two enter in two different numbers. The software is to
either add, subtract, multiply or divide the numbers at the users discretion. Result is to be displayed to
the user.
BEGIN Basic Calculator
Get Number l
Get Number2
CASEWHERE Calculation
Subtraction (-) : Numberl - Number2
Multiplication (*) : Numberl * Number2
Division (/) : Numberl / Number2
OTHERWISE : Numberl + Number2
ENDCASE
Display Calculation
END Basic Calculator
BEGIN
Get number 1
Get number 2
Calculation
=
Display Calculation
End
34
WEEK 6
SPECIFIC LEARNING OUTCOMES
To understand:
Design algorithm for problems involving.
Strictly sequence control structure
Selection control structure
Iteration control structure
35
Iteration Logic (Repetitive flow)
The repetition structure can also be called a loop. In a loop, an operation or a set of
operation is repeated until some condition is satisfied. The basic form of repetition is termed DO
WHILE in the literature of structured programming. In some languages, the repetition structure
might be termed PERFORM UNTIL. In the perform until pattern, the program logic tests a
condition; if it is true, the program executes the operation and loops back for another test. If the
condition is true, the repetition ceases, is normally depicted by the diagram below
yes
Condition
true Yes - action
?
No
ITERATION CONTROL STRUCTURE
The iteration control structure in this (pre-test) iteration structure, the condition is first tested
before any execution of the action-block (called loop body). If the condition is true, the action block will
be carried out, followed by another testing of the condition. The loop or structure is terminated once the
specified condition is no longer valid. This control structure is generally denoted by a DO-WHILE-
ENDDO construct. It is of the form:
DO WHILE (Condition)
statement -1
statement -2
“
“
statement n
ENDDO
Statement -1 to statement-n will be repeatedly carried out until the condition is no longer true.
Usually the condition is first tested before executing statement -1 to statement -n. Furthermore one of
the statement between the DO WHILE and ENDDO Will be meant to alter the condition specified, thus
providing the means of terminating the algorithm.
36
Example 1: Write an algorithm for a program to calculate and print out the perimeter of ten rectangles
with given length and breadth.
Solution:
The steps required for processing one rectangle will be repeated 10 times for the above problem.
To solve this problem, a counting variable, say counter, will first be set to zero i.e Counter = 0. This is
because the necessary steps for one rectangle have not been carried out at all. The algorithm for
calculating the perimeter of one rectangle is given by:
1. Input l, b
2. Calculate perimeter = 2(1+ b)
3. Output perimeter
The 3 steps above are required for calculating the perimeter of the rectangle. These 3 steps will
have to be repeated 10 times to solve the given problem.
To indicate that one rectangle has been processed, the counting variable will have to be
incremented by 1; i.e Counter = Counter + 1.
This step (incrementing the counter by 1) will be part of the operation or processing required for one
rectangle. That is, the following 4 steps will be required:
1. Input l,b
2. Calculate perimeter =2 (L+b)
3. Output perimeter
4. Increment Counter by 1 (i.e Counter = Counter 1)
these 4 steps will have to be repeated as long as the value of the counting variable is less than 10 (i.e the
required number of rectangle to be processed). That is, the 4 steps will be repeated as long as Counter <
10. These 4 steps will now have to be enclosed within the DO- WHILE ENDDO structure. That is;
DO WHILE (Counter < 10)
1. Input l, b.
2. Calculate perimeter = 2 (l+ b)
3. Output perimeter
4. Counter = Counter +1
ENDDO
Thus the complete algorithm for the given problem is:
1. Set Counter =0
2. Do while (Counter < 10)
2.1 Input l,b
37
2.2 Calculate perimeter 2(l+b)
2.3 Output perimeter
2.4 Counter = counter + 1
3. Enddo
4. Stop
To repeat the same operation for 1000 rectangles, is a trivial matter. All that is required is to change the
terminating condition (Counter < 10) to (Counter < 1000).
Example is too specific to a particular number of rectangle This is why it has to be modified
when the operation is required for 1000 rectangles. If only 5 rectangles are to be processed, it will have
to be modified again. A more generalistic program for this problem that will not require frequent
amendment will be to develop an algorithm to process n rectangles, where n > 0.
Example 2
Write algorithm for a program to calculate and output the perimeter of n (n > o) rectangles. With given l
and b.
Solution: To do this we must first know the value of n. we obtain this through the keyboard. After
obtaining the value of n, the algorithm below will do the job, excepting that the terminating condition
will now have to be changed to (Counter < n). Thus the algorithm for the problem is:
1. Input N
2. Counter = 0
3. Do while (Counter < n)
3.1 Input l,b
3.2 Calculate perimeter = 2 (1 + b)
3.3 Output perimeter
3.4 Counter = Counter + 1
4. Enddo
5. Stop
Similarly, the pseudo-code for computing and printing the area of 3 triangles given the base b
and height h is as shown below.
Example 3:
1. Let I = 0
2. Do While (I < 3)
2.1 Read b,h
2.2 compute Area A = 1/2b*h
38
2.3 output b,h, Area
2.4 I=i+l
3. Enddo
4. Stop
There are various variations of the iteration control structures. This control structure is
implemented in different ways in different programming languages.
Note:
i. Steps 2.1, 2.2 and 2.3 are repeated until I is no longer less than 3
ii. Step 2.3 in the algorithm says = i +1. This is, a common statement in many Computer programs.
The meaning or semantics of the statement is that the new value of I equals the old value plus 2.
Similarly, a statement like P= P*Q means that the new value of P equals the old value of P
multiplied by Current value of Q.
iii. The counting variable is called the loop controlling variable. Its value is being altered by step
2.3, thus providing the means of terminating the loop.
Quiz: What will be the result if step 2.3 is not made part of the loop?
Note: Recollect that to carry out similar operation on 1000 triangles only requires changing the
terminating condition of example three in step 2 from Do while (i<3) to Do while (i<1000).
Example 3: can be modified to calculate and output the areas of triangles, m> 0. as given in the
algorithm below.
Example 4
Algorithm to calculate and output areas of m different triangles.
1. Input m (asking for number of triangles)
2. i= o
3. Do while (i < m)
3.1 Read b,h
3.2 Calculate Area = ½ * b*h
3.3 Output Area
3.4 i=i+1
4. Enddo
5. Stop
39
Example 5: Algorithm to input and display 100 names is:
1. K=0
2. Do while (K< 100)
2.1 Input name$
2.2 Output Name$
2.3 K=K+ 1
3. Enddo
4. Stop
Note: Example 5: can be modified to input and display n names as given below:
Example 6: Algorithm to input and display n names.
1. Input n (The statement asks for value of n)
2. K=0
3. Do while (K <n)
2.1 Input Name$
2.2 Output Name$
2.3 K = k+1
4. Enddo
5. Stop
Example 7: Algorithm to input and display given names until a name is "stop".
1. Input name$
2. Do while (name$ = “stop)
2.1 Output names$
3.1 Input name$
4. Enddo
5. Stop
Note:- This is an example of repetitive operation to be carried out until a given condition is satisfied. No
specific number of times for its repetition is given. However the terminating condition is when
names="stop".
This algorithm can be modified to display the number of names processed.
Example 8
Algorithm that display, input names until a given name is "stop". It displays the number of names
processed).
1. K= 0 (Variable counting number of names processed)
40
2. Input Name$
3. Do while (Name$ "stop")
3.1 Output Name$
3.2 K =k+l
3.3 Input name$
4. Enddo
5. Output "No of names processed =", K.
6. Stop
For example let us take 10 sets of numbers each set containing three. The problem is to get the
biggest number in each set and print it.
Algorithm
41
WEEK 7
SPECIFIC LEARNING OUTCOMES
To understand:
Identify the problem and confirm it solvable.
Design algorithm for the chosen method of solution with flowcharts or pseudo codes.
42
HOW DO YOU WRITE AN ALGORITHM IN PYTHON?
Algorithms written in Python or any other language are most commonly written in a step-by-step
manner that clearly defines the instructions a program needs to run.
Though there is no defined standard as to how you should write algorithm, there are basic shared code
constructs between languages that we often use to create an algorithm, such as loops and control flow.
Algorithms are written to solve problems and overcome challenges in development, so ensuring that a
problem is well defined is key to writing a solution. Oftentimes, there may be multiple solutions to a
given problem and many algorithms may be implemented at once as a way of helping the program find
the best solution available.
However the solution is implemented, an algorithm should contain six characteristics.
HOW TO WRITE A PYTHON ALGORITHM: 6 CHARACTERISTICS
43
Example3: A program to output student grade
Marks = int(input("Please enter the marks:"))
grade=""
if(marks>=80):
grade="A Grade"
elif (marks>=60):
grade="B Grade"
elif (marks>=50):
grade="C Grade"
elif (marks>=45):
grade="D Grade"
else:
grade="fail"
print("Marks:", marks)
print("Grade:",grade)
44
Example 6: A python program to find the area of triangle
#Input the base and height of the triangle from the user
base = float(input("Enter the base of the triangle: "))
height = float(input("Enter the height of the triangle: "))
#Calculate the area of the triangle
area = 0.5 * base * height
#Print the area of the triangle
print(f"The area of the triangle with base {base} and height {height} is: {area}")
45
WEEK 8 & 9
SPECIFIC LEARNING OUTCOMES
To understand:
Explain modular programming concept.
46
THE CONCEPT OF MODULAR PROGRAMMING
As program become larger, and more complex, it becomes more difficult to write clear
understandable solutions that work correctly. The goal of modular programming is to break up
the program into small parts that are more easily understood. The planning, coding and testing
can be done on these small, relatively simple units, rather than on one large, complex body of
code.
MODULAR PROGRAMMING
One popular technique in designing program structure is called modular programming This is the
process by which a large called program modules A program module is a well-defined program
programming tasks can be sub-divided into smaller parts or functions segment which performs a specific
task For e.g. if a program is meant reasonable to have separate modules to handle each of the main to do
matrix addition, subtraction, multiplication and inversion, it is operation viz: addition, subtraction,
multiplication and inversion
1) At a higher a level, a module can be a subprogram which can be separately compiled and tested.
2) At the lower level it can be an "open" subroutine such as macro, se functions. internal
procedures, function, etc
47
BASIC PROGRAM STRUCTURE CHART
A structure chart is a diagram in which program modules are represented by rectangular r boxes and the
inter module relationship by means of connecting lines.
There are 2 basic forms of program structure. These are hierarchical and network.
Hierarchical Program Structure
In this structure, there is a single module at the top with one more subordinate modules. The singular top
module is superior to its subordinate modules, however, these subordinates may themselves have
additional subordinate modules to which they are superior. Any given module can be subordinate to only
one superior, but may be superior to one or more subordinate modules. The figure below illustrate this
structure.
Level 0 A
Level 1 B C
E F A
Level 2 D
48
Example 1: Draw a hierarchical structured chart for a program to input 2 numbers x and y and output
the result when any of the four basic arithmetic is carried out on them.
Arithmetic
Operations
?
1 2 3 4
B C
B C
D
D E
Representation of Network Structure
One clear mark of program complexity is obviously the number of modules in a program.
However, the greater source of complexity the number of inter-module relationships. Such relationship
indicated by the network structure in tends to undo the benefits derived from modularization by making
functional distinctions between program modules less clear. Thus resulting in program structure that are
complex, difficult to understand and difficult to modify. As a result of all these, hierarchical, rather than
network structures are the preferred form of program structures.
49
TOP DOWN DESIGN APPROACH
The process by which well-partitioned modular program can be structured into hierarchies is
called top-down design.
In top-down design, we begin by identifying one module that describes the overall functions of
the program., Then we proceed to partition this overall function into its main components. For e.g
suppose that the overall function is "process student result". The main components are House-keeping-
and-heading. process-routine, print-class-average and print-summary-lines.
PROCESS RESULT
PROCESS RESULT
50
task that ultimately can be expressed in one cohesive module. A cohesive module is one that performs
only one function and all program statements in the module are directly related to that function only.
Top-down design is a well- tested and effective method of developing good program designs. A
complete design for the program is as shown below.
Note:
The curve arrow from process-result module to process-routine is used to indicate a looping situation. It
represents repetitive invocation of process-routine by process-result.
PROCESS RESULT 1
51
WEEK 10 & 11
SPECIFIC LEARNING OUTCOMES
To understand:
Explain machine language, low-level language and High level languages
52
LEVELS OF COMPUTER PROGRAMMING LANGUAGES
The generally accepted dictionary definition of language is that it is a "notational system for
communication". A programming Language is thus a notational system for communicating with the
computer. That is, a programming language is a means by which users is express what they want
computer to do for them. Examples of programming language are BASIC, FORTRAN, COBOL, PL/1,
C, JAVA etc.
Programming language can be categorized into 3 main levels: machine language, low-level language
and high-level language. Each category or level of programming language has its own distinguishing
features, advantages and disadvantages.
MACHINE LANGUAGE
Machine Code or machine language is a low-level programming language that can be understood
directly by a computer‟s central processing unit (CPU). Machine code consists of sequences of
binary numbers, or bits, which are usually represented by 1s and 0s, and which form the basic
instructions that guide the operation of a computer. The specific set of instructions that
constitutes a machine code depends on the make and model of the computer‟s CPU. For instance,
the machine code for the Motorola 68000 microprocessor differs from that used in the Intel
Pentium microprocessor.
Writing programs in machine code is tedious and time-consuming since the programmer must
keep track of each specific bit in an instruction. Another difficulty with programming directly in
machine code is that errors are very hard to detect because the program is represented by rows
and columns of 1s and 0s.
Features of Machine Language
The main feature or characteristic of machine language is that it is machine dependent or machine -
oriented. This means that each computer system has its own unique machine language and it is different
nt from any other machine language of another system This difference is due to the fact that different
machines have different word length. instruction sets and instruction formats. This is analogous to
human language like Yoruba, which has different dialects For example, we have the Igbomina, Ekiti,.
ljesa, etc All these are Yoruba languages but are different significantly from one another.
Advantages of Machine Language
1) Less code is produced
2) Storage is saved
3) User has direct control of machine instruction
4) Execution is faster as no translation is needed
5) The programmer knows all the registers and instruction that use them.
53
Disadvantages of Machine Language
3) The developed programs are error prone and difficult to debug (correct)
4) Programs written to be run on one computer machine cannot be run on another type of computer.
This is because each family of computer has its own unique ML which is tailor- made to its
individual hardware features.
1) High level language tends to be inefficient in the use of CPU and other facilities.
2) Machine code instructions are produced and then requires more storage spaces.
Program Command
It is used to indicate that which operating CPU It is used to tell application or system to do
should execute on set of data. something or perform task.
Types of programs include word processors, Types of command includes input program
game programs, graphic programs, data base commands, utility commands, internal
systems, etc. command, external command, etc.
Programs are handled by programmer who Commands are handled by part of operating
write compute programs. system i.e. command interpreter.
56
WEEK 12
SPECIFIC LEARNING OUTCOMES
To understand:
Debugging.
57
THE CONCEPT OF DEBUGGING AND MAINTAINING PROGRAM
Debugging is the art of diagnosing errors in programs and determining how to correct them. "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 that
you learn how to identify which sort of problem you're looking at, and apply the appropriate techniques
to eliminate the problem.
Bugs are found throughout the software lifecycle. The programmer may find an issue, a software tester
might identify a problem, or an end user might report an unexpected result. Part of debugging
effectively involves using the appropriate techniques to get necessary information from the different
sources of problem reports.
Debugging is described as identification and removal of localized implementation errors or bugs from a
program or system. 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. This
tool typically offer trace facilities and allow the planting of breakpoint in the program at which
execution is to be suspended so that examination of partial results is possible and permit examination
and modification of the values of program variables when a breakpoint is reached.
In computer program/software, a bug is an error in coding or logic that causes a program to malfunction
or to produce incorrect results. The computer software (debug tool) is used to detect, locate, and correct
logical or syntactical errors in a computer program. Similarly, in hardware, a bug is a recurring physical
problem that prevents a system or set of components from working together properly. To detect, locate,
and correct a malfunction or to fix an inoperable system, the term troubleshoot is more commonly used
in hardware contexts. The three major program error are; syntax error, logical error and run-time error.
SOURCES OF BUGS IN A PROGRAM
With coding errors, the source of the problem lies with the person who implements the code. Examples
of coding errors include:
Calling the wrong function ("moveUp", instead of "moveDown")
Using the wrong variable names in the wrong places ( "moveTo(y, x)" instead of "moveTo(x,
y)")
Failing to initialize a variable ( "y = x + 1", where x has not been set)
Skipping a check for an error return disk space, available processor speed, and overwhelming
input/output devices. More difficult design errors fall into several categories:
58
Failure to hide complexity
Incomplete or ambiguous "contracts"
Undocumented side effects
Complex interactivity bugs arise in scenarios where multiple parts of a single program, multiple
programs, or multiple computers interact.
Software users readily see some design errors, while in other cases design flaws make a program more
difficult to improve or fix, and those flaws are not obvious to a user. Obvious design flaws are often
demonstrated by programs that run up against the limits of a computer, such as available memory,
available
Sometimes, computer hardware simply fails, and it usually does so in wildly unexpected ways.
Determining that the problem lies not with the software itself, but with the computer(s) on which it is
usually complicated by the fact that the person debugging the software may not have access to the
hardware that shows the problem.
PREVENTING BUGS
No discussion of debugging software would be complete without a discussion of how to prevent bugs in
the first place. No matter how well you write code, if you write the wrong code, it won't help anyone. If
you create the right code, but users cannot work the user interface, you might as well have not written
the code. In short, a good debugger should keep an open mind about where the problem might lie.
Although it is outside the scope of this discussion to describe the myriad techniques for avoiding bugs,
many of the techniques here are equally useful after the fact, when you have a bug and need to uncover
it and fix it. Thus, a brief discussion follows.
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
59
1. Recognize a bug exists
60
3. Identify cause of 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. For example, if it has been determined that
the program faults because a field is wrong, the next step is to identify why the field is wrong.
This is the actual source of the bug, although some would argue that the inability of a program to
handle bad data can be considered a bug as well.
A good understanding of the system is vital to successfully identifying the source of the
bug. 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 system: the input data was incorrect. In other cases it might be due to a logic error,
where correct data was handled incorrectly. Other possibilities include unexpected values, where
the initial assumptions were that a given field can have only "n" values, when in fact, it can have
more, as well as unexpected combinations of values in different fields (field x was only supposed
to have that value when field y was something different). Another possibility is incorrect
reference data, such as a lookup table containing incorrect values relative to the record that was
corrupted.
Having determined the cause of the bug, it is a good idea to examine similar sections of
the code to see if the same mistake is repeated elsewhere. If the error was clearly a typo, this is
less likely, but if the original programmer misunderstood the initial design and/or requirements,
the same or similar mistakes could have been made elsewhere.
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.
61
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 (e.g., are there more
pressing problems?).
62
SYNTAX OF A PROGRAM
The syntax of a program is the rules defining the legal sequences of symbolic elements in a
particular language. The syntax rules define the form of various constructs in the language, but
say nothing about the meaning of these constructs. Examples of constructs are; expressions,
procedures and programs.
PROGRAMMING ERRORS
Error simply means mistake. That is errors occur in programs as a result of system failure
(hardware), wrong code/instructions (software) and human error. There are four categories of
programming error;
RUN-TIME ERRORS (EXECUTION ERROR)
Is an error that occurs during the execution of a program. In contrast, compile-time errors occur
while a program is being compiled. Runtime errors indicate bugs in the program or problems that
the designers had anticipated but could do nothing about. For example, running out of
memory will often cause a runtime error.
Note that runtime errors differ from bombs or crashes in that you can often recover gracefully
from a runtime error.
Run-time errors have the following basic characteristics;
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.
Detected by the computer run-time system
Computer usually prints error message and stops.
DEFINE LOGICAL ERRORS
A problem that causes a program to produce invalid output or to crash (lock up). The problem is
either insufficient logic or erroneous logic. For example, a program can crash if there are not
enough validity checks performed on the input or on the calculations themselves, and the
computer attempts to divide by zero. 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 computer keeps running.
Logic errors have the following basic characteristics;
63
Detected by programmer (i.e You!)
Hardest to detect, locate and find.
DEFINE SYNTAX ERRORS (COMPILATION ERROR)
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. 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, unlike semantic
errors which do not become apparent until run-time.
Run-time errors have the following basic characteristics;
Error in the form of statement: misspelled word, unmatched parenthesis, comma out of place
Detected by the computer at compiler time
Computer cannot correct error, so object program is not generated and thus program is not
executed
Computer (compiler) prints error messages, but continues to compile.
Linker errors: These types of errors have the following basic characteristics;
Prevents the generation of an executable image
Common linker errors;
o specifying the wrong header file
o disagreement among the function prototype, function definition and calls to that function
The difference between run-time, logical and syntax errors?
Students should identify the differences from the above explanations.
PROGRAM MAINTENANCE
Program/software maintenance is the modification of a software product after delivery to correct faults,
to improve performance or other attributes, or to adapt the product to a modified environment. This
international standard describes the 6 software maintenance processes as:
Categories of Program maintenance
E.B. Swanson initially identified three categories of maintenance: corrective, adaptive, and perfective.
1. The implementation processes 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.
65
WEEK 13
SPECIFIC LEARNING OUTCOMES
To understand:
Employ structured approach to both flowcharting and program development.
Whether the original programmer or someone else needs to make a change in the code the job is
much easier if the original programmer used lots of comments, gave the variables and constants
descriptive names, and sketched out the basic structure of the program at the very beginning in
pseudo-code.
Using Comments in Code
The use of comments can mean the difference between code which any competent programmer
can maintain or modify and a program that even the original programmer has trouble figuring out.
Every routine should start with at least one comment that documents the purpose of the routine
and any non- obvious dependencies or effects that the routine may have on other portions of the
program.
When first developing the structure of a program it can be very helpful to write out the different
routines in pseudo-code. This is language which resembles a cross between English and the
programming language that the code will eventually be written in.
Using pseudo-code allows the programmer to concentrate on the conceptual aspects of the
program without being distracted by syntax rules. The pseudo-code can also be the basis of the
67
comments so it can server two purposes.
Using Modular Coding
Whenever possible, the lines of a routine should fit entirely on one screen of the editor. By
keeping routines short, it is easier to comprehend them and see errors. Having short routines also
forces the programmer to break each task into distinct sub-tasks, each of which is easier to
maintain and modify in the future.
Modular coding also has the advantage of creating reusable routines that can be used in
other programs. Once a routine is debugged and verified it is easier to copy and paste it into
another program than to write it all over again.
Following these simple suggestions will make a programmer's code easier to maintain and
modify. It may seem like more work, but in the end the net result is greater efficiency and fewer
mistakes.
68