You are on page 1of 19

Problem Solving The

Algorithmic WayPart 1
Table of Contents
Problem Solving The Algorithmic WayPart 1 ................................... 1

Appendix: Solutions to Check Your Understanding........................... 16


Problem Solving The Algorithmic Way

Problem Solving The Algorithmic WayPart 1


Session Overview
This session builds around the problem-solving approach to programming using algorithms. The
session helps you understand the need for designing algorithms before programming. In addition, the
session explains how to use algorithms for problem solving. The session also discusses the various
forms of algorithms.

Session Objectives
Identify the need for problem solving in programming
Use algorithms for problem solving
Identify the structure of an algorithm
Identify the forms of algorithm

Session Breakup
S. No. Duration
Section
(Minutes)
1 Introduction to Problem Solving for 05
Programming
2 Need for Problem Solving in Programming 08
3 Algorithms for Problem Solving 05
4 Using Algorithms 02
5 What is an Algorithm? 03
6 Characteristics of an Algorithm 05
7 Steps for Creating an Algorithm 05
8 Structure of an Algorithm 10
9 Forms of Algorithms 05
10 Types of Algorithms 05
11 Check Your Understanding 05
12 Summary 02
Total 60 minutes

NIIT Yuva Jyoti


1
Problem Solving The Algorithmic Way

Introduction to Problem Solving for Programming


All programs are developed to overcome a challenge or solve a problem. The ideal way to solve a
problem is to define the problem and then design its solution. After you have designed a solution, it
becomes easier to develop programs for that solution.
For example, you need to reach your college by 9 a.m. You can take one of the two modes of
transportthe city bus or the metro. The metro station is 10 minutes away from your house, and it
takes you just 15 minutes to reach the college. On the other hand, the bus stop is 5 minutes away but
the bus takes 20 minutes to reach college. In addition, the bus may take longer depending on the
traffic. If you leave the house at 8:25 a.m., which mode of transport should you take to reach college
on time?
The preceding scenario is a typical problem you face in your daily life. Your programming problems
are no different, and you need to approach the problems in programming the same way you would do
in your daily life. The first step to approach a problem is to design the solution instead of finalising the
solution.

Need for Problem Solving in Programming


Consider a scenario to understand the need for problem solving before writing a code.
You are working in a multinational company. The annual team meeting of your division is scheduled
for November and will be held in Nainital. Your supervisor has asked you to arrange for
accommodation for the entire team. It is already middle October and due to festive seasons, you
foresee difficulty in bookings. What should you do?
In the preceding scenario, the first reaction would be to pick up the phone and start calling hotels for
reservations. You search the Internet for contact details of various hotels in Nainital and call them to
enquire about availability. Since you did not plan your calls, you do not know the number of people
who will be attending the meeting, the exact dates of the meeting and the number of rooms you
require to book. This would result in waste of time and effort with a possibility of not arriving at a
desired solution.
What would be the correct approach to solve the problem?
The preceding scenario is an example of a situation you will find yourself in, when asked to develop a
program. Making random calls without any planning is very similar to writing a code for a problem
without any plan or a design.

NIIT Yuva Jyoti


2
Problem Solving The Algorithmic Way

The following figure shows the correct way of arriving at a solution for a problem:

The disadvantages of straightaway coding are:


You tend to create complex, large code snippets.
You end up writing code where one code snippet is closely dependent on the other.
You face difficulty in maintaining the code if the code is large.
You cannot make additions to the code later as it would likely disrupt the entire design of
the program. This is because the code was not made to adapt to future changes.
You are less likely to reuse the code, since there are very few smaller modules.
You would be at the risk of introducing errors if the code is large and then face difficulty in
debugging the code.
Programming is the skill of understanding a task and following a methodology to write a computer
program to automate it. As a programmer, your aim is to write good programs.

A computer program is a set of instructions written in a programming


language, which the processor can decode to perform the specific task.

Problem solving and critical thinking help you write programs faster. When thinking in a group, you
tend to get innovative ideas for efficiently solving or developing a problem or program, respectively.
For example, a large program can be broken down into simpler smaller modules, which could be later
integrated. In this manner, the same program is shared by many developers, thereby saving time.
Moreover, smaller modules are easy to maintain and reuse.

