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

Lecture Note CSC102

Text

Uploaded by

mohammedbala843
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views

Lecture Note CSC102

Text

Uploaded by

mohammedbala843
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 76

MODIBBO ADAMA UNIVERSITY, YOLA

FACULTY OF PHYSICAL SCIENCES


DEPARTMENT OF COMPUTER SCIENCE

LECTURE NOTE

COURSE TITLE: INTRODUCTION TO PROBLEM SOLVING


COURSE CODE: CSC102

2024
TABLE OF CONTENT
CHAPTER 1: PROBLEM-SOLVING STRATEGIES 4
1.1 Objectives 4
1.2 Problem-Solving Strategies Defined 4
1.3 Multiple Problem-Solving Strategies 4
1.3.1 Trial And Error 5
1.3.2 Algorithm and Heuristic 5
1.4 Other Problem-Solving Strategies 6
1.5 Summary 8
CHAPTER 2: THE PROBLEM SOLVING PROCESS 9
2.1 Objectives 9
2.2 Computer as a Model of Computation 9
2.3 Understand the Problem 10
2.4 Formulating a Model 11
2.5 Develop an Algorithm 12
2.6 Writing the Program 16
2.7 Test the Program 16
2.8 Evaluating the Solution 17
2.9 Summary 17
CHAPTER 3: ROLE OF ALGORITHMS IN PROBLEM SOLVING 18
3.1 Objectives 18
3.2 The Concept of Abstraction 18
3.2.1 Importance of Abstraction 18
3.2.2 How to Abstract 19
3.2.3 Types of Abstraction 19
3.3 Summary 23
CHAPTER 4: ALGORITHMS 24
4.1 Objectives 24
4.2 The Notion of Algorithm 24
4.3 Reasons for Algorithm 25
4.4 Steps Involved in Algorithm Development 25

1
4.5 Characteristics of Algorithm 26
4.6 Representation of Algorithms 26
4.7 Advantages and Disadvantages of Algorithm 28
4.8 Summary 29
CHAPTER 5: FLOWCHARTS 30
5.1 Objectives 30
5.2 Concept of Flowcharts 30
5.2.1 Symbols Used in Creating a Flowchart 30
5.2.2 Intermediate and Advanced Flowchart Symbols 31
5.3 Considerations in Flowcharting 33
5.4 Sample Flowcharts 34
5.5 Differences between Algorithm and Flowchart 37
5.6 Advantages of Flowcharts 37
5.7 Summary 37
CHAPTER 6: PSEUDOCODE 38
6.1 Objectives 38
6.2 Meaning and Definition of Pseudocode 38
6.3 Reasons for Using Pseudocode 38
6.4 The Main Constructs of Pseudocode 39
6.5 Rules for Writing Pseudocode 40
6.6 Advantages of Pseudocode 41
6.7 Worked Examples 41
6.8 Summary 42
CHAPTER 7: CONTROL STRUCTURES / SELECTION AND ITERATION 43
7.1 Objectives 43
7.2 Control Structures 43
7.2.1 Selection 43
7.2.2 Iteration (Looping) 48
7.3 Summary 53
CHAPTER 8: TESTING AND DEBUGGING 54
8.1 Objectives 54

2
8.2 Program Testing 54
8.3 Types of Program Tests 54
8.4 Need for Program Testing 56
8.5 Benefits of Program Testing 57
8.6 Debugging 58
8.6.1 Types of Errors to Debug 58
8.7 Difference between Testing and Debugging 59
8.8 Summary 60
CHAPTER 9: PROGRAM IMPLEMENTATION 61
9.1 Objectives 61
9.2 Program Implementation 61
9.3 Program Implementation Examples 62
9.4 Summary 65

3
CHAPTER 1: PROBLEM-SOLVING STRATEGIES

1.1 OBJECTIVES

• Define problem solving strategies

• Define algorithm and heuristic and their role in problem solving

• Describe typical common problem solving strategies

• Explain some common roadblocks to effective problem solving.

1.2 PROBLEM-SOLVING STRATEGIES


When people are presented with a problem whether it is a complex mathematical problem or a
broken printer, how do you solve it? Before finding a solution to the problem, the problem must
first be clearly identified. After that, one of many problem solving strategies can be applied,
hopefully resulting in a solution.
A problem-solving strategy is a plan used to find a solution or overcome a challenge. Different
strategies have different action plans associated with them. For example, a well-known strategyis
trial and error. Each problem-solving strategy includes multiple steps to provide you with helpful
guidelines on how to resolve a business problem or industry challenge. Effective problem-solving
requires you to identify the problem, select the right process to approach it and follow a plan
tailored to the specific issue you are trying to solve.

1.3 MULTIPLE PROBLEM-SOLVING STRATEGIES

Problems themselves can be classified into two different categories known as ill-defined and well-
defined problems. Ill-defined problems represent issues that do not haveclear goals, solution paths,
or expected solutions whereas well-defined problems have specificgoals, clearly defined solutions,
and clear expected solutions. Problem solving often incorporates logical reasoning and
interpretation of meanings behind the problem, and also in many cases require abstract thinking
and creativity in order to find novel solutions. Various methods of studying problem solving exist
including simulation, computer modelling, and experimentation. Understanding how a variety of
problem-solving strategies work is important because different problems typically require you to

4
approach them in different ways to find the best solution. By mastering several problem-solving
strategies, you can more effectively select the right plan of action when faced with challenges in
the future. This can help you solve problems faster and develop stronger critical thinking skills

1.3.1 TRIAL AND ERROR

A trial-and-error approach to problem-solving involves trying a number of different solutions and


ruling out those that do not work. This approach can be a good option if you have a very limited
number of options available. In terms of a broken printer for example, one could try checking the
ink levels, and if that doesn’t work, you could check to make sure the paper tray isn’t jammed. Or
may be the printer isn’t actually connected to a laptop. When using trial and error, one would
continue to try different solutions until the problem is solved. Although trial and error is not
typically one of the most time-efficient strategies, it is a commonly used one.

1.3.2 ALGORITHM AND HEURISTIC

A common type of strategy is an algorithm. An algorithm is a problem-solving formula that


provides you with step-by-step instructions used to achieve a desired outcome. You can think of
an algorithm as a recipe with highly detailed instructions that produce the same result every time
they are performed. Algorithms are used frequently in our everyday lives, especially in computer
science. When you run a search on the Internet, search engines like Google use algorithms to
decide which entries will appear first in your list of results. Facebook also uses algorithms to decide
which posts to display on your news feed. Can you identify other situations in which algorithms
are used?

A heuristic is another type of problem solving strategy. While an algorithm must be followed
exactly to produce a correct result, a heuristic is a general problem-solving framework. You can think
of these as mental shortcuts that are used to solve problems. A “rule of thumb” is an example of a
heuristic. Such a rule saves the person time and energy when making a decision, but despite its
time-saving characteristics, it is not always the best method for making a rational decision.
Different types of heuristics are used in different types of situations, but the impulse to use a
heuristic occurs when one of five conditions is met.
1. When one is faced with too much information
2. When the time to make a decision is limited

5
3. When the decision to be made is unimportant
4. When there is access to very little information to use in making the decision
5. When an appropriate heuristic happens to come to mind in the same moment
Working backwards is a useful heuristic in which you begin solving the problem by focusing on
the end result. It is common to use the working backwards heuristic to plan the events of your day
on a regular basis, probably without even thinking about it. Another useful heuristic is the practice
of accomplishing a large goal or task by breaking it into a series of smaller steps. Students often
use this common method to complete a large research project or long essay for school. For
example, students typically brainstorm, develop a thesis or main topic, research the chosen topic,
organize their information into an outline, write a rough draft, revise and edit the rough draft,
develop a final draft, organize the references list, and proofread their work before turning in the
project. The large task becomes less overwhelming when it is broken down into a series of small
steps.
Table 1: Commonly Used Problem-Solving Strategies

Method Description Example


Trial and error Continue trying different Restarting phone, turning off
solutions until problem is WiFi, turning off Bluetooth
solved in order to determine why
your phone is
malfunctioning
Algorithm Step-by-step problem- Instruction manual for
solving formula installing new software on
your computer
Heuristic General problem-solving Working backwards;
framework breaking a task into steps

1.4 OTHER PROBLEM-SOLVING STRATEGIES

Here are some examples of problem-solving strategies that may equally be adopted to see which
works best for you in different situations:
i. Use past experience

6
Take the time to consider if you have encountered a similar situation to your current problem
in the past. This can help draw connections between different events. Ask yourself how you
approached the previous situation and adapt those solutions to the problem currently being
solved. For example, a company trying to market a new clothing line may consider marketing
tactics they have previously used, such as magazine advertisements or social media
advertisements. By analysing what tactics have worked in the past, they can create a
successful marketing campaign again.

ii. Bring in a facilitator

If one is trying to solve a complex problem with a group of other people, bringing in a
facilitator can help increase efficiency and mediate collaboration. Having an impartial third
party can help a group stay on task, document the process and have a more meaningful
conversation. Consider inviting a facilitator to your next group meeting to help generate
better solutions.
iii. Develop a decision matrix for evaluation

If multiple solutions are developed for a problem, one may need to determine which one is
the best. A decision matrix can be an excellent tool to help you approach this task because it
allows you to rank potential solutions. Some factors you can analyse when ranking each
potential solution are:
• Timeliness

• Risk

• Manageability

• Expense

• Practicality

• Effectiveness

After having decided which factors to include, use them to rank each potential solution by
assigning a weighted value of 0 to 10 in each of these areas. For example, one solution may
receive a score of 10 in the timeliness factor because it meets all the requirements, while
another solution may only receive a seven. Having ranked each of the potential solutions

7
based on these factors, add up the total number of points each solution received. The solution
with the highest number of points should meet the most important criteria.

iv. Ask your peers for help

Getting opinions from peers can expose new perspectives and unique solutions. Friends,
families or colleagues may have different experiences, ideas and skills that may contribute
to finding the best solution to a problem. Consider asking a diverse range of colleagues or
peers to share what they would do if they were in your situation. Even if you don't end up
taking one of their suggestions, the conversation may help you process your ideas and arrive
at a new solution.

