Lesson 2 The Art of Problem Solving
Lesson 2 The Art of Problem Solving
Programming
Lesson 2:
The art of problem solving
Lesson objectives
Upon successful completion of this lesson, candidates will be able to demonstrate their competence
in, and their ability to:
A vocabulary and set of grammatical rules (syntax) for instructing a computer to perform specific tasks.
The term programming language usually refers to high-level languages, such as BASIC, C, C++,
COBOL, FORTRAN, Ada, and Pascal.
You eventually need to convert your program into machine language so that the computer can
understand it.
There are two ways to do this: – Compile the program – Interpret the program
Compile is to transform a program written in a high-level programming
language from source code into object code. This can be done by using a
tool called compiler.
A compiler reads the whole source code and translates it into a complete
machine code program to perform the required tasks which is output as a
new file.
This source code is written in a programming language like C++, JAVA, Perl etc.
Computer programmers write, test, and maintain programs or software that tell the
computer what to do.
What Skills are Required to Become a Programmer?
The first generation languages, or 1GL, are low-level languages that are machine language.
The second generation languages, or 2GL, are also low-level languages that generally consist of
assembly languages.
The fourth generation languages, or 4GL, are languages that consist of statements similar to
statements in a human language. Fourth generation languages are commonly used in database
programming and scripts.
The fifth generation languages, or 5GL, are programming languages that contain visual tools to help
develop a program. A good example of a fifth generation language is Visual Basic.
1. First-generation: Machine language
2. Second-generation: Assembly language
3. Third-generation: High-level language
4. Fourth-generation
5. (Fifth-generation)
1GL: Machine language
Windows Application
– C, C++, Java, Visual Basic, C#
Web Application
– Server Side
• PHP, JSP (Java), ASP.NET (Visual Basic, C#), …
– Client Side
• JaveScript, VBScript
4GL / 5GL
3GL offered greater power to the programmer, while 4GL open up the
development environment to a wider population. (Applications Development
Without Programmers)
Interpreter:
– translate and run the source code one line at a time. Easy to write and
easy to find the errors in the program, but running very slow.
• JavaScript, VBScript, PHP, …
Compiler:
– translates the source code once and for all, producing a complete
machine language program. Very fast, but when the program fails, difficult
to show the programmer where are the errors.
– C, C++, Java, C#, and so on.
Implement a Language
Generally, the action of any translating program can be divided into three
phases
1. Scanning
2. Parsing
3. Code generation
Implement a Language - Scanning
sum +
a b
TYPES OF PROGRAMMING LANGUAGES
Types of Programming Language
Low-level languages are closer to the language used by a computer, while high-
level languages are closer to human languages.
Machine Language
A program written in assembly language consists of a series of instructions mnemonics that correspond to
a stream of executable instructions, when translated by an assembler, that can be loaded into memory
and executed.
Assembly languages use keywords and symbols, much like English, to form a programming language but
at the same time introduce a new problem.
The problem is that the computer doesn't understand the assembly code, so we need a way to convert it
to machine code, which the computer does understand.
Assembly language programs are translated into machine language by a program called an assembler.
Example:
• Machine language : 10110000 01100001
• Assembly language : mov a1, #061h
• Meaning: Move the hexadecimal value 61 (97 decimal) into the processor register named "a1".
High Level Language
High-level languages allow us to write computer code using instructions resembling everyday spoken
language (for example: print, if, while) which are then translated into machine language to be executed.
Programs written in a high-level language need to be translated into machine language before they can
be executed.
Some programming languages use a compiler to perform this translation and others use an interpreter.
Examples of High-level Language:
• ADA
• C
• C++
• JAVA
• BASIC
• COBOL
• PASCAL
• PHYTON
BASIC
Developed in the 1950s for teaching University students to program and provided with every self-
respecting personal computer in the 1980s,
BASIC has been the first programming language for many programmers.
BASIC Example:
PRINT "Hello world!“
Visual Basic
Based on the BASIC language, Visual Basic was one of the first products to
provide a graphical programming environment and a paint metaphor for
developing user interfaces.
C
Developed by Dennis Ritchie at Bell Labs in the mid 1970s.
C is much closer to assembly language than are most other high-level languages.
The first major program written in C was the UNIX operating system.
The low-level nature of C, however, can make the language difficult to use for some
types of applications.
Example:
#include “stdio.h”
int main(void) {
printf("hello, world\n");
return 0;
}
C++
A high-level programming language developed by Bjarne Stroustrup at Bell Labs.
C++ is one of the most popular programming language for graphical applications, such as
those that run in Windows and Macintosh environments.
C++ Example:
#include <stdlib.h>
int main() {
std::cout << "Hello World!" << std::endl;
return 0;
}
Pascal
A high-level programming language developed by Niklaus Wirth in the late 1960s.
The language is named after Blaise Pascal, a seventeenth-century French mathematician who
constructed one of the first mechanical adding machines.
Pascal Example:
Program HelloWorld(output);
begin
writeLn('Hello, World!')
end.
Java
A high-level programming language developed by Sun Microsystems.
Java was originally called OAK, and was designed for handheld devices and set-top boxes.
Oak was unsuccessful so in 1995 Sun changed the name to Java and modified the language to
take advantage of the burgeoning World Wide Web.
Java is a general purpose programming language with a number of features that make the
language well suited for use on the World Wide Web.
Example:
/* * Outputs "Hello, World!" and then exits */
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
THE ART OF PROBLEM SOLVING
Preparing to Program
When creating a program you should also follow a similar sequence of steps:
1. Determine the objective(s) of the program.
2. Determine the methods you want to use in writing the program.
3. Create the program to solve the problem.
4. Run the program to see the results.
Introduction to problem solving techniques
Intelligence is one of the key characteristics which differentiate a human being from other living
creatures on the earth. Basic intelligence covers day to day problem solving and making strategies
to handle different situations which keep arising in day to day life.
One person goes to the Bank to withdraw money. After knowing the balance in his account,
he/she decides to withdraw the entire amount from his account but he/she has to leave
minimum balance in his account. Here deciding about how much amount he/she may with draw
from the account is one of the examples of the basic intelligence.
During the process of solving any problem, one tries to find the necessary steps to be taken in a
sequence.
Problem solving
Can you think of a day in your life which goes without problem solving? Answer to this question is
of course, No.
In our life we are bound to solve problems. In our day to day activity such as purchasing
something from a general store and making payments, depositing fee in school, or withdrawing
money from bank account. All these activities involve some kind of problem solving.
It can be said that whatever activity a human being or machine do for achieving a specified
objective comes under problem solving.
PROBLEM SOLVING IN PROGRAMMING
2. Implementation phase
implement the program in some programming language
Algorithms
All computing problems can be solved by executing a series of actions in a specific order
An algorithm is a procedure in terms of actions to be executed and the order in which these
actions are to be executed
Program control specifies the order in which statements are to be executed
Properties of algorithm
Donald Ervin Knuth has given a list of five properties for an algorithm:
1) Finiteness: An algorithm must always terminate after a finite number of steps. It means after
every step one reach closer to solution of the problem and after a finite number of steps
algorithm reaches to an end point.
2) Definiteness: Each step of an algorithm must be precisely defined. It is done by well thought
actions to be performed at each step of the algorithm. Also the actions are defined
unambiguously for each activity in the algorithm.
3) Input: Any operation you perform need some beginning value/quantities associated with
different activities in the operation. So the value/quantities are given to the algorithm before it
begins.
Properties of algorithm (Cont’d)
4. Output: One always expects output/result (expected value/quantities) in terms of output from
an algorithm. The result may be obtained at different stages of the algorithm. If some result is
from the intermediate stage of the operation then it is known as intermediate result and result
obtained at the end of algorithm is known as end result. The output is expected
value/quantities always have a specified relation to the inputs
5. Effectiveness: Algorithms to be developed/written using basic operations. Actually operations
should be basic, so that even they can in principle be done exactly and in a finite amount of
time by a person, by using paper and pencil only.
Type of Algorithms
The algorithm classification falls into the three types of control structures. They are:
1. Sequence
2. Branching (Selection)
3. Loop (Repetition)
These three control structures are sufficient for all purposes.
The sequence is exemplified by sequence of statements place one after the other – the one
above or before another gets executed first.
Previous examples in problem 1 and 3 shows how a sequence of actions can be performed to
solve a particular problem
Problem 1: Write an algorithm to calculate the perimeter and area of rectangle. Given its length
and width.
Step 1: Start
Step 2: Read length of the rectangle.
Step 3: Read width of the rectangle.
Step 4: Calculate perimeter of the rectangle using the formula perimeter = 2* (length + width)
Step 5: Calculate area of the rectangle using the formula area = length *width.
Step 6: Print perimeter.
Step 7: Print area.
Step 8: Stop.
Problem 2: Write an algorithm to determine a student’s final grade and indicate whether it is
passing or failing. The final grade is calculated as the average of four marks.
Step 1: Start
Step 2: Read\input the first num1.
Step 3: Read\input the second num2.
Step 4: Sum num1+num2 // calculation of sum
Step 5: Print Sum
Step 6: End
Branching / Selection
The branch refers to a binary decision based on some condition. If the condition is true, one of
the two branches is explored; if the condition is false, the other alternative is taken.
Step 1: Start
Step 2: Read/input A and B
Step 3: If A greater than B then C=A
Step 4: if B greater than A then C=B
Step 5: Print C
Step 6: End
Problem 5: A algorithm to find the largest value of any three numbers.
Step 1: Start
Step 2: Read/input A,B and C
Step 3: If (A>=B) and (A>=C) then Max=A
Step 4: If (B>=A) and (B>=C) then Max=B
Step 5:If (C>=A) and (C>=B) then Max=C
Step 6: Print Max
Step 7: End
Looping
The loop allows a statement or a sequence of statements to be repeatedly executed based on some
loop condition. It is represented by the ‘while’ and ‘for’ constructs in most programming languages, for
unbounded loops and bounded loops respectively.
Unbounded loops refer to those whose number of iterations depends on the eventuality that the
termination condition is satisfied; bounded loops refer to those whose number of iterations is known
before-hand.
In the flowcharts, a back arrow hints the presence of a loop.
A trip around the loop is known as iteration.
You must ensure that the condition for the termination of the looping must be satisfied after some
finite number of iterations, otherwise it ends up as an infinite loop, a common mistake made by
inexperienced programmers.
The loop is also known as the repetition structure.
Problem 6: An algorithm to calculate even numbers between 0 and 99
1. Start
2. I←0
3. Write I in standard output
4. I ← I+2
5. If (I <=98) then go to line 3
6. End
Problem 7: Design an algorithm which gets a natural value, n as its input and calculates odd
numbers equal or less than n. Then write them in the standard output
1. Start
2. Read n
3. I←1
4. Write I
5. I←I+2
6. If ( I <= n) then go to line 4
7. End
Problem 8: Design an algorithm which generates even numbers between 1000 and 2000 and then
prints them in the standard output. It should also print total sum
1. Start
2. I ← 1000 and S ← 0
3. Write I
4. S←S+I
5. I←I+2
6. If (I <= 2000) then go to line 3
else go to line 7
7. Write S
8. End
Pseudo code
A general algorithm can be refined successively to get step by step detailed algorithm that is
very close to a computer language known as pseudo code.
Pseudo code is an artificial and informal language that helps programmers develop the actual
code.
It is usually referred to as fake-code.
As the name suggests, pseudo code — it cannot be executed on a real computer, but it
models and resembles real programming code, and is written at roughly the same level of
detail.
Problem 9: Write a pseudo-code to describe an algorithm which will accept two numbers from
the keyboard and calculate the sum and product displaying the answer on the monitor screen.
1. Start
2. Use variables sum, product, number1, number2 of type int
3. display “Input two numbers”
4. accept number1, number2
5. sum = number1 + number2
6. print “The sum is “, sum
7. product = number1 * number2
8. print “The Product is “, product
9. End program
Flow chart
1. All boxes of the flowchart are connected with Arrows. (Not lines)
2. Flowchart symbols have an entry point on the top of the symbol with no other entry points. The exit point for
all flowchart symbols is on the bottom except for the Decision symbol.
3. The Decision symbol has two exit points; these can be on the sides or the bottom and one side.
4. Generally a flowchart will flow from top to bottom. However, an upward flow can be shown as long as it does
not exceed 3 symbols.
5. Connectors are used to connect breaks in the flowchart. Examples are:
From one page to another page.
From the bottom of the page to the top of the same page.
An upward flow of more then 3 symbols
6. Subroutines and Interrupt programs have their own and independent flowcharts.
7. All flow charts start with a Terminal or Predefined Process (for interrupt programs or subroutines) symbol.
8. All flowcharts end with a terminal or a contentious loop.
Problem 10 : a flowchart to input two numbers from user and display the largest of two numbers
Problem 11 : a flowchart to input hours worked and pay rate and display gross pay
Problem 12 : Find the area of a circle of radius r.
Problem 13 : Convert temperature Fahrenheit to Celsius
Problem 14 : Flowchart for the calculate the average from 25 exam scores.
Practice Exercise
1. What is an algorithm?
2. Explain need of an algorithm?
3. Write an algorithm to find average age of a group of 10 players?
4. Write an algorithm to find factorial of N?
5. Explain steps involve in drawing of a flowchart.
6. Explain uses of Flowchart.
7. Draw a flowchart to find the sum of first 100 natural numbers.
8. Draw a flowchart to find the largest of three numbers x, y and z.
9. Draw flowchart for the problem of determining prime number?
The End!!!
Compiled by F. Zinyowera