NIIT Yuva Jyoti


3
Problem Solving The Algorithmic Way

Problem solving for programming is done as follows:

In the preceding scenario, where you need to book a hotel for your team, the problem-solving
approach before booking the hotel should be:
1. Identify the problem:
Too many people
Rush due to festive season
Less time left for booking
2. Arrive at the solution:
The number of people going
Whether to book rooms on twin-sharing basis
Asking peers if someone has done such a task before
Asking your supervisor if the organisation has a corporate travel agent
The allotted budget
3. Develop the solution into an algorithm: Based on the responses to the preceding
questions, you arrive at the solution as:
Total number of persons going is 20.
The rooms can be booked on twin-sharing basis. Moreover, as the weather is cold,
non-AC rooms can be booked.
Contact the travel agent suggested by your supervisor to share the details of booking.
Inform the travel agent about the budget given by your supervisor.
4. Check the algorithm for results: On confirmation of the booking, verify that:
The number of rooms booked is correct.
Dates of arrival and departure are correct.
Location is appropriate.
The cost is within budget.

NIIT Yuva Jyoti


4
Problem Solving The Algorithmic Way

Algorithms for Problem Solving


Programming is a means to solve a problem faced by your customer and enable a processor
(computer or any other embedded device with a processor) to perform a desired task.
Your customers requirement is the problem statement for you, and your responsibility as a developer
is to give a solution to the problem in form of a written program.
To find a solution to a problem, follow a methodology and do not straightaway start coding. The right
programming methodology requires you to:
Adopt an analytical problem-solving approach.
Critically think about the given problem.
Problem solving refers to a systematic approach to defining a problem. You identify the situations or
tasks that present uncertainties or difficulties. Then, you need to overcome or reduce these
uncertainties or difficulties and create a vast number of possible solutions without judging these
solutions.
Selecting the optimum solution from various options and implementing it help you solve the problem.
While you use the problem-solving approach, you need to apply critical thinking at each stage. Critical
thinking is defined as purposeful mental activity that helps formulate or solve problems, make
decisions or fulfil a desire to understand.
Problem solving in programming is done through algorithms, which can be in the form of
pseudocodes or flow charts, as shown in the following figure:

Using Algorithms
An algorithm enables the developer to choose the right thought process to arrive at the best solution
for a problem.

An algorithm is a procedure for solving a problem using a sequence of


instructions.

NIIT Yuva Jyoti


5
Problem Solving The Algorithmic Way

What is an algorithm?
An algorithm is a finite set of clearly defined steps that describe how you want to solve a problem. It
converts input, information relating to the problem, into output which is the solution by following a
defined set of steps, as shown in the following figure:

A computer program is itself an algorithm. However, because it is written according to the syntax of a
specific programming language, you tend to focus on syntactic issues and lose the focus on the
algorithm. The problem-solving approach to programming requires you to design an algorithm that
adheres to the good characteristics of a program and then write the code from the algorithm.

Characteristics of an Algorithm
An algorithm allows you to think, analyse and design a solution before developing a program. An
algorithm is written in a spoken language and not in any programming language, such that even a
person who does not know programming can easily understand it. Writing an algorithm in the initial
stages of programming helps eliminate errors of problem-solving logic so that when a developer
starts programming, he/she needs to consider only the language-specific issues.
Hence, the main characteristics of an algorithm are:
It should have a definite starting point.
The steps should be crisp and clear.
It should be accurate.
It should arrive at the correct solution.
It should not get stuck in an infinite loop.
It should end at a definite point.

NIIT Yuva Jyoti


6
Problem Solving The Algorithmic Way

The following figure represents the characteristics of an algorithm with the help of the previously
discussed example of booking a hotel:

Steps for Creating an Algorithm


The key to solving a problem is to start with a plan. That plan is called an algorithm and consists of
seven major steps. It is the responsibility of the software development team to identify the problem
and confirm it with the customer. The next step is to analyse the problem to find out the starting and
ending points for solving the problem.
After the analysis step, an action plan highlighting the major steps involved in the process needs to
be developed. The algorithm then needs to be refined to arrive at the best possible solution. The final
step is to review the algorithm and implement the solution.