v. Step away from the problem

Finally, if the problem being worked on does not need an immediate solution, consider
stepping away from it for a short period of time. You can do this literally by taking a walk
to help clear your mind or figuratively by setting the problem aside for a few days until you
are ready to approach it again. Allowing yourself time to rest, exercise and take care of your
own well-being can make solving the problem easier when you come back to it because you
may feel energized and focused.

1.5 SUMMARY

• Problem-solving strategies may include multiple steps in order to proffer solution to


business problem or industrial challenges.
• Effective problem-solving requires you to identify the problem, select the right process
to approach it and follow a plan tailored to the specific issue you are trying to solve
• Understanding the strategies of proffering solutions to problem through trial and error,
algorithm and heuristic.
• Working backwards is a useful heuristic in which you begin solving the problem by focusing on
the end result.

8
CHAPTER 2: THE PROBLEM SOLVING PROCESS

2.1 OBJECTIVES

• Understand the computer as a model of computation

• Explain the problem solving process in detail

• Apply the problem solving paradigm to routine elementary problems

2.2 COMPUTER AS A MODEL OF COMPUTATION

In regards to problem solving, we will apply the above model in that we will assume that we are
given some kind of input information that we need to work with in order to produce some desired
output as solution. However, the above model is quite simplified. For larger and more complex
problems, we need to iterate (i.e., repeat) the input/process/output stages multiple times in
sequence, producing intermediate results along the way that solve part of our problem, but not
necessarily the whole problem. For simple computations, the above model is sufficient.

Definition: Problem Solving is the sequential process of analysing information related to a given
situation and generating appropriate response options.

In solving a problem, there are some well-defined steps to be followed. For example, considerhow
the input/process/output works on a simple problem:
Example: Calculate the average grade for all students in a class.

9
1. Input: get all the grades … possibly by typing them in via the keyboard or by reading
them from a USB flash drive or hard disk.
2. Process: add them all up and compute the average grade.

3. Output: output the answer to either the monitor, to the printer, to the USB flash drive
or hard disk … or a combination of any of these devices.
It is noted that the problem is easily solved by simply getting the input, computing something and
producing the output. We now examine the steps to problem solving within the context of the
above example.

Storage/Network devices
Input devices

10
Figure 2.1: Simplified Model of a Uniprocessor Computer

A typical single CPU computer processes information as shown in the diagram. Problems are
solved using a computer by obtaining some kind of user input (e.g., keyboard/mouse information
or game control movements), then processing the input and producing some kind of output (e.g.,
images, text, sound). Sometimes the incoming and outgoing data may be in the form of hard drives
or network devices.

2.3 UNDERSTAND THE PROBLEM

It sounds strange, but the first step to solving any problem is to make sure that one understands the
problem about to be solved. One needs to know:
• What input data/information is available?

• What does the data/information represent?

• In what format is the data/information?

• What is missing in the data provided?

• Does the person solving the problem have everything needed?

• What output information needs to be produced?

11
• In what format should the result be: text, picture, graph?

• What are the other requirements needed for computation?

In the example given above, it is understood that the input is a bunch of grades. But we need to
understand the format of the grades. Each grade might be a number from 0 to 100 or it may be a
letter grade from A to F. If it is a number, the grade might be a whole integer like 73 or it may be
a real number like 73.42. We need to understand the format of the grades in order to solve the
problem.

We also need to consider missing grades. What if we do not have the grade for every student: for
instance, some were away during the test? Should we be able to include that person in our average
(i.e., they received 0) or ignore them when computing the average? We also need to understand
what the output should be. Again, there is a formatting issue. Should the output be a whole or real
number or a letter grade? Do we want to display a pie chart with the average grade? The choice is
ours.

Finally, one needs to understand the kind of processing that must be performed on the data. This
leads to the next step.

2.4 FORMULATING A MODEL

The next step is to understand the processing part of the problem. Many problems break downinto
smaller problems that require some kind of simple mathematical computations in order to process
the data. In the example given, the average of the incoming grades is to be computed. A model (or
formula) is thus needed for computing the average of a bunch of numbers. If there is no such
“formula”, one must be developed. Often, however, the problem breaks down into simple
computations that is well understood. Sometimes, one can look up certain formulas in a book or
online if there is a hitch.
In order to come up with a model, we need to fully understand the information available to us.
Assuming that the input data is a bunch of integers or real numbers 𝑥1, 𝑥2, ⋯ , 𝑥𝑛 representing a
grade percentage, the following computational model may apply:
𝐴𝑣𝑒𝑟𝑎𝑔𝑒1 = (𝑥1 + 𝑥2 + 𝑥3 + ⋯ + 𝑥𝑛)/𝑛

where the result will be a number from 0 to 100.


That is very straight forward, assuming that the formula for computing the average of a bunch of

12
numbers is known. However, this approach will not work if the input data is a set of letter grades
like B, C, A, F, D, etc., because addition and division cannot be performed on the letters. This
problem solving step must figure out a way to produce an average from such letters. Thinking is
required. After some thought, we may decide to assign an integer number to the incoming
letters asfollows:
A=5 B=4 C=3 D=2 E=1 F=0

If it is assumed that these newly assigned grade numbers are 𝑦1, 𝑦2, ⋯ , 𝑦𝑛, then the following
computational model may be used:
𝐴𝑣𝑒𝑟𝑎𝑔𝑒2 = (𝑦1 + 𝑦2 + 𝑦3 + ⋯ + 𝑦𝑛)/𝑛

where the result will be a number from 0 to 5.

As for the output, if it is to be represented as a percentage, then 𝐴𝑣𝑒𝑟𝑎𝑔𝑒1 can either be used
directly or one may use (𝐴𝑣𝑒𝑟𝑎𝑔𝑒2/5), depending on the input that we had originally. If a letter
grade is preferred as output, then one may need to use (𝐴𝑣𝑒𝑟𝑎𝑔𝑒1/100 ∗ 5) or (𝐴𝑣𝑒𝑟𝑎𝑔𝑒1 ∗
0.05) or 𝐴𝑣𝑒𝑟𝑎𝑔𝑒2 and then map that to some kind of “lookup table” that allowsone to look up a
grade letter according to a number from 0 to 5.

The main point to understand this step in the problems solving process is that it is all about figuring
out how to make use of the available data to compute an answer.

2.5 DEVELOP AN ALGORITHM

Having understood the problem and formulated a model, it is time to come up with a precise plan
of what the computer is expected to do.

Definition: Algorithm is a precise sequence of instructions for solving a problem.

Some of the more complex algorithms may be considered randomized algorithms or non-
deterministic algorithms where the instructions are not necessarily in sequence and may not even
have a finite number of instructions. However, the above definition will apply for all algorithms
that will be discussed in this course.

To develop an algorithm, the instructions must be represented in a way that is understandable to a


person who is trying to figure out the steps involved. Two commonly used representationsfor an

13
algorithm is by using (1) pseudo code, or (2) flowcharts. Consider the following example for solving
the problem of a broken lamp. First is the example in a flowchart, and then in pseudocode.

Lamp not working

Lamp No
plugged Plug in Lamp
in?

Yes

Bulb Yes
burned Replace Bulb
out?

No

Buy new Lamp

Figure 2.2: Flowchart for a broken Lamp

Pseudocode

1. IF lamp works, go to step 7.

2. Check if lamp is plugged in.

3. IF not plugged in, plug in lamp.

4. Check if bulb is burnt out.

5. IF blub is burnt, replace bulb.

6. IF lamp doesn’t work buy new lamp.

7. Quit ... problem is solved.

Note: pseudocode is a simple and concise sequence of English-like instructions to solve problem.
Pseudocode is often used as a way of describing a computer program to someone who doesn’t

14
understand how to program a computer. When learning to program, it is important to write
pseudocode because it helps to clearly understand the problem that one is trying to solve. It also
helps avoid getting bogged down with syntax details (i.e., like spelling mistakes) when writing the
program later.
Although flowcharts can be visually appealing, pseudocode is often the preferred choice for
algorithm development because:
• It can be difficult to draw a flowchart neatly, especially when mistakes are made.
• Pseudocode fits more easily on a page of paper.
• Pseudocode can be written in a way that is very close to real program code, making it
easier later to write the program (i.e., in step 4).
• Pseudocode takes less time to write than drawing a flowchart.
Pseudocode will vary according to whoever writes it. That is, one person’s pseudocode is often quite
different from that of another person. However, there are some common control structures (i.e.,
features) that appear whenever pseudocode is written. These features are shown along with some
examples:
Sequence: Listing instructions step-by-step in order (often numbered)
1. Make sure switch is turned on
2. Check if lamp is plugged in
3. Check if bulb is burned out
4. 4. ……
Condition: Making a decision and doing one thing or something else depending on the outcome
of the decision.
If lamp is not plugged in
then plug it in
If bulb is burned out
then replace bulb
Else buy new lamp

Repetition: repeating something a fixed number of times or until some condition occurs

Repeat
get a new light bulb put

15
it in the lamp
Until lamp works or no more bulbs left

Repeat 3 times
Unplug lamp
Plug into different socket
…..

Storage: storing information for use in instructions further down the list

x ← a new bulb
count ← 8

Transfer of Control: being able to go to a specific step when needed

If bulb works
then goto step 7
Note:

• The bold in the above examples highlights the specific control structure.

• For the condition and repetition structures, the portion of the pseudocode that is part ofthe
condition or the repeat loop are indented a bit in order to make it clear that these kinds of
inner steps that belong to that structure.

Consider the previous example of finding the average of a set of 𝑛 grades stored in a file. What would the
pseudocode look like? Here is an example of what it might look like if we had the example of 𝑛 numeric
grades 𝑥1, 𝑥2, ⋯ , 𝑥𝑛 that were loaded from a file:
Algorithm: Display Grades

1. set the sum of the grade values to 0.


