Intro to Programming Module 2A
Intro to Programming Module 2A
Module 2 of 4 modules
Programming 1
Philip L. Balagtey
09514915726
[email protected]
Information Technology
1st Semester, School Year 2021-2022
INTRODUCTION
LEARNING OUTCOMES
At the end of the module, you should be able to:
a. analyze a problem and identify the computing requirements
appropriate for its solution;
b. design, implement, and evaluate an algorithm to meet desired needs;
c. apply design and development principles in the construction of program
of varying complexity.
d. apply current techniques, skills, and tools necessary for computing
practice.
PRE-TEST
The following questions cover general areas of this module. You may not know
the answers to all questions, but please attempt to answer them without asking
others or referring to books.
Choose the best answer for each question and write the letter of your choice after
the number.
a. Decision
b. Input/Output
c. Process
d. Start
1
2. A diagram to show each step.
a. Algorithm
b. Flowchart
c. Pseudocode
d. Program
a. Decision
b. Input/Output
c. Process
d. Start
a. Decision
b. Input/Output
c. Process
d. Start
6. What is an algorithm?
a. A flowchart
b. A decision
c. A pseudocode
d. A step by step instructions used to solve a problem
2
9. Which is not true about the arrows used in a flowchart?
a. Direction of arrow shows the flow in a flowchart.
b. Arrows are used show the sequence of the problem solving.
c. Arrows are used to connect boxes in a flowchart.
d. Arrows can be used to represent an input.
3
LESSON 1: Algorithm
Objectives:
At the end of the lesson, you should be able to:
1. understand the basics and usefulness of an algorithm,
2. analyzed various algorithmic solutions to the problem; and,
3. implement the algorithmic solutions to a given problem.
LET’S ENGAGE
Algorithms are judged not only by how well they solve a problem, but also
by how effectively they use resources like time and space. We will learn
techniques for analyzing time and space complexity of algorithms and will use
these to evaluate tradeoffs between different algorithms. We will also see that
problems can be organized into a hierarchy that measures their inherent
difficulty by the efficiency of the best possible algorithm for solving them.
It is possible to create algorithms for the things that we do every day such
as making breakfast, brushing teeth, taking a bath and washing your clothes.
Before we start our lesson, let’s try doing this activity. How do you cook
adobo?
Write your answers on a short bond paper. Put numbers next to your
response to indicate the order of the steps.
Recipe
2 lbs pork belly
2 tablespoons garlic minced or crushed
5 pieces dried laurel leaves
4 tablespoons vinegar
1/2 cup soy sauce
1 tablespoon black pepper
2 cups water
Salt to taste
4
been bringing us faster and faster hardware. The other is efficient algorithms
that are fuelling the computer revolution.
In mathematics, computer science, and related subjects, an algorithm is a
finite sequence of steps expressed for solving a problem. An algorithm can be
defined as “a process that performs some sequence of operations in order to solve
a given problem”. Algorithms are used for calculation, data processing, and many
other fields.
In computing, algorithms are essential because they serve as the
systematic procedures that computers require. A good algorithm is like using the
right tool in the workshop. It does the job with the right amount of effort. Using
the wrong algorithm or one that is not clearly defined is like trying to cut a piece
of plywood with a pair of scissors: although the job may get done, you have to
wonder how effective you were in completing it.
Let us follow an example to help us understand the concept of algorithm
in a better way. Let’s say that you have a friend arriving at the bus station from
Bontoc, Mountain Province, and your friend needs to get from the bus station to
your house. Here are two different ways (algorithms) that you might give your
friend for getting to your home.
Algorithm 1
When your bus arrives at the bus station
Wait for a taxi
Get in a taxi
Tell the driver my address
Algorithm 2
When your bus arrives at the bus station, call me
Wait for me at the bus station.
All these algorithms accomplish the same goal, but each algorithm does it
in a different way. Each algorithm also has a different cost and a different travel
time. Taking a taxi, for example, is the fastest way, but also the most expensive.
Waiting for your friend is definitely less expensive, but a whole lot slower. You
choose the algorithm based on the circumstances.
In computer programming, there are often many different algorithms to
achieve any given task. Each algorithm has advantages and disadvantages in
different circumstances. Sorting is one place where a lot of research has been
done, because computers spend a lot of time sorting lists.
Three reasons for using algorithms are efficiency, abstraction and
reusability.
5
Efficiency: Certain types of problems, like sorting, occur often in computing.
Efficient algorithms must be used to solve such problems considering the time
and cost factor involved in each algorithm.
Abstraction: Algorithms provide a level of abstraction in solving problems
because many seemingly complicated problems can be distilled into simpler ones
for which well-known algorithms exist. Once we see a more complicated problem
in a simpler light, we can think of the simpler problem as just an abstraction of
the more complicated one. For example, imagine trying to find the shortest way
to route a packet between two gateways in an internet. Once we realize that this
problem is just a variation of the more general shortest path problem, we can
solve it using the generalized approach.
Reusability: Algorithms are often reusable in many different situations. Since
many well-known algorithms are the generalizations of more complicated ones,
and since many complicated problems can be distilled into simpler ones, an
efficient means of solving certain simpler problems potentially lets us solve many
complicated problems.
Expressing Algorithms
Algorithms can be expressed in many different notations, including
natural languages, pseudocode, flowcharts and programming languages.
Natural language expressions of algorithms tend to be verbose and ambiguous,
and are rarely used for complex or technical algorithms. Pseudocode and
flowcharts are structured ways to express algorithms that avoid many
ambiguities common in natural language statements, while remaining
independent of a particular implementation language. Programming languages
are primarily intended for expressing algorithms in a form that can be executed
by a computer, but are often used to define or document algorithms.
Sometimes it is helpful in the description of an algorithm to supplement
small flowcharts with natural language and/or arithmetic expressions written
inside block diagrams to summarize what the flowcharts are accomplishing.
Algorithm using natural language statements:
Start
Assume that the first number is 10
Assume that the second number is 5
Add 10 and 5
Display the output
Stop
Start
Algorithm using pseudocode
Num1=10;
Num2=5;
Sum=Num1 + Num2;
Print Sum;
Stop
6
Benefits of Using Algorithms
The use of algorithms provides a number of benefits. One of these benefits
is in the development of the procedure itself, which involves identification of the
processes, major decision points, and variables necessary to solve the problem.
Developing an algorithm allows and even forces examination of the solution
process in a rational manner. Identification of the processes and decision points
reduces the task into a series of smaller steps of more manageable size. Problems
that would be difficult or impossible to solve in entirety can be approached as a
series of small, solvable sub-problems.
By using an algorithm, decision making becomes a more rational process.
In addition to making the process more rational, use of algorithm will make the
process more efficient and more consistent. Efficiency is an inherent result of
the analysis and specification process. Consistency comes from both the use of
the same specified process and increased skill in applying the process. An
algorithm serves as a mnemonic device and helps ensure that variables or parts
of the problem are not ignored. Presenting the solution process as an algorithm
allows more precise communication. Finally, separation of the procedure steps
facilitates division of labor and development of expertise.
A final benefit of the use of an algorithm comes from the improvement it
makes possible. If the problem solver does not know what was done, he or she
will not know what was done wrong. As time goes by and results are compared
with goals, the existence of a specified solution process allows identification of
weaknesses and errors in the process. Reduction of a task to a specified set of
steps or algorithm is an important part of analysis, control and evaluation.
7
Print length in cm
Stop
An algorithm to compute the area of a rectangle
Start
Input the width
Input the length
Calculate the area by multiplying width with length
Print area
Stop
Self-Assessment
1. Given the number of commodities bought, create an algorithm that computes
the total amount purchased in a fast food center. Assume the following unit price
of each commodity:
Spaghetti - P65.00
Cheeseburger - P45.00
Soft drinks - P20.00
Fried Chicken - P45.00
2. Create an algorithm that computes the average grade of a student, given his
grade four subjects: Filipino, Math, English and Science. Assume that all
subjects are 1 unit except for science with 2 units.
3. Create an algorithm that will compute the weekly salary of an employee. The
algorithm will ask for the number of days worked and the rate per day.
Selection
It refers to a decision based on a certain condition. If the condition is true,
one of the two branches is explored otherwise the other alternative is taken or
executed. This is usually presented in if-else construct in programming.
An algorithm that reads to values, determines the larger value and prints the
larger value.
Start
Input first value
Input second value
If first value is greater than second value, then
Larger value is the first value, otherwise
Larger value is the second value
Stop
Below is an algorithm that will ask the user to enter to enter his/her name
and sex. Then displays a message on the screen whether he/she is a boy or a
girl.
8
Start
Input name
Input sex
If sex is equal to "Male"
Display "You are a Boy" otherwise
Display "You are a Girl" otherwise
Stop
Another example of algorithm using the select construct that ask a
person's name and age, and display if he/she is a minor or not.
Start
Input name
Input age
If age is lesser or equal to 17
Display "Minor" otherwise
Display "Not a Minor" otherwise
Stop
Self-assessment
1. Create an algorithm that will determine and display on the screen if an entered
number is a positive or a negative.
2. Create an algorithm that will display the amount to be paid by a customer if
he/she is given 10% discount rate for buying an item that costs more than
P1000.00 otherwise only 3%.
Iteration
Iteration is the repetition of a process in a computer program. Iterations of
functions are common in computer programming, since they allow several blocks
of data to be processed in sequence. This is normally done using a looping
statement in programming. These loops will repeat a process until a certain
number, case or condition is reached.
9
While counter is lesser than 10
Display counter
Increment counter with 1
End while
Stop
An algorithm that reads 10 numbers.
Start
Set counter to 1
While counter is lesser than 10
Then Input a number
Increment counter with 1
End while
Stop
If you want to know more about algorithm, visit the following:
How To Get Better At Writing Algorithms.
https://panlasangpinoy.com/filipino-food-pork-adobo-recipe/
Introduction to Algorithm. https://www.youtube.com/watch?v=gcQMBK53UjI
BBC Ideas. “What is algorithm and how do they work”.
https://www.youtube.com/watch?v=ZnBF2GeAKbo
2. Create an algorithm that will input an hourly rate and the number of
hours worked for the week. Compute their pay for the week and display
the output.
3. Design the algorithm that computes your age. It should accept your
birth year and the year of the next election. The algorithm then checks
if you are qualified to cast your vote in the coming election.
10
LESSON 2: Flowchart
Objectives
At the end of the lesson, you should be able to:
1. translate algorithms to flowchart; and,
2. design a solution for a certain problem using flowchart.
LET’S ENGAGE
Flow charts are a useful tool in these situations, as they make a process
easy to understand at a glance. Using just a few words and some simple
symbols, they show clearly what happens at each stage and how this affects
other decisions and actions.
The blue flowchart is meant to show the steps on how to stop working
and shutting down the computer.
Place the instruction below in the flowchart. Some of the instructions are
not required, include only those are relevant to the task.
Start
Stop
11
LET’S TALK ABOUT IT.
Flowchart
A Flowchart is a type of diagram (graphical or symbolic) that represents an
algorithm or process. Each step in the process is represented by a different
symbol and contains a short description of the process step. The flow chart
symbols are linked together with arrows showing the process flow direction. A
flowchart typically shows the flow of data in a process, detailing the
operations/steps in a pictorial format which is easier to understand than reading
it in a textual format.
A flowchart describes what operations (and in what sequence) are required
to solve a given problem. A flowchart can be likened to the blueprint of a building.
As we know a designer draws a blueprint before starting construction on a
building. Similarly, a programmer prefers to draw a flowchart prior to writing a
computer program.
Flowcharts are a pictorial or graphical representation of a process. The
purpose of all flow charts is to communicate how a process works or should work
without any technical or group specific jargon.
Flowcharts are used in analyzing, designing, documenting or managing a
process or program in various fields.
Flowcharts are generally drawn in the early stages of formulating computer
solutions. Flowcharts often facilitate communication between programmers and
business people. These flowcharts play a vital role in the programming of a
problem and are quite helpful in understanding the logic of complicated and
lengthy problems. Once the flowchart is drawn, it becomes easy to write the
program in any high level language. Often we see how flowcharts are helpful in
explaining the program to others. Hence, it is correct to say that a flowchart is
a must for the better documentation of a complex program.
For example, consider that we need to find the sum, average and product
of 3 numbers given by the user.
Algorithm for the given problem is as follows:
Start
Read num1, num2, num3
Compute sum as num1+num2+num3
Computer average as sum/3
Compute product as num1 x num2 x num3
Write/Display the sum, average and product
Stop
Flowchart for the above problem will look like
12
Start
Read num1,num2,num3
sum= num1+num2+num3
average = S/3
product=X * Y * A
Write
sum,average,product
Stop
Now that we have seen an example of a flowchart let us list the advantages
and limitations of using flowcharts.
13
Complex logic: Sometimes, the program logic is quite complicated. In that case,
flowchart becomes complex and clumsy.
Alterations and Modifications: If alterations are required the flowchart may
require re-drawing completely.
Reproduction: As the flowchart symbols cannot be typed, reproduction of
flowchart becomes a problem.
The essentials of what is done can easily be lost in the technical details of how
it is done.
14
Process: A rectangular flow chart shape indicates a normal/generic process flow
step. For example, “Add 1 to X”, “M = M*F” or similar.
Decision: A diamond flow chart shape indicates a branch in the process flow.
This symbol is used when a decision needs to be made, commonly a Yes/No
question or True/False test.
Connector: A small, labelled, circular flow chart shape used to indicate a jump
in the process flow. Connectors are generally used in complex or multi-sheet
diagrams.
On-page off-page
Data: A parallelogram that indicates data input or output (I/O) for a process.
Examples: Get X from the user, Display X.
Arrow: used to show the flow of control in a process. An arrow coming from one
symbol and ending at another symbol represents that control passes to the
symbol the arrow points to.
These are the basic symbols used generally. Now, the basic guidelines for
drawing a flowchart with the above symbols are that:
In drawing a proper flowchart, all necessary requirements should be listed
out in logical order.
The flowchart should be neat, clear and easy to follow. There should not
be any room for ambiguity in understanding the flowchart.
The flowchart is to be read left to right or top to bottom.
A process symbol can have only one flow line coming out of it.
15
For a decision symbol, only one flow line can enter it, but multiple lines
can leave it to denote possible answers.
The terminal symbols can only have one flow line in conjunction with
them.
Start
Read LFeet
LCenti = LFeet * 30
Write LCenti
Stop
16
Start
Area = Width *
Length
Write Area
Stop
Self-Assessment.
1. Given the number of commodities bought, create an algorithm that computes
the total amount purchased in a fast food center. Assume the following unit price
of each commodity:
Spaghetti - P65.00
Cheeseburger - P45.00
Soft drinks - P20.00
Fried Chicken - P45.00
2. Create an algorithm that computes the average grade of a student, given his
grade four subjects: Filipino, Math, English and Science. Assume that all
subjects are 1 unit except for science with 2 units.
3. Create an algorithm that will compute the weekly salary of an employee. The
algorithm will ask for the number of days worked and the rate per day.
Selection
Once the condition is evaluated, the control flows into one of two paths.
Once the conditional execution is finished, the flows rejoin before leaving the
structure. Once again the single entry, single exit nature of a structure is evident.
Either process could be replaced with any structure (sequence, selection, or
repetition) or it could be omitted (for example the process on the "NO" side might
not exist).
As an alternative, the "Question" could be replaced with a Boolean
expression and the branches labelled "TRUE" and "FALSE".
A flowchart that reads to values, determines the larger value and prints
the larger value.
17
Start
Input first value
Input second value
If first value is greater than second value then
Larger value is the first value, otherwise
Larger value is the second value
Stop
Start
N
If val1 > val2
Stop
Start Start
Input name
Input sex Read name Read sex
If sex==Male
Display "You are a Boy" otherwise
Y
Display "You are a Girl" If sex==
"Male"
Stop
N
Display "You
are a Boy" Display "You
are a girl"
Stop
18
Another example of flowchart using the select construct that ask a
person's name and age, and display if he/she is a minor or not.
Input name
Input age
If age is lesser than or equal to 17
Display "You are a minor" otherwise
Display "You are not a m"
Start
Y
If <= 17
Display "You
Display "You
are a minor"
are not a
minor"
Stop
Self-Assessment
a. Create an algorithm that will determine and display on the screen if an
entered number is a positive or a negative.
b. Create an algorithm that will display the amount to be paid by a customer
if he/she is given 10% discount rate for buying an item that costs more
than P1000.00 otherwise only 3%.
Repetition
Either the processing repeats or the control leaves the structure. (Again,
the process could be replacing another structure).
Notice that the return line joins the entry line before the question. Never
try to insert processing in the entry line between the join and the question.
The flowchart below will display "Hello World" 5 times.
19
Set counter to 1
While counter is lesser than 5
Display "Hello World"
Increment counter with 1
End while
Start
N
While counter
Counter = 1
<=5
Y
Display
"Hello
World"
Counter = Counter
+1
Stop
Display
counter
Counter = Counter
+1
20
Start
Set counter to 1
While counter is lesser than or equal to 10
Then Input a number
Increment counter with 1
End while
Stop
Start
N
While counter
Counter = 1 <=10
Input
number
Counter = Counter
+1
Stop
Self-Assessment
a. Create a flowchart that will add numbers from 1 to 10
b. Create a program that will accept the quiz scores of a student and
display his average, given the total number of quizzes he has taken.
If you want to know more about algorithm, visit the following:
The friendship algorithm Retrieved from
https://www.youtube.com/watch?v=k0xgjUhEG3U
Activity: Perform the following activities, write your answers in a short bond
paper.
1. Draw a flowchart to match the following algorithm.
Give variable num1 a starting value of 5
Give variable num2 a starting value of 10
Add 7 to num2
21
Store the value num1 times num2 in variable num3
Store the value num2 minus num1 in num2
Output num1, num2 and num3
2. Draw a flowchart that computes your age. It should accept your birth year
and the year of the next election. The algorithm then checks if you are
qualified to cast your vote in the coming election.
3. Draw a flowchart that will accept and compute 10 numbers. Display the
sum.
22
POST ASSESSMENT
Read carefully the statement below and perform what is being asked. Write your
answers in a short bond paper.
1. What is an algorithm? List the characteristics of an algorithm.
2. What is a flowchart? Differentiate the two types of flowchart.
3. What are the common guidelines of flowchart?
4. List flowcharting symbols along with their meaning.
5. Write two disadvantages of flowchart.
6. Draw a flowchart to find the greatest number among three numbers.
7. Write the algorithm and flowchart to display HCF
8. Write the algorithm and flowchart to display LCM
9. Draw a flowchart to display the numbers from 10 – 1
10. Write the algorithm to compute your final grade where,
Formula:
Finalgrade = (TentativeFInal Grad x 2) + MiddleTerm Grade
3
REFERENCES
https://www.java-made-easy.com/java-output.html#ixzz6Tsh9bQn8
https://java.com/en/download/help/download_options.xml
Programming Knowledge. Retrieved from
https://www.youtube.com/watch?v=pgr-Bzkc4zg
Atiwong Suchato. Learning Computer Programming using Java with 101
Samples.
www.computerhope.com
https://www.tutorialspoint.com/computer_fundamentals/computer_output_de
vices.htm
http://www.btechsmartclass.com/c_programming/C-Program-Development-
Life-Cycle.html
Programming Languages: Low Level, machine language, Assembly, High Level
Language (HLL); Algorithm and Flow chart: Concept and Uses
What is a computer language. Retrieved from
https://www.tutorialspoint.com/what-is-a-computer-language
D.S. Malik (2012). Java Programming: Problem Analysis to Program Design 5th
Edition.
23