NIIT Yuva Jyoti


7
Problem Solving The Algorithmic Way

The steps involved for creating an algorithm are shown in the following figure:

Consider the example of reaching college by 9 a.m., which was discussed previously. You can take
one of the two modes of transportthe city bus or the metro. The steps for writing an algorithm for this
scenario would be as follows:
1. Identify the problem.
You need to reach the college by 9 a.m.
2. Analyse the problem.
The bus stop is near your house, but the bus may take more time depending on the
traffic. If you take the bus, you may reach the college in 25 minutes or you might get
stuck in traffic and take more time to reach the college.
On the other hand, the metro station is little far from your house. But, once you reach
the metro station, you will reach the college in 15 minutes.
3. Identify the solutions.
Taking the bus is an indefinite solution, and you may or may not reach the college on
time.
Taking the metro will definitely make you reach college on time.
4. Evaluate the solutions.
If you leave before 8:30, then you can take the bus, as the bus stand is closer to your
home.
If you leave at 8:30, you can take either the bus or the metro.
If you leave after 8:30, then you should take the metro, as the metro would take lesser
travelling time than the bus.
5. Select the best solution.
Since its 8:25, you should take the bus, as the bus stop is closer to your home.

NIIT Yuva Jyoti


8
Problem Solving The Algorithmic Way

6. Develop an action plan.


a. Reach the bus stop at 8:30.
b. When the bus comes, take the bus.
c. The bus reaches the college by 8:50.
7. Implement the solution.

Structure of an Algorithm
Every algorithm should have clearly defined sections written in an order, as shown in the following
figure:

Self-Read

To read more about algorithms, visit the following link:


http://faculty.ccri.edu/mkelly/COMI1150/ProblemSolvingAndProgramDesign.pdf

An algorithm for the preceding scenario, where you need to book a hotel for the team members of
your organisation, would be as follows:

NIIT Yuva Jyoti


9
Problem Solving The Algorithmic Way

The steps to write an algorithm are:


Step 1: Start.
Step 2: Declare variables with their data type.
Step 3: Input values.
Step 4: Do processing.
Step 5: Display output.
Step 6: Stop.

Examples for Writing Algorithms


Example 1: Write an algorithm to find product of two numbers.
Solution
Step 1: Start.
Step 2: Declare the variables: number1 as int, number2 as int, and product as int.
Step 3: Read values number1 and number2.
Step 4: Multiply number1 and number2 and assign the result to product.
product = number1 * number2
Step 5: Display the product.
Step 6: Stop

Example 2: Write an algorithm to calculate the tax amount for the employees of your organisation.
Solution
Step 1: Start.
Step 2: Declare the variables: salary as double and tax as float.
Step 3: Read the value of salary.
Step 4: If salary < 1,00,000, then
tax = 0
otherwise
if salary > 1,00,000 and salary < 1,50,000 then
tax = salary * 0.05
otherwise
tax = salary * 0.30
Step 5: Display tax.
Step 6: Stop.

NIIT Yuva Jyoti


10
Problem Solving The Algorithmic Way

Example 3: Your supervisor approaches you to determine the bonus for every employee in your
department. An employee is entitled for a bonus if he/she has taken less than two leaves in a quarter.
You need to design an algorithm to calculate the bonus.

Solution
Step 1: Start.
Step 2: Declare the variables: employee_name as an array of characters, leaves_in_quarter as float
and BONUS as double.
Step 3: Read the values of employee_name and leaves_in_quarter.
Step 4: If (leaves_in_quarter < 2), then
BONUS = 10% of salary
otherwise
BONUS = 0
Step 5: Display BONUS for, employee_name is Rs. BONUS.
Step 6: Stop.
Typically, while writing algorithms, developers tend to make mistakes.
Consider the example in which you need to add two numbers that would be entered by the user. The
following example depicts some mistakes while writing an algorithm:
Step 1: Start.
Step 2: Find sum.
Step 3: Add num1 and num2 and assign the result to sum.
Step 4: Read values num1 and num2.
Step 5: Display sum.
Step 6: Stop.
To correct the preceding errors, the correct steps for writing the algorithm would be as follows:
Step 1: Start.
Step 2: Declare the variables: num1, num2 and sum.
Step 3: Read values num1 and num2.
Step 4: Add num1 and num2 and assign the result to sum.
sum = num1 + num2
Step 5: Display the sum.
Step 6: Stop.