2. load all grades 𝑥1, 𝑥2, ⋯ , 𝑥𝑛 from file.
3. repeat n times {
4. get grade xi
5. add xi to the sum

16
}
6. compute the average to be sum / n.
7. print the average

It would be wise to run through the above algorithm with a real set of numbers. Each time an
algorithm is tested with a fixed set of input data, this is known as a test case.
Many test cases can be created. Here are some to try:

𝑛 = 5, 𝑥1 = 92, 𝑥2 = 37, 𝑥3 = 43, 𝑥4 = 12, 𝑥5 = 71……… result should be 51

𝑛 = 3, 𝑥1 = 1, 𝑥2 = 1, 𝑥3 = 1 .................................................. result should be 1

𝑛 = 0 ........................................................................................ result should be 0

2.6 WRITING THE PROGRAM

Now that we have a precise set of steps for solving the problem, most of the hard work has been
done. The next step is to transform the algorithm from step 3 into a set of instructions that can be
understood by the computer. Writing a program is often called "coding" or “implementing an
algorithm”. So the code (or source code) is actually the program itself. The computer requires
precise instructions in order to understand what it is being asked to do. For example, removing
one of the semi-colon characters (;) from the program like java, will make the computer become
confused as to what it’s being asked to do because the semi-colon characters (;) is what it
understands to be the end of an instruction. Leaving one of them off will cause the program to
generate what is known as a compile-time error.

Definition: Compiling is the process of converting a program into instructions that can be
understood by the computer.

2.7 TEST THE PROGRAM

Once a program is written and compiles, the next task is to make sure that it solves the problem that
it was intended to solve and that the solutions are correct. Running a program is the process of
telling the computer to evaluate the compiled instructions.When a program is run and all is well,
you should see the correct output. It is possible however,that a program works correctly for some

17
set of input data but not for all. If the output of a program is incorrect, it is possible that the
algorithm was not properly converted into a proper program. It is also possible that the programmer
did not produce a proper algorithm that handles all situations that could arise. Perhaps some
instructions are performed out of sequence. Whatever happened, such problems with the program
are known as bugs.
Definition: Bugs are errors with a program that cause it to stop working or produce incorrect or
undesirable results.
It is the responsibility of the programmer to fix as many bugs in a program as are present. To find
bugs effectively, a program should be tested with many test cases (called a test suite). It isalso a
good idea to have others test one’s program because they may think up situations or inputdata that
one may never have thought of.
Definition: Debugging is the process of finding and fixing errors in program code.

2.8 EVALUATING THE SOLUTION


Once the program produces a result that seems correct, the original problem needs to be
reconsidered to make sure that the answer is formatted into a proper solution to the problem. It is
often the case that it may be realised that the program solution does not solve the problem the way
it is expected. It may also be realised that more steps are involved.

For example, if the result of a program is a long list of numbers, but the intent was to determine a
pattern in the numbers or to identify some feature from the data, then simply producing a listof
numbers may not suffice. There may be a need to display the information in a way that helps
visualise or interpret the results with respect to the problem; perhaps a chart or graph is needed.It is
also possible that when the results are examined, it is realised that additional data are needed to
fully solve the problem. Alternatively, the results may need to be adjusted to solve the problem
more efficiently (e.g., a game is too slow).

It is important to remember that the computer will only do what it is told to do. It is up to the user
to interpret the results in a meaningful way and determine whether or not it solves the original
problem. It may be necessary to re-do some of the steps again, perhaps going as far back as step 1
again, if data were missing.

18
2.9 SUMMARY
The decision to get a solution to any exist problem involve a cycle that consist of the following
using a Computer as a model of computation, Understanding the Problem, Formulating a Model,
Developing an Algorithm, Writing the Program, Testing the Program and finally Evaluating the
Solution. Thus you have learnt that the various stages involve in the problem solving processing:
The stages are sequential and are seven in number:
• Computer as a model of computation

• Understanding the Problem

• Formulating a Model

• Developing an Algorithm

• Writing the Program

• Testing the Program

• Evaluating the Solution

CHAPTER 3: ROLE OF ALGORITHMS IN PROBLEM SOLVING

3.1 OBJECTIVES

• Define abstraction as a problem aid

• Understand the importance of abstraction in problem solving

• Describe how to perform abstraction

• Explain the various types of abstraction used in problem solving

3.2 THE CONCEPT OF ABSTRACTION

This is the creation of well-defined interfaces to hide the inner workings of computer programs from
users. It may also be defined as the process of identifying the general characteristics needed to
solve a problem while filtering out unnecessary information. It is also described as simplifying a
process or artifact by providing what you really need, and hiding the useless details you don't care

19
about, thus removing unnecessary detail.

Abstraction is widely used to simplify things that may be very complex. We use abstractions all
the time, almost without thinking. For example, if you learn to drive, you will be taught that putting
your foot on the accelerator will speed up the car and putting your foot on the brake pedal will
slow it down. You will not be taught anything about how the acceleration or braking systems
actually work.

3.2.1 IMPORTANCE OF ABSTRACTION

In computer science, abstraction is used to manage the complexity of a lot of what is designed and
created. Computer hardware is seen as components or black boxes.

The abstraction above represents a computer. It shows the names of the components and how they
interact with each other but hides the complexity of each type of component.
3.2.2 HOW TO ABSTRACT

In computing, when we decompose problems, we then look for patterns among and within the
smaller problems that make up the complex problem. Abstraction allows us to create a general idea
of what the problem is and how to solve it. We remove all specific detail, and any patterns that will
not help us solve the problem.

20
For example, the school timetable (as shown below) is an abstraction of what happens in a typical
week: it captures key information such as who is taught what subject where and by whom, but
leaves to one side further layers of complexity, such as the learning objectives and activities
planned in any individual lesson. When abstracting, we remove specific details and keep the
general relevant patterns. So, abstraction allows us to form our idea of the problem. This idea is
also known as a model. Once we have a model of our problem, we can then designan algorithm to
solve it.

3.2.3 TYPES OF ABSTRACTION

i. Representational Abstraction

Abstraction appears in many forms within computing, both in terms of techniques used to
approach problem-solving, and in the computational tools employed to develop solutions.
The maps of many metropolitan public transport systems worldwide is a classic example
of a representational abstraction. Many specific details about the lines are removed because
they are not necessary for the purpose of the map, which is to help plan a journey. What
remains when unnecessary detail has been removed is a representational abstraction, i.e. a
simpler version directed at solving a particular problem.

21
Figure 3: Example of a metropolitan public transport system 'map'

Many real-world objects and situations are represented in computer systems. In a flight
simulator, different planes will be represented in some way within the system. If object-
oriented programming is used, the plane will be an object with a set of properties that are
relevant to the features of the simulator. Some details will be essential, such as the weight
of the plane (as this will affect its handling). Other details, such as the material used to
upholster the seats, will be irrelevant, and these aspects will not need to be represented
within the systemor model.
Computer scientists have to choose what to include in the model and what to discard. They
must ensure that they include the minimum amount of detail necessary to solve the given
problem to the required degree of accuracy.

ii. Abstraction by Generalisation

22
When you group things in terms of a set of common characteristics, you are generalising.
This is a fundamental technique used in object-oriented programming (although it is not
exclusive to OOP) when you identify that some objects are 'kinds of' more generic objects.
For example, you might say that a cocker spaniel is a kind of dog. Dogs have common sets
of characteristics,such as having four legs, a tail, and ears. However, so do cats; a biologist
may tell you that both animals belong to the order Carnivora (a group that includes many
other types of animal including bears, skunks, and badgers). Generalising in this way
allows code to be developed and shared between objects.
You can also apply the technique of generalisation to the problem itself. It is often helpful
to be able to identify a problem as an example of a more general set of problems. Sometimes,
this will help you to understand quickly that the problem is non-computable, or that it is
intractable.Otherwise, if the problem can be solved, you can benefit from a solution that
already exists.

iii. Procedural abstraction

This type represents a computational method. One of the skills that you will develop as a
computer scientist is the ability to design a well-abstracted procedure that is generalised as
far as possible.
For example, consider the problem of calculating the surface area of a chopping board.
You write the following subroutine:

PROCEDURE calculate_chopping_board_area()
side1_length = INPUT("Enter length of side 1: ")
side2_length = INPUT("Enter length of side 2: ")
side1_length = STR(side1_length)
side2_length = STR(side2_length) area
= side1_length * side2_length
PRINT(area)
ENDPROCEDURE

This is an example of a subroutine that is too specific. Firstly, it is bound to a specific


(command line) user interface. If you abstract away this detail, the subroutine will be

23
independent of the user interface, and will therefore be more general. Here is a more
general version of the same subroutine:

FUNCTION calculate_chopping_board_area(side1_length, side2_length)


area = side1_length * side2_length
RETURN area
ENDFUNCTION

A further abstraction is to replace the name (identifier) of the subroutine with something
moregeneral:

FUNCTION calculate_area(side1_length, side2_length)area


= side1_length * side2_length
RETURN area
ENDFUNCTION

iv. Functional Abstraction

In functional abstraction, the implementation detail of the computational method is hidden.


You can think of a function as a black box. The function will receive an input (or set of
inputs),process the input(s), and return the output. How the transformation is achieved is
hidden fromthe user?
Most languages will provide a set of built-in functions that can be used by the programmer.
In the previous example of a subroutine that calculates the area of a regular polygon, a
maths library is used to provide useful mathematical functions. In the example, functions
were used to provide the value of pi, to calculate the square root of a number, and to
calculate the tangent of a number.
In Python, for example, the built-in function to display a value to the console or command
line interface is print. If you code in Python, you will be familiar with typing a command
such as print ("Hello World"). You will know that the name of the function is print,
and it mustbe followed by a value (to print) enclosed in parentheses.

v. Data Abstraction

Some data types, such as unsigned integers, are conceptually simple; others are more
complex.Data abstraction is a technique that allows you to separate the way that a compound
data object is used, from the details of how it is constructed.

24
If you have studied data structures, you will be aware of the concept of a stack as an
example of an abstract data type (ADT). A stack is a last in, first out (LIFO) data structure
that supports three standard operations: push (add an item to the stack), pop (remove an
item from a stack), and peek (look at the item at the top of the stack). The abstract concept
of a stack, and its operations, can be understood without any consideration of how it is
implemented. Sometimes,you will see a stack drawn as an upright container with a single
opening at the top. This abstraction helps you to understand the LIFO nature of the
structure.

3.3 SUMMARY
In this week the concept of abstraction and its importance in problem solving were described,
Abstraction involves the process of taking away or removing characteristics from something in
order to reduce it to a set of essential characteristics. In abstraction, essential elements are
displayed to the user and trivial elements are kept hidden. Its main goal is to handle complexity by
hiding unnecessary details from the user. In computing, when we decompose problems, we then
look for patterns among and within the smaller problems that make up the complex problem.
Abstraction allows us to create a general idea of what the problem is and how to solve it. We remove
all specific detail, and any patterns that will not help us solve the problem. There are five types of
abstractions namely; representational abstraction, abstraction by generalization, procedural
abstraction, functional abstraction and data abstraction.

25
CHAPTER 4: ALGORITHMS

4.1 OBJECTIVES

• Understand and explain the concept of algorithms

• Explain the need for algorithms and their desirable characteristics

• Describe the steps involved in developing an algorithm

• Develop algorithms for simple problems

• Advantage and disadvantage of algorithm

.
4.2 THE NOTION OF ALGORITHM

By definition, an algorithm is an effective step-by-step procedure for solving a problem in a finite


number of steps. In other words, it is a finite set of well-defined instructions or step-by- step
description of the procedure written in human readable language for solving a given problem. An
algorithm itself is division of a problem into small steps which are ordered in sequence and easily
understandable. Algorithms are very important to the way computers process information, because
a computer program is basically an algorithm that tells computer what specific tasks to perform in
what specific order to accomplish a specific task. The same problem can be solved with different
methods. So, for solving the same problem, different algorithms can be designed. In these
algorithms, number of steps, time and efforts may vary more or less.
For example, we might need to sort a sequence of numbers into non-decreasing order. This
problem arises frequently in practice and provides fertile ground for introducing many standard
design techniques and analysis tools. Here is how we formally define the sorting problem:

For example, given the input sequence 〈31; 41; 59; 26; 41; 58〉, a sorting algorithm returns as
output the sequence 〈26; 31; 41; 41; 58; 59〉. Such an input sequence is called an instance of the
sorting problem. In general, an instance of a problem consists of the input (satisfying whatever
conditions are imposed in the problem statement) needed to compute a solution to the problem.

26
In computer science we give a special name to the sub-algorithms. They are sometimes called
modules, functions or procedures.

4.3 REASONS FOR ALGORITHM


A programmer writes a program to instruct the computer to do certain tasks as desired. The
computer then follows the steps written in the program code. Therefore, the programmer first
prepares a roadmap of the program to be written, before actually writing the code. Without a
roadmap, the programmer may not be able to clearly visualise the instructions to be written and may
end up developing a program which may not work as expected. Such a roadmap is nothing but the
algorithm which is the building block of a computer program.
For example, searching using a search engine, sending a message, finding a word in a document,
booking a taxi through an app, performing online banking, playing computer games,all are based on
algorithms. Writing an algorithm is mostly considered as a first step to programming. Once we
have an algorithm to solve a problem, we can write the computer program for giving instructions
to the computer in high level language. If the algorithm is correct, computer will run the program
correctly, every time. So, the purpose of using an algorithm is to increase the reliability, accuracy
and efficiency of obtaining solutions.

4.4 STEPS INVOLVED IN ALGORITHM DEVELOPMENT

An algorithm can be defined as “a complete, unambiguous, finite number of logical steps for
solving a specific problem “
Step1. Identification of input: For an algorithm, there are quantities to be supplied called input
and these are fed externally. The input is to be identified first for any specified problem.
Step2: Identification of output: From an algorithm, at least one quantity is produced, called
for any specified problem.
Step3: Identify the processing operations: All the calculations to be performed in order to
lead to output from the input are to be identified in an orderly manner.
Step4: Processing Definiteness: The instructions composing the algorithm must be clear and
there should not be any ambiguity in them.
Step5: Processing Finiteness: If we go through the algorithm, then for all cases, the algorithm

27
should terminate after a finite number of steps.
Step6: Possessing Effectiveness: The instructions in the algorithm must be sufficiently basic
and in practice they can be carries out easily.

4.5 CHARACTERISTICS OF ALGORITHM

An algorithm must possess following characteristics namely;

1. Precision: the steps are precisely stated or defined.

2. Uniqueness: results of each step are uniquely defined and only depend on the inputand
the result of the preceding steps.
3. Finiteness: the algorithm always stops after a finite number of steps.

4. Input: the algorithm receives some input.

5. Output: the algorithm produces some output.

4.6 REPRESENTATION OF ALGORITHMS

Using their algorithmic thinking skills, software designers or programmers analyse the problem and
identify the logical steps that need to be followed to reach a solution. Once the steps are identified,
the need is to write down these steps along with the required input and desired output. There are
two common methods of representing an algorithm namely; flowchart and pseudocode.
Either of the methods can be used to represent an algorithm while keeping in mind the following:
• It showcases the logic of the problem solution, excluding any implementation details
• It clearly reveals the flow of control during execution of the program

Representative Algorithms for Simple Problems

Write an algorithm for the following

1. Write an algorithm to calculate the simple interest using the formula:

𝑆𝑖𝑚𝑝𝑙𝑒 𝑖𝑛𝑡𝑒𝑟𝑒𝑠𝑡 = 𝑃 ∗ 𝑁 ∗ 𝑅/100, Where 𝑃 is principle Amount, 𝑁 is the number ofyears


and 𝑅 is the rate of interest.

Algorithm calculateSimpleInterest

28
Step 1: Read the three input quantities’ P, N and R.
Step 2: Calculate simple interest as
Simple interest = P* N* R/100
Step 3: Print simple interest.
Step 4: Stop.

2. Write an algorithm to find the area of the triangle. Let 𝑏, 𝑐 be the sides of the triangle 𝐴𝐵𝐶
and 𝐴 the included angle between the given sides.

Algorithm findAreaOfTriangle

Step 1: Input the given elements of the triangle namely sides 𝑏, 𝑐 and anglebetween
the sides 𝐴
1
Step 2: area = ∗ 𝑏 ∗ 𝑐 ∗ sin (𝐴)
2

Step 3: Output
the AreaStep 4:
Stop.

3. Write an algorithm to find the largest of three numbers 𝑋, 𝑌, Z

Algorithm findLargestOfThreeNumbers

Step 1 Read the numbers 𝑋, 𝑌, 𝑍.


Step 2 If (X > Y)
big = X
Else big = Y
Step 3 If (big < Z)

big = Z
Step 4 Print big
Step 5 Stop.

4. Write an algorithm to find the largest data value of a set of given data values

29
Algorithm findLargestDataValue

Step 1: LARGE = 0

Step 2: read NUM

Step 3: While NUM > = 0 do

3.1 If NUM > LARGE then

3.1.1 LARGE = NUM

3.2. Read NUM

Step 4: Write “largest data value is”, LARGE


Step 5: Stop

5. Write an algorithm which will test whether a given integer value is prime or not.

Algorithm testForPrime

Step 1: M=2

Step 2: read N

Step 3: MAX = SQRT (N)

Step 4: While M < = MAX do