NIIT Yuva Jyoti


11
Problem Solving The Algorithmic Way

Forms of Algorithms
There are two forms of AlgorithmPseudocode and Flow chart. The following figure depicts the
characteristics of the two forms of algorithms:

Types of Algorithms
There are many different ways of classifying algorithms. It enables you to understand how an
algorithm works. It also helps in choosing the right technique to analyse the algorithm to solve a
problem. It is important for a developer to appreciate the right kind of algorithm based on the scope of
the problem statement.
An algorithm may be classified as:
Deterministic vs. Randomized
Deterministic algorithms give the same result every time for the same input and same
steps. Randomised algorithms, on the other hand, give a different result each time for the
same input.
Offline vs. Online
Online algorithms are computed based on the input given online (by the user), whereas
input is known beforehand in Offline algorithms.
Exact vs. Approximate
Exact algorithms are used to arrive at the exact solution, whereas approximate algorithms
aim at arriving at a solution that is proximity of the exact goal.
Simple recursive algorithm
Recursive algorithm breaks a problem into smaller parts until you arrive at a simpler
sub-problem that can be easily solved.
Backtracking algorithm
In case of backtracking algorithm, each time a solution is generated, it is tested if all
conditions are satisfied to continue further, else you need to back track and go on a
different path.
Divide-and-conquer algorithm

NIIT Yuva Jyoti


12
Problem Solving The Algorithmic Way

In case of divide-and-conquer algorithm, the problem is divided by a constant factor into


smaller sub-problems. These sub-problems are solved and their individual results lead to
the overall solution of the original problem.
Dynamic programming algorithm
In case of dynamic programming algorithm, the result of each sub-problem is remembered
and that value is used whenever needed instead of computing it again.
Greedy algorithm
A greedy algorithm makes a locally optimum solution such that it leads to a globally optimal
solution.

Self-Read

To read more about types of algorithms, please visit the following website:
http://www.mi.fu-berlin.de/wiki/pub/ABI/DiscretMathWS10/runtime.pdf

Check Your Understanding


Question 1: What is an algorithm?
Question 2: What are the two forms of algorithms?
Question 3: What is the correct sequence of steps of writing an algorithm?
a. Select the solution Analyse the problem Develop the plan Implement the solution
b. Develop the plan Analyse the problem Select the solution Implement the solution
c. Analyse the problem Select the solution Develop the plan Implement the solution
d. Develop the plan Analyse the problem Select the solution Implement the solution
Question 4: Every algorithm needs to have a header and a terminator.
State whether the preceding statement is true or false.
Question 5: Correct the following algorithm to find the average of any three numbers.
Step 1: Start.
Step 2: Find average.
Step 3: Add num1, num2 and num3.
Step 4: Read the values num1, num2 and num3.
Step 5: average = sum/3
Step 6: sum = num1+num2+num3
Step 7: Display the average.
Step 8: Stop.

NIIT Yuva Jyoti


13
Problem Solving The Algorithmic Way

Question 6: Which of the following is a characteristic of a good program?


a. It should be a single composite unit.
b. It should be complex.
c. It should be easy to maintain.
d. It should be unique and decomposable.
Question 7: Your organisation is conducting skill-level exams for the junior developers to be
promoted to the senior level. Ten members of your team are taking this exam. To clear the exam, the
team member needs to be employed with the organisation for a period of minimum two years and
secure more than seventy percent in the test. Write an algorithm to check the eligibility of the member
and display the result.
Question 8: Your supervisor has approached you to determine the increment for every employee in
your department. An employee gets an increment if he/she has cleared proficiency test in Java, C++,
and Oracle. You need to design an algorithm to calculate the increment based on the following
criteria:
If the employee has cleared all three language tests, he/she gets an increment of 10%.
If the employee has cleared two of the three language tests, he/she gets an increment of 5%.
If the employee has cleared only one language test, he/she gets no increment.
Question 9: You are responsible for computing the salary of the employees in your organisation. The
salary is calculated based on the per-hour rate and the number of hours worked. Write an algorithm
to calculate the salary of the employees.
Question 10: In the following figure, what is missing at the step 3 of the problem-solving approach?