4.1 If (M * (N/M) = N then

4.1.1 goto step 7


Step 4.2. M = M+1
Step 5: Write “number is prime”
Step 6 goto step 8
Step 7 Write “number is not a prime”
Step 8 End

6. Write an algorithm to calculate the perimeter and area of rectangle. Given its length and
width.

30
Algorithm
calculatePerimeterAndAreaOfRectangle

Step 1: Read length and width of the rectangle


Step 2: Calculate perimeter = 2* (length + width)
Step 3: Calculate area = length *width.
Step 4: Print perimeter
Step 5 Print area
Step 6: Stop

4.7 ADVANTAGES AND DISADVANTAGES OF ALGORITHM


Advantages
Designing an algorithm has following advantages:
1. Effective Communication: Since algorithm is written in English like language, it is
simple to understand step-by-step solution of the problems.
2. Easy Debugging: Well-designed algorithm makes debugging easy so that we can
identify logical error in the program.
3. Easy and Efficient Coding: An algorithm acts as a blueprint of a program and helps
during program development.
4. Independent of Programming Language: An algorithm is independent of
programming languages and can be easily coded using any high level language.

Disadvantages

An algorithm has following disadvantages:


1. Developing algorithm for complex problems would be time consuming and difficult to
understand.
2. Understanding complex logic through algorithms can be very difficult.

4.8 SUMMARY

Algorithm is a finite set of well-defined instructions or step-by-step description of the procedure


written in human readable language for solving a given problem. The purpose of using an
algorithm is to increase the reliability, accuracy and efficiency of obtaining solutions.There are two

31
common methods of representing an algorithm namely; flowchart and pseudocode. Designing an
algorithm has advantages of effective Communication, easy debugging, easy and efficient coding
and Independent of programming language the disadvantages are in the time consumption
especially when developing complex problems and difficulty in understanding complex logic
problem. Furthermore, one needs to understand the details of the algorithms involved so that one
can predict if there are special cases in which the coding won’twork quickly, or if it will produce
unacceptable results. By developing a good understanding of a large range of algorithms, you will
be able to choose the right one for a problem and applyit properly.

CHAPTER 5: FLOWCHARTS

5.1 OBJECTIVES

• Understand the basic concepts of flowcharts

• Apply basic symbols and notations to create flowcharts

• Understand the conditions that apply in the design of flowcharts

• Undertake simple flowcharting problems

5.2 CONCEPT OF FLOWCHARTS


A flowchart is a visual representation of an algorithm. A flowchart is a diagram made up of boxes,
diamonds and other shapes, connected by arrows. Each shape represents a step of the solution

32
process and the arrow represents the order or link among the steps. It is a diagram that shows each
step or progression through a process.
A well-made flowchart can be used to break big ideas into small, bite-sized pieces that are
expressed visually, so knowing how to make one is sort of like having a universal language. Being
able to flowchart makes it possible to communicate with any stakeholder or audience, because
visuals are typically easier to understand than words. For this reason, flowcharts are a valuable
type of business diagram but can also be used for more technical fields like manufacturing or
software engineering.

5.2.1 SYMBOLS USED IN CREATING A FLOWCHART

Whether you're trying to read a flowchart or creating a flowchart, knowing the most common
flowchart symbols and conventions is going to make it a lot easier. Here is a list of common
flowchart symbols you need to know, plus a rundown on some more intermediate process symbols
if you're looking for extra credit.

Table 5.1: Basic Flowchart Symbols

Symbol Name Function

Indicates any type of internal operation


Process
inside the Processor or Memory

Used for any Input / Output (I/O)


operation. Indicates that the computer is
input/output
to obtain data
or output results

33
Used to ask a question that can be
Decision answered in a binary format (Yes/No,
True/False)
Allows the flowchart to be drawn without
Connector intersecting lines or without a reverse
flow.

Used to invoke a subroutine or an


Predefined Process
Interrupt program.

Indicates the starting or ending of the


Terminal program, process, or interrupt program

Flow Lines Shows direction of flow.

5.2.2 INTERMEDIATE AND ADVANCED FLOWCHART SYMBOLS

As pointed out earlier, flowcharts illustrate where data are being input and output, where
information is being stored, what decisions need to be made, and which people need to be involved.
In addition to the basic flowchart conventions, rules, and symbols, these intermediate flowchart
symbols help describe a process with even more detail.
Document Symbols

Single and multiple document icons show additional points of reference involved in a flowchart.
They may be used to indicate items like “create an invoice” or “review testing paperwork.”

Data Symbols

34
Data symbols clarify where the data that the flowchart references are being stored. (You probably
won’t use the paper tape symbol, but it definitely came in handy back in the day.)
Input & Output Symbols

Input and output symbols show where and how data are coming in and out throughout a
process.
Merging & Connecting Symbols

Agreed-upon merging and connector symbols make it easier to connect flowcharts that span
multiple pages.

35
5.3 CONSIDERATIONS IN FLOWCHARTING

Understanding the function of different flowcharts and when to use them is important, but so is
how you design your flowcharts. That is why flowcharts need a balance between information and
design. They need to be informative but in a way that gets the people intended to read and use them.
Here are a few factors to consider when designing flowcharts.

Style and Design

• Direction is important. For the most part, charts should flow left-to-right or top-to-
bottom. Eyes follow this path naturally, making it easier for people looking at the
flowchart to understand them.
• Keep them on one page when possible. Charts are easier to digest when they're simple
and kept to one page. The more pages there are, the more complex the chart seems. To
be fair there might be times when you need more than one page and this is when you're
dealing with complex processes and have to be well documented. In that case, they can't
be summarized because key information might be lost.
• Use consistent sizing and spacing because uniform design makes them easier to read
and follow.
• Include a chart key. There are standard symbols that most flowcharts use. Because
these symbols are standardized, they make it easier to understand the flowchart. Also
include a key so that it is clear to people reading it the point you are passing across.
• Use no more than three colours. It's tempting to want to use as many colours as
possible to show a path or highlight certain information. But the truth is, the fewer
colours used, the easier it is to follow the flow of the chart.
Text and Content

• Stick to one font to make flowcharts easy to follow. Also, make sure that the fonts are
easy to read and large enough.
• Fewer words the better. Because documentation is important, don't get rid of it
completely. Instead, use flowcharts to emphasize the important parts and use the
documentation as backup with more details. Readability is important on charts so the
less words you use there, the better.

36
Access and Communication

• Know your audience and how to speak to them. Some flowcharts have to be more
technical than others but make sure the people reviewing them understand them. When
possible, make your charts as straight forward as possible.
Share flowcharts with the right teams
• Any teams that are affected by the information in theflowchart need to know where to
find it. Set up a documentation process that ensures that the right people see the charts.
This can be specific teams or the entire company. Keep in mind, if the entire company
has access, it makes sense to offer high-level details on what is included sothat everyone
viewing the charts understands them.

5.4 SAMPLE FLOWCHARTS

This section presents pictorial representation of some simple problems as flowcharts.

1. Draw a flowchart to solve the problem of a non-functioning light bulb

37
2. Draw a flowchart to find the square of a number

3. Draw a flowchart for adding the integers from 1 to 100 and print their sum.

38
39
4. Draw the Flowchart to find Roots of Quadratic equation 𝑎𝑥2 + 𝑏𝑥 + 𝑐 = 0 Thecoefficients
𝑎, 𝑏, 𝑐 are the input data

40
5.5 DIFFERENCES BETWEEN ALGORITHM AND FLOWCHART

Algorithm Flowchart

1. A method of representing the step- 1. Flowchart is diagrammatic


by-steplogical procedure for solving representation of an algorithm. It is
a problem constructed using different types of
2. It contains step-by-step English boxes and symbols.
descriptions, each step representing 2. The flowchart employs a series of
a particular operation leading to blocks and arrows, each of which
solution ofproblem represents a particular step in an
3. These are particularly useful for algorithm
smallproblems 3. These are useful for detailed
4. For complex programs, algorithms representations of complicated
proveto be inadequate programs
4. For complex programs, Flowcharts
proveto be adequate

5.6 ADVANTAGES OF FLOWCHARTS

1. The flowchart shows the logic of a problem displayed in pictorial fashion which
felicitates easier checking of an algorithm.
2. The Flowchart is good means of communication to other users. It is also a compact
means of recording an algorithm solution to a problem.
3. The flowchart allows the problem solver to break the problem into parts. These parts
can be connected to make master chart.
4. The flowchart is a permanent record of the solution which can be consulted at a later

41
time.

5.7 SUMMARY

Flowcharts are simple diagrams that map out a process, so that one can easily communicate it to
other people. They are typically used to define and analyse a process, build a step-by-step picture
of it. To draw a flow chart, identify the tasks and decisions that you make during a process, and write
them in order. Then, arrange these steps in the flow chart format, using the appropriate symbols.
CHAPTER 6: PSEUDOCODE
6.1 OBJECTIVES

• Understand the meaning and importance of pseudocode in problem solving


• Apply the rules guiding the use of pseudocodes
• Demonstrate basic skills in writing pseudocode for simple problems

6.2 MEANING AND DEFINITION OF PSEUDOCODE

Pseudocode is a term which is often used in programming and algorithm based fields. It is a
methodology that allows the programmer to represent the implementation of an algorithm. Simply,
we can say that it’s the cooked up representation of an algorithm. Often at times, algorithms are
represented with the help of pseudocodes as they can be interpreted by programmers no matter
what their programming background or knowledge is. Pseudocode, as the name suggests, is a false
code or a representation of code which can be understood by evena layman with some school level
programming knowledge. It’s simply an implementation of an algorithm in the form of annotations
and informative text written in plain English. It has no syntax like any of the programming
language and thus can’t be compiled or interpreted by the computer.
Although pseudocode is a syntax-free description of an algorithm, it must provide a full description
of the algorithm’s logic so that moving from it to implementation should be merely a task of
translating each line into code using the syntax of any programming language.

6.3 REASONS FOR USING PSEUDOCODE

1. Better readability. Often, programmers work alongside people from other domains,

42
such as mathematicians, business partners, managers, and so on. Using pseudocode to
explain the mechanics of the code will make the communication between the different
backgrounds easier and more efficient.
2. Ease up code construction. When the programmer goes through the process of
developing and generating pseudocode, the process of converting that into real code
written in any programming language will become much easier and faster as well.
3. A good middle point between flowchart and code. Moving directly from the idea to
the flowchart to the code is not always a smooth ride. That’s where pseudocode presentsa
way to make the transition between the different stages somewhat smoother.
4. Act as a start point for documentation. Documentation is an essential aspect of building a
good project. Often, starting documentation is the most difficult part.However, pseudocode
can represent a good starting point for what the documentation should include. Sometimes,
programmers include the pseudocode as a docstring at thebeginning of the code file.
5. Easier bug detection and fixing. Since pseudocode is written in a human-readable
format, it is easier to edit and discover bugs before actually writing a single line of code.
Editing pseudocode can be done more efficiently than testing, debugging, and fixing
actual code.
6.4 THE MAIN CONSTRUCTS OF PSEUDOCODE

The core of pseudocode is the ability to represent 6 programming constructs (always written in
uppercase): SEQUENCE, CASE, WHILE, REPEAT-UNTIL, FOR, and IF-THEN-ELSE. These
constructs — also called keywords —are used to describe the control flow of the algorithm.

i. SEQUENCE: This represents a set of steps performed one after another in a linear fashion.
Each step must be completed before moving on to the next. For example, if you have tasks
A, B, and C, they will be performed in the order A → B → C.
ii. WHILE: This is a loop structure where a condition is checked at the beginning. The loop
continues to execute as long as the condition is true. For example, "While it is raining, stay
indoors" means you keep staying indoors as long as it rains.
iii. REPEAT-UNTIL: This loop structure also involves repeating a set of actions, but the
condition is checked at the end. This means the loop will always execute at least once. For

43
example, "Repeat checking the temperature until it reaches 100°C" means you keep
checking until the temperature hits 100°C.
iv. FOR: This is another looping construct that typically involves a counter or an iterator,
running for a specific number of times or over a range of values. For example, "For each
item in the list, print the item" means you print each item one by one.
v. IF-THEN-ELSE: This is a conditional statement that changes the flow of the algorithm
based on a condition. If the condition is true, a specific set of actions is performed (THEN);
if not, an alternative set of actions can be performed (ELSE). For example, "If it is raining,
take an umbrella; otherwise, wear sunglasses."
vi. CASE: This is a more general form of the IF-THEN-ELSE structure, often used when there
are multiple conditions to check. It allows different actions to be taken based on different
cases. For example, "Case of the day of the week: Monday - go to work, Saturday - relax,
Sunday - family day" means different actions are taken depending on the day.

Although these 6 constructs are the most often used ones, you can theoretically use them
to implement any algorithm. You might find yourself needing some more based on your
specific application. Perhaps the two most needed commands are:
Table1.6.1:
Invoking classes
Constructs or calling functions (using the CALL keyword).
of Pseudocode

2. Handling exceptions (using EXCEPTION, WHEN keywords)

44
6.5 RULES FOR WRITING PSEUDOCODE

When writing pseudocode, everyone often has their own style of presenting things out since it’s
read by humans and not by a computer; its rules are less rigorous than that of a programming
language. However, there are some simple rules that help make pseudocode more universally
understood.

i. Capitalize the Initial Word: Start each line with a capitalized initial word, usually one of
the main constructs such as IF, WHILE, REPEAT, FOR, CASE, etc.
ii. One Statement per Line: Each line should contain only one statement. This helps in
maintaining clarity and simplicity in the pseudocode.
iii. Indentation for Hierarchy and Readability: Indent lines to show the hierarchy and
structure of the pseudocode. This helps in distinguishing nested constructs and improves
overall readability.
iv. End Multiline Sections with END Keywords: Use appropriate END keywords to close
multiline sections, such as ENDIF, ENDWHILE, ENDREPEAT, etc. This clearly marks
the end of a block or section.
v. Language Independence: Write pseudocode in a way that is not tied to any specific
programming language. This makes it easier to understand and translate into different
languages.

45
vi. Use Problem Domain Terminology: Use terminology relevant to the problem domain
rather than implementation-specific terms. For example, use "Append the last name to the
first name" instead of "name = first + last."
vii. Keep It Simple, Concise, and Readable: Pseudocode should be straightforward and easy
to understand. Avoid unnecessary complexity and focus on conveying the logic and
structure clearly.

Following these rules will help you generate readable pseudocode and be able to recognize a not
well-written one.
6.6 ADVANTAGES OF PSEUDOCODE

1. Improves the readability of any approach. It’s one of the best approaches to start
implementation of an algorithm.
2. Acts as a bridge between the program and the algorithm or flowchart. Also works as a
rough documentation, so the program of one developer can be understood easily whena
pseudo code is written out. In industries, the approach of documentation is essential.And
that’s where a pseudo-code proves vital.
3. The main goal of a pseudo code is to explain what exactly each line of a program should
do, hence making the code construction phase easier for the programmer.

6.7 WORKED EXAMPLES

1. Write pseudocode that reads two numbers and multiplies them together and print out their
product.

READ 𝑛𝑢𝑚1, 𝑛𝑢𝑚2

SET product to 𝑛𝑢𝑚1 * 𝑛𝑢𝑚2

Write product

2. Write pseudocode that tells a user that the number they entered is not a 5 or a 6.

a. READ number
b. IF number == 5 THEN
c. WRITE "Your number is 5"
d. ELSE IF number == 6 THEN

46
e. WRITE "Your number is 6"
f. ELSE
g. WRITE "Your number is not 5 or 6"

3. END IFWrite pseudocode to print all multiples of 5 between 1 and 100 (including both 1
and100).
SET x to 1 WHILE (x < 20)
WRITE x

WRITE x = x*5

ADD 1 to x
END WHILE

Let's break down the pseudocode:

i. SET x to 1:

This initializes a variable x with the value 1. It sets the starting point for the loop.

ii. WHILE x <= 20:

This begins a loop that will continue to run as long as the condition x <= 20 is
true. In other words, the loop will execute repeatedly while x is less than or
equal to 20.

iii. WRITE x * 5:

This command outputs the result of x * 5. For each iteration of the loop, it
multiplies the current value of x by 5 and writes (or displays) the result.

iv. ADD 1 to x:

This increments the value of x by 1 at the end of each loop iteration. After the
value of x is printed, the loop increases x by 1, preparing for the next iteration.

v. END WHILE:

47
This marks the end of the while loop. The loop will start over from the top
(checking if x <= 20) until the condition is no longer true.

4. Write pseudocode that will count all the even numbers up to a user defined stopping
point.
GET count
SET x to 0
WHILE (x < count)

SET even to even + 2

ADD 1 to x
WRITE even
ENDWHILE

Let's go through the pseudocode step-by-step:

i. READ count:

This instruction takes an input value from the user or another source and stores it in
the variable count. This value determines how many iterations the loop will run.

ii. SET x to 0:

This initializes the variable x to 0. x serves as a counter in the loop and will help in
calculating even numbers.

iii. WHILE x < count:

This starts a loop that will execute as long as the condition x < count is true. The
loop will continue running until x reaches the value of count.

iv. SET even to x * 2:

Inside the loop, this line calculates the even number corresponding to the current value
of x. By multiplying x by 2, the code generates even numbers (0, 2, 4, 6, etc.).

v. WRITE even:

48
This outputs the value of even to the screen or another output device. It prints the even
number calculated in the previous step.

vi. ADD 1 to x:

This increments the value of x by 1 after each iteration. It updates the counter so that
the next even number can be calculated in the next loop cycle.

vii. END WHILE:

This marks the end of the while loop. Once the condition x < count is no longer true,
the loop stops executing.

The pseudocode is designed to generate and print a series of even numbers starting from 0, up to
the number of even numbers specified by the count variable. The loop begins with x = 0 and
continues until x reaches count. During each iteration, it calculates an even number by multiplying
x by 2 and then prints this number. The loop progresses by increasing x by 1 each time, ensuring
that the next even number is calculated in the next cycle.

For example, if count is 5, the loop will print the first 5 even numbers: 0, 2, 4, 6, and 8.

6.8 SUMMARY

As the complexity and size of a problem increase, the need for generating pseudocode to make
writing the actual code much easier becomes more apparent. It helps the problem solver realize
possible problems or design flaws in the algorithm earlier in the development stage. Hence, saving
more time and effort on fixing bugs and avoiding errors. Moreover, pseudocode allowed
programmers to communicate more efficiently with others from different backgrounds, as it
delivers the algorithm's idea without the complexity of syntax restrictions. A clear, concise,
straightforward pseudocode can make a big difference in the road from idea to implementation, a
smooth ride for the programmer. It’s one of the overall tools underestimated by the programming
community but defiantly, needs to be utilized more.

49
CHAPTER 7: CONTROL STRUCTURES / SELECTION AND ITERATION

7.1 OBJECTIVES

• Explain control structures and their importance in implementation

• Apply selection control structure to implement algorithms

• Implement solutions using iteration as an alternative implementation strategy


• Combine control structures in ways that facilitate solution to the problem at hand

7.2 CONTROL STRUCTURES


Control structures are fundamental components of computer programs, acting as the framework
for decision-making. They allow a program to "make decisions" and follow different paths based
on conditions. Unlike a simple linear sequence of instructions, a program can branch out, repeat
certain sections, or skip others. Control structures evaluate variables and determine the course of
action based on specific criteria. The basic Control Structures in programming languages are:

• Selection (Conditionals): which are used to execute one or more statements if a


condition is met.
• Iteration (Loops): which purpose is to repeat a statement a certain number of times or
while a condition is fulfilled.
We now take a look at each one of these concepts
7.2.1 SELECTION

Selection is at the very core of programming. The idea behind them is that they allow the control
flow of the code that is executed based on different conditions in the program (e.g. an input taken
from the user, or the internal state of the machine the program is running on). In This section will
explore the If and the If-Else statements.

The If Statement

If statements execute one or more statements when a condition is met. If the testing of that
condition is TRUE, the statement gets executed. But if it is FALSE (the condition is not met),then
nothing happens. Let´s visualize it:

50
If statement

The syntax of the If statements is:

If(condition)
statements

Example

To show a simple case, let’s say you want to verify if the value of a variable (x) is positive:
x = 4

If(x >= 0) {

Print (“variable x is a positive number”)

In this example, first we assign the value of 4 to the variable (x) and use the “If statement” to verify
if that value is equal or greater than 0. If the test results TRUE (as in this case), the function will
print the sentence: “variable x is a positive number”.

Output

[1] "variable x is a positive number"

But since the If statement only executes a statement if the tested condition is TRUE, what would
have happened if the variable value was negative? To execute a statement on a tested condition

51
with a FALSE result, we need to use If-Else statement.
The If-Else Statement

This Control Structure allows a program to follow alternative paths of execution, whether a
condition is met or not.

If-Else statement

The syntax of “If-Else statements” is:

If(condition)
Statements
Else
statements

The else part of the instruction is optional and is only evaluated if the condition tests FALSE.
Example 1

Following our example, the previous conditional If statement is extended by adding the else part
to test if the value of a variable is positive or negative and perform an action i.e., whether the test
result is TRUE or FALSE.

x = -4

If(x >= 0) {

52
Print(“variable x is a positive number”)

}else {

Print(“variable x is a negative number”)

In this example, a value of -4 is assigned to the variable x and use the If statement to verify ifthat
value is equal to or greater than 0. If the test results TRUE, the function will print the sentence:
“variable x is a positive number”. But in case the test results FALSE (as in this case),the function
continues to the alternative expression and prints the sentence: “variable x is a negative number”.

Output

[1] "variable x is a negative number"


Example 2

Assume we need to define more than 2 conditions, as obtained in the grading of an exam. In that
case we can grade A, B, C, D or F (5 options), so, how can this be done?
If-Elsestatements can have multiple alternative statements. In the example below we define an
initial score, and an If-Else statement of 5 rating categories. This piece of code will go through
each condition until reaching a TRUE test result.
Score = 75
If(score >= 90) {
Print(“A”)

}else if(score >=80) {

Print(“B”)

} else if(score >=70) {

Print(“C”)

} else if(score >=60) {

Print(“D”)

}else {

Print(“F”)

53
}

Output

[1] “C”

SELECT CASE Statement

For a multi-way branching such as the above example, a handy construct to implement such
scenario is the Select Case statement, also referred to as CASE statement.
The following is its syntactic form:

SELECT CASE (selector)


CASE label-list-1
statements-1
CASE label-list-2
statements-2
CASE label-list-3
statements-3
.....
CASE label-list-n
statements-n
CASE DEFAULT
statements-DEFAULT
END SELECT
where statements-1, statements-2, statements-3, ..., statements-n and statements-DEFAULT are
sequences of executable statements, including the SELECT CASE statement itself, and selector
is an expression whose result is of type INTEGER, CHARACTER or LOGICAL or BOOLEAN
(i.e., no REAL type can be used for the selector). The label lists label-list-1, label-list-
2, label-list-3... and label-list-n are called case labels.

A label-list is a list of labels, separated by commas. Each label must be one of the following
forms.
value

54
value-1..value-2
value-1 :
: value-2

where value, value-1 and value-2 are constants. The type of these constants must bethe
same as that of the selector.
Example 3

We now implement example 2 above using the SELECT CASE statement.

Score = 75

Select Case(score) {
Case 90..100 {
Print(“A”)

break

Case 80..89 {

Print(“B”)

break

Case 70..79 {

Print(“C”)

break

Case 60..69 {

Print(“D”)

break

Case default {

55
Print(“F”)

End Select

Output

[1] “C”

Note: The above syntax is generalized and there may be slight differences in the actual
implementation by specific programming languages.

7.2.2 ITERATION (LOOPING)

Iteration is the automation of multi-step processes by organizing sequences of actions, and


grouping the parts that need to be repeated. Also a central part of programming, iteration (or
Looping) gives computers much of their power. They can repeat a sequence of steps as often as
necessary, and appropriate repetitions of simple steps can solve complex problems. Iterationallows
us to simplify our algorithm by stating that we will repeat certain steps until told otherwise.
In general terms, there are two types of “Looping techniques”:

1. For Loops: are the ones that execute for a prescribed number of times, as controlled
by a counter or an index.
2. While Loops and Repeat Loops: are based on the onset and verification of a logical
condition. The condition is tested at the start or end of the loop construct.
Let’s take a look at them:
For Loops

In this Control Structure, statements are executed one after another in a consecutive order over a
sequence of values that gets evaluated only when the For Loop is initiated (never re- evaluated).
In this case, the number of iterations is fixed and known in advance.

56
For Loop

If the evaluation of the condition on a variable (which can assume values within a specified
sequence) results TRUE, one or more statements will be executed sequentially over that stringof
values. Once the first condition test is done (and results TRUE), the statement is executed and the
condition is evaluated again, going through an iterative process. The “variable in sequence” section
performs this test on each value of the sequence until it covers the last element.
If the condition is not met and the resulting outcome is FALSE (e.g. the “variable in sequence”part
has finished going through all the elements of the sequence), the loop ends. If the condition test
results FALSE in the first iteration, the For Loop is never executed.

The syntax of For Loops is:

For (variable-in-sequence)
statements
Example

To show how For Loops work, first we will create a sequence by concatenating different names of
fruits to create a list called “fruit_list”:

57
Fruit_list = (‘Apple’, ‘Kiwi’, ‘Orange’, ‘Banana’)

We will use this fruit list as the “sequence” in a For Loop, and make the it run a statement once
(print the name of each value) for each provided value in the sequence (the different fruitsin the fruit
list):
Note: This example code is in Python.

for (i in fruit_list) {
print (i)
}

This way, the outcome of the For Loop is as follows:

[1] "Apple"
[1] "Kiwi"
[1] "Orange"
[1] "Banana"

While Loops

In While Loops a condition is first evaluated, and if the result of testing that condition is TRUE,
one or more statements are repeatedly executed until that condition becomes FALSE.

Unlike If statements, in which a condition tested as TRUE executes an expression only onceand
ends, While Loops are iterative statements that execute some expression over and over again

58
until the condition becomes FALSE. If the condition never turns out to be FALSE, the While
Loop will go on forever and the program will crash. The other way around, if the condition test
results FALSE in the beginning of the loop, the expression will never get executed.
The syntax of “While Loops” is:

While(condition)
statement

Example

First we will create a variable (x) and assign it the value of 1. Then we set a While Loop to
iteratively test a condition over that variable until the condition test results FALSE:

x = 1

while(x < 10) {


print (x)
x = x+1

This is how it works: the initial value of the variable x is 1, so when we test the condition “is the
variable (x) less than 10?”, the result evaluates to TRUE and the expression is executed, printing
the result of the variable x, which in the first case is 1. But then something happens: the variable
x is incremented by 1 before the function ends, and in the next iteration the valueof x will be 2.
This variable reassignment is important because it will eventually reach the FALSE condition and
the loop exit (value of x = 10). Failing to change the initial conditions in a While Loop will result
into an infinite loop, causing the program to crash.
Output

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5

59
[1] 6
[1] 7
[1] 8
[1] 9

Repeat Loops

Closely linked to While Loops, Repeat Loops execute statements iteratively, but until a stop
condition is met. This way, statements are executed at least once, no matter what the result of the
condition is, and the loop is exited only when certain condition becomes TRUE:

Repeat Loop

The syntax of “Repeat Loops” is:

Repeat

Statements
(Condition)
break

60
Repeat Loops use Break statements as a stop condition. Break statements are combined withthe
test of a condition to interrupt cycles within loops, since when the program hits a break, it will pass
control to the instruction immediately after the end of the loop (if any). Repeat Loops will run
forever if the Break condition is not met.

Example

First we create a variable x and assign it the value of 5. Then we set a Repeat Loop to iteratively
print the value of the variable, modify the value of the variable (increase it by 1), and test a
condition over that variable (if it equals 10) until the condition test results TRUE.
x = 5
Repeat {
print(x)
x = x+1
if(x == 10) {
break
}

The “breaking condition” triggers when the variable x reaches 10, and the loop ends.

Output

[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
7.3 SUMMARY

Though we have seen and explained Control Structures in isolation, they can actually be combined
anyway desired: Loops may contain several internal Loops; Conditionals may contain Loops and
Conditionals, the options are endless. You can develop advanced solutions just by combining the
Control Structures we explained in this section. We can reach complex outcomes as a result of the

61
interaction of simpler components. Control Structures constitute the basic blocks for decision
making processes in computing. They change the flow of programs and enable us to construct
complex sets of instructions out of simpler building blocks.

62
CHAPTER 8: TESTING AND DEBUGGING

8.1 OBJECTIVES

• Define and classify program tests

• Explain the desirable properties of program tests

• Appreciate the need for and benefits of program testing

• Understand the debugging process as well as types of programming errors

8.2 PROGRAM TESTING

Fundamentally, program testing is a process to check if the program or the entire system is working
same as it was supposed to do, and not working as it was not supposed to do. It is done by the tester
to identify the defects in the program or system to determine if actual result of testcase execution
matches or not with expected result. It can be done using manual and automated process. The issues
are logged against all the failed cases and are communicated to the development team for
debugging and fixing. After the bug fixes the tester then retests the bugand checks if the issues no
more exist.

8.3 TYPES OF PROGRAM TESTS

Unit Test

Unit test are low-level test that focus on testing a specific part of the system. They are cheapto
write and fast to run. Test failures should provide enough contextual information to pinpoint the
source of the error. Unit tests should be independent and isolated; interacting with external
components increases both the scope of the tests and the time it takes for the tests to run. The size
of a unit test depends on what we are trying to do. Thinking in terms of a unit of behaviour allows
writing tests around logical blocks of code.

63
Example

Suppose we have the following function that takes a list of words and returns the most common
word and the number of occurrences of that word:
def find_top_word(words)

# Return most common word & occurrences


word_counter = Counter(words)
return word_counter.most_common(1)[0]

We can test this function by creating a list, running the find_top_word() function over that list and
comparing the results of the function to the value we expect:

def test_find_top_word():
words = ["foo", "bar", "bat", "baz", "foo", "baz", "foo"]
result = find_top_word(words)

assert result[0] == "foo"


assert result[1] == 3

If we ever wanted to change the implementation of find_top_words(), we can do it without fear.


Our test ensures that the functionality of find_top_word() cannot change without causinga test
failure.

Integration Tests

Every complex application has internal and external components working together to do something
interesting. In contrast to units tests which focus on individual components, integration tests
combine various parts of the system and test them together as a group. Integration testing can also
refer to testing at service boundaries of our application, i.e. when itgoes out to the database, file
system, or external API (application program interface).
By definition, integration tests are larger in scope and take longer to run than unit tests. This means
that test failures require some investigation: we know that one of the components in ourtest is not
working, but the failure's exact location needs to be found. This is in contrast to unittests which are
smaller in scope and indicate exactly where things have failed. Integration tests should be run in a
production-like environment; this minimizes the chance that tests fail due to differences in

64
configuration.

End-to-End Tests

End-to-end tests check to see if the system meets our defined business requirements. A common
test is to trace a path through the system in the same manner a user would experience.For example,
we can test a new user workflow: simulate creating an account, "clicking" the link in the activate
email, logging-in for the first time, and interacting with our web application's tutorial modal pop-
up. We can conduct end-to-end tests through our user interface (UI) by leveraging a browser
automation tool like Chrome. This creates a dependency between our UI and our tests, which
makes our tests brittle: a change to the front-end requires us to change tests. This is not sustainable
as either our front-end will become static or our tests will not be run.
End-to-end tests are considered black box as we do not need to know anything about the
implementation in order to conduct testing. This also means that test failures provide no
indication of what went wrong; we would need to use logs to help us trace the error and
diagnose system failure.

Functional Tests

Functional tests focus on the business requirements of an application. They only verify the output
of an action and do not check the intermediate states of the system when performing that action.
There is sometimes a confusion between integration tests and functional tests as they both require
multiple components to interact with each other. The difference is that an integration test may
simply verify that one can query the database while a functional test wouldexpect to get a specific
value from the database as defined by the product requirements.

Smoke Tests

Smoke tests are basic tests that check basic functionality of the application. They are meant to be
quick to execute, and their goal is to give one the assurance that the major features of the system
are working as expected. Smoke tests can be useful right after a new build is made to decide
whether or not one can run more expensive tests, or right after a deployment to make sure that the
application is running properly in the newly deployed environment.

65
8.4 NEED FOR PROGRAM TESTING

Human errors can cause a defect or failure at any stage of the software development life cycle.The
results are classified as trivial or catastrophic, depending on the consequences of the error. The
requirement of rigorous testing and their associated documentation during the software
development life cycle arises because of the following reasons:

1. To identify defects

2. To reduce flaws in the component or system

3. Increase the overall quality of the system

There can also be a requirement to perform software testing to comply with legal requirementsor
industry-specific standards. These standards and rules can specify what kind of techniques should
we use for product development. For example, the motor, avionics, medical, and pharmaceutical
industries, etc., all have standards covering the testing of the product.

The following shows the significance of testing for a reliable and easy to use software product:

• The testing is important since it discovers defects/bugs before the delivery to the client,
which guarantees the quality of the software.
• It makes the software more reliable and easy to use.

• Thoroughly tested software ensures reliable and high-performance software operation.

For example, assume you are using a Net Banking application to transfer the amount to your
friend's account. So, you initiate the transaction, get a successful transaction message, and the
amount also deducts from your account. However, your friend confirms that his/her account has
not received any credits yet. Likewise, your account is also not reflecting the reversed transaction.
This will surely make you upset and leave you as an unsatisfied customer.

The question is, why did it happen? It is because of the improper testing of the net banking
application before release. Thorough testing of the website for all possible user operations would
lead to early identification of this problem. Therefore, one can fix it before releasing it to the public
for a smoother experience.

8.5 BENEFITS OF PROGRAM TESTING

66
A well-thought-out testing strategy paired with thorough test cases provides the following benefits:
Modify Code with Confidence

If a program does anything of interest, it has interactions between functions, classes, and modules.
This means a single line change can break our program in unexpected ways. Tests give us
confidence in our code. By running our tests after we modify our code, we can confirmour changes
did not break existing functionality as defined by our tests.
In contrast, modifying a code base without tests is a challenge. There is no way of knowing if
things are working as intended. We are programming by the seat of our pants, which is quite arisky
proposition.
Identify Bugs Early

Bugs cost money. How much depends on when you find them. Fixing bugs gets more expensivethe
further you are in the software development life cycle (SDLC).
Improve System Design

Though a bit controversial, writing code with tests in mind improves system design. A thoroughtest
suite shows that the developer has actually thought about the problem in some depth. Writing tests
compels you to write your own API which, hopefully results in a better interface.

8.6 DEBUGGING

Debugging is a computer programing process for finding and resolving errors in software or a
website, often referred to as "bugs." It often requires a comprehensive procedure to identify the
reason why a bug occurred and ensure a program can run smoothly for users in the future. Software
developers and engineers often debug programs using a digital tool to view and edit the coding
language, which contains instructions for how a program works. Debugging allows them to address
individual sections of code to ensure that every part of a program operates in an expected and
optimal way.

8.6.1 TYPES OF ERRORS TO DEBUG

Here are some examples of common errors you can encounter while debugging and how to address
them:
Syntax errors

67
Syntax errors are grammatical interruptions in a line of code. For example, an extra bracket or
period might cause a syntax error to occur. A compiler can often recognize a syntax error then
notify you in a separate message screen about where it is in the code and how to fix it using a
debugging tool. Some compilers also highlight them when you first load the program's code into
the system.
Logic errors

Logic errors are issues in the code's algorithms. They can occur when a program's code produces
an unexpected output or causes the program to stop working. For example, adding two number-
type variables when you intended to divide them might cause a logic error. You can resolve logic
errors by using a debugging tool to carefully examine the variable causing the issue in a line of
data.
Run-time errors

Run-time errors occur when a person uses the program and they're detected by the computer
executing it. They can still appear after you finish an initial debugging process because a computer
might interpret the program's code in an unexpected way. For example, an operatingsystem might
format code in a certain configuration that renders it unusable. To address theseerrors, it's important
to ensure an operating system has the information it needs to run a programcorrectly.
Interface errors

Interface errors involve a disconnect in an API, which means one or both coding languages in an
API cause this error to occur. For example, an API might have certain requirements that are only
present in the code of one program. To address an interface error, compare and contrast lines in
your code with the other. Be sure to have records of any debugging and testing processes
you completed in the past to help streamline this step.

8.7 DIFFERENCE BETWEEN TESTING AND DEBUGGING

Testing Debugging
Testing gets started with known conditions This is manual step by step unstructured and
with expected results. unreliable process to find and removes a
specific bug from the system.

68
It performed based on the testing type
which we need to perform unit testing,
It performed based on the type of bug.
integration testing, system testing, user
acceptance testing, etc.
Testing is the process which can be planned, Debugging is the process which cannot be so
designed and executed. forced.
It is the process to identify the failure of It is the process to give the absolution to code
implemented code. failure.
It is a demonstration of error or apparent It is always treated as a deductive process.
correctness.
Testing is the display of errors It is a deductive process
Design knowledge is not required for Detailed design knowledge is definitely
testing the system under test. Any person required to perform debugging.
with or without test case can do testing.
Testing can be outsourced to outside team Debugging cannot be out sourced to outside
as well. team. It must be done by inside development
team.
Most of the test cases in testing can be Automation in the debugging cannot possible.
automated.
Testing is the process to identify the bugs Debugging is the process to identify the root
in the system under test. cause of the bugs.

8.8 SUMMARY

The importance of software testing is imperative. Program testing is a crucial component of


software product development because it improves consistency and performance. The main benefit
of testing is the identification and subsequent removal of the errors. However, testing also helps
developers and testers to compare actual and expected results in order to improve quality. If the
software production happens without testing it, it could be useless or sometimes dangerous for
customers. So, a tester should wear a unique hat that protects the reliability of the software and
makes it safe to use in real-life scenarios.

69
CHAPTER 9: PROGRAM IMPLEMENTATION

9.1 OBJECTIVES
• Develop practical coding skills
• Foster logical thinking and problem-solving abilities

9.2 PROGRAM IMPLEMENTATION


Program implementation involves translating an algorithm or a set of instructions into a specific
programming language, such as Python, to solve a problem. It involves writing code that follows
the syntax and rules of the chosen programming language. Once you have the algorithm and
flowchart in place, you can proceed with the implementation phase. Here's an overview of the
steps involved in implementing a program in Python:

i. Understand the problem: Make sure you have a clear understanding of the problem you are

70
trying to solve. Break it down into smaller tasks or sub-problems.

ii. Design the algorithm: Create a step-by-step plan or algorithm for solving the problem. This
can be done using flowcharts, pseudocode, or simply written descriptions.

iii. Choose an appropriate programming language: In this case, you have already chosen
Python as the programming language for implementation.

iv. Write the code: Start translating the algorithm into Python code. Begin with the main
structure of the program, such as defining functions, classes, or modules, and then fill in
the details.

v. Break down the problem into functions: Divide the problem into smaller functions or
modules that perform specific tasks. This makes the code more modular, readable, and
maintainable.

vi. Implement the logic: Write the code to implement the logic of each function, following the
algorithm you designed. Use appropriate control structures, such as loops and conditional
statements, to control the flow of execution.

vii. Test and debug: After writing the code, test it with various inputs to ensure it produces the
expected results. Debug any errors or logical issues that may arise during testing.
viii. Optimize and refine: Once the code is working correctly, you can consider optimizing it
for performance or making improvements to enhance its efficiency or readability.

9.3 PROGRAM IMPLEMENTATION EXAMPLES


Example 1: Write a Python program to find the sum and average of three numbers
Description:
sum = number1+number2+number3
Average = sum/3
Algorithm:
Step 1: Start
Step 2: Declare variables num1, num2, num3 and sum, avg.
Step 3: Read values num1,num2, num3
Step 4: Add num1, num2, num3 and assign the result to sum.
sum = num1+num2 +num3

71
avg = sum/3
Step 5: Display sum and average
Step 6: Stop

Flowchart:

Python code:
# Input the three numbers
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))

# Calculate the sum


sum = num1 + num2 + num3

# Calculate the average


avg = sum_of_numbers / 3

# Print the sum and average


print("Sum of the numbers:", sum)
print("Average of the numbers:", avg)

Example 2: Write a Python program to find the exponentiation (Power of a number).

72
Algorithm:
Step 1: Start
Step 2: read a, b
Step 3: r= a**b
Step 4: Display r
Step 5: Stop
Flowchart:

Python code:
a = int(input(“enter value a:”))
b = int(input(“enter value b:”))
r = a**b
print(“exponentiation is”, r)

Example 3: write a Python program to convert the length in feet to centimeter


Description:
Input the length in feet (Lft)
Calculate the length in an (LCM) by multiplying LFT with 30
Print Length in Cm (LCM)

73
Algorithm:
Step 1: Start
Step 2: Input Lft
Step 3: Lcm = Lft * 30
Step 4: Display Lcm
Step 5: Stop
Flowchart:

Python code:

Lft = int(input("Enter the value of Lft: "))


Lcm = Lft * 30
print("The calculated Lcm is:", Lcm)

9.4 SUMMARY

In the program implementation lesson, we discussed the process of translating problem-solving


algorithms into actual code. Through hands-on exercises and projects, students gained practical
coding skills and became familiar with a specific programming language, such as Python. They

74
learned how to write code that follows the syntax and conventions of the language, enabling them
to express their solutions effectively. The lesson also focused on fostering logical thinking and
problem-solving abilities. By breaking down problems into smaller components and designing
algorithms to solve them, students developed their analytical skills. They learned to think critically
and logically about approaching problems, which is valuable not only in programming but also in
various other disciplines and real-life situations.

75

You might also like