a. Write the code.


b. Develop the solution in the form of an algorithm.
c. Define the problem.
d. Validate the solution developed.

NIIT Yuva Jyoti


14
Problem Solving The Algorithmic Way

Summary
In this session, you learned:
Program design includes the steps a programmer should take before he/she starts coding
the program in a specific language.
There are various disadvantages of coding straightaway for a problem.
Your customers requirement is the problem statement, and your responsibility as a
developer is to give a solution to the problem by writing a program.
Problem solving in programming is done through algorithms.
An algorithm is a procedure for solving a problem using a sequence of instructions.
Writing an algorithm in the initial stages of programming helps eliminate errors of
problem-solving logic so that when a developer starts programming, he/she needs to
consider only the language-specific issues.
The various steps for writing an algorithm are:
Identify the problem.
Analyse the problem.
Identify solutions.
Evaluate solutions.
Select the best solution.
Develop an action plan.
Implement the solution.
There are two forms of AlgorithmPseudocode and Flow chart.
Pseudocode literally means fake code as it is not a programming code. It only specifies the
steps to perform a task.
Flow charts represent the steps of problem solving using symbols and texts.

NIIT Yuva Jyoti


15
Problem Solving The Algorithmic Way

Appendix: Solutions to Check Your Understanding


Question 1:
An algorithm is a finite set of clearly defined steps that describe how you want to solve a problem. It
has a definite set of inputs and a predictable and known set of result, which is the solution to the
problem.

Question 2:
The two forms of Algorithm are Pseudocode and Flow chart.
Question 3:
The correct sequence of steps of writing an algorithm is:
c. Analyse the problem Select the solution Develop the plan Implement the solution
Question 4:
True. Every algorithm needs to have a header and a terminator.
Question 5:
The correct algorithm to find the average of any three numbers is:
Step 1: Start.
Step 2: Declare the variables: num1 as int, num2 as int, num3 as int, sum as int and average as
float.
Step 3: Read the values num1, num2 and num3.
Step 4: Add num1, num2 and num3 and assign to sum.
sum = num1 + num2 + num3
Step 5: Divide the sum by 3 and assign to average.
average = sum / 3
Step 6: Display the average.
Step 7: Stop.
Question 6: A good program should be easy to maintain.
Question 7:
The algorithm for checking the eligibility of the member for promotion and displaying his/her result is
as follows:
Step 1: Start.
Step 2: Declare the variables: employee_name, no_of_years and test_percentage.
Step 3: Read employee_name, no_of_years, and test_percentage.
Step 4: If (no_of_years < 2), then
Display You are not eligible for the test
otherwise
if (test_percentage >= 70)
display You are promoted!

NIIT Yuva Jyoti


16
Problem Solving The Algorithmic Way

otherwise
display You are not promoted. You need to work hard!
Step 5: Stop.
Question 8:
The algorithm to calculate the increment is as follows:
Step 1: Start.
Step 2: Declare the variables: employee_name, no_of_tests_cleared and increment.
Step 3: Read salary, employee_name and no_of_tests_cleared.
Step 4: If (no_of_tests_cleared = 3), then
increment = 10% of salary
otherwise
if (no_of_tests_cleared = 2)
increment = 5% of salary
otherwise
increment = 0
Step 5: Stop.
Question 9:
The algorithm to calculate the salary of the employees is as follows:
Step 1: Start.
Step 2: Declare the variables: rate, hours and salary.
Step 3: Read the values, hours and rate.
Step 4: Multiply hours with rate to calculate salary.
salary = hours * rate
Step 5: Display the salary.
Step 6: Stop.
Question 10: The missing step is to develop the solution into an algorithm.

NIIT Yuva Jyoti


17

You might also like