Topic 2 - Algorithmic Problem Solving PDF
Topic 2 - Algorithmic Problem Solving PDF
PROGRAMMING 1
LECTURE: 02 – ALGORITHMIC PROBLEM SOLVING
2
Learning Objectives:
Problem Solving
• Programming is a process of problem solving
In 1994, reports
• An algorithm specifies a series of steps that perform a
31%
particular cancelled
computation or task. Algorithms were
originally
born
53% as
morepart than
of mathematics – the word
2x over budget
“algorithm” comes from the Arabic writer Muḥammad
ibn Mūsā al-Khwārizmī
Algorithm:
Step-by-step problem-solving process
Solution achieved in finite amount of time
4
Design
• The process of designing the steps which are
needed to solve the required problem.
▫ Produce an algorithm by writing a pseudo code or a flow
chart.
• 2 types of design:
▫ Structured analysis and design
▫ Object oriented analysis and design
10
• Top-down design
• Programmer begins with a general design and move towards
detail design.
11
Pseudocode
• Step-by-step instructions that the computer must follow to
transform the problem’s input into its output.
Pseudocode
• A method of designing a
program using normal
human-language statements
to describe the logic and
processing flow.
14
Pseudocode
• A method of designing a
program using normal
human-language statements
to describe the logic and
processing flow.
15
Pseudocode
• Uses short English statements to show
the steps the computer must take to
accomplish the program’s goal.
• Consists of natural language-like
statements that precisely describe the
steps of an algorithm or program
• Statements describe actions
• Focuses on the logic of the algorithm
or program
16
Pseudocode
• Avoids language-specific elements
• Written at a level so that the desired
programming code can be generated almost
automatically from each statement
• Steps are numbered. Subordinate numbers
and/or indentation are used for dependent
statements in selection and repetition
structures.
17
Pseudocode
• Avoids language-specific elements
• Written at a level so that the desired
programming code can be generated almost
automatically from each statement
• Steps are numbered. Subordinate numbers
and/or indentation are used for dependent
statements in selection and repetition
structures.
18
Pseudocode
Several keywords are often used to indicate
common input, output, and processing
operations.
Pseudocode
• Sequence
▫ Sequential control is indicated by writing one action after
another, each action on a line by itself, and all actions
aligned with the same indent. The actions are performed in
the sequence (top to bottom) that they are written.
▫ Example
1. READ height of rectangle
2. READ width of rectangle
3. COMPUTE area as height times width
20
Pseudocode
• Selection
▫ Single-Selection IF
1. IF condition THEN (IF condition is true, then
do subordinate statement 1, etc. If condition is
false, then skip statements)
1.1 statement 1
1.2 etc.
21
Pseudocode
▫ Double-Selection IF
• 2. IF condition THEN (IF condition is true, then do
subordinate statement 1, etc. If condition is false, then
skip statements and execute statements under ELSE)
2.1 statement 1
2.2 etc.
• 3. ELSE (else if condition is not true, then do
subordinate statement 2, etc.)
3.1 statement 2
3.2 statement 3
22
Pseudocode
• 4. SWITCH expression TO
4.1 case 1: action1
4.2 case 2: action2
4.3 etc.
4.4 default: actionx
23
Pseudocode
• Repetition
• 5. WHILE condition (while condition is true,
then do subordinate statements)
5.1 statement 1
5.2 etc.
24
Pseudocode
• DO – WHILE structure (like WHILE, but tests
condition at the end of the loop. Thus, statements
in the structure will always be executed at least
once.)
6. DO
6.1 statement 1
6.2 etc.
7. WHILE condition
25
Pseudocode
Pseudocode
Pseudocode
27
Express an algorithm to get two numbers from the user (dividend and divisor),
testing to make sure that the divisor number is not zero, and displaying their
quotient using pseudocode
1. Start
2. Declare variables: dividend, divisor, quotient
3. Prompt user to enter dividend and divisor
4. Get dividend and divisor
5. IF divisor is equal to zero, THEN
5.1 DO
5.1.1 Display error message, “divisor must be non-zero”
5.1.2 Prompt user to enter divisor
5.1.3 Get divisor
5.2 WHILE divisor is equal to zero
6. ENDIF
7. Display dividend and divisor
8. Calculate quotient as dividend/divisor
9. Display quotient
10. End
28
Flowchart
• A chart that graphically
presents the detailed series
of steps needed to solve
programming problems.
29
Flowchart
30
Flowchart
Example:
31
Flowchart
Decision Flowchart:
32
Flowchart
Looping Flowchart:
33
Flowchart
35
Pseudocode
Program : Determine the average grade of a class
1. Start
2. Initialize counter and sum to 0
3. Do While there are more data
3.1 Get the next grade
3.2 Add the grade to the sum
3.3 Increment the counter
4. Loop
5. Compute average = sum / counter
6. Display average
7. End
36
Implementation
• The process of writing the code that translates
the design into a computer program using a
programming language.
• Different languages have different syntax.
• A language syntax’s is the set of grammar and
rules that specifies how to write instructions
for an algorithm.
38
Testing
• The process of running the program and checking for
errors. This is to ensure that the program works like it is
supposed to.
• Types of errors:
▫ Syntax error
Code violates the syntax, or grammar, of the programming language.
▫ Run-time error
Error that occurs while program is running.
▫ Logic error
A logic error (or logical error) is a ‘bug’ or mistake in a program’s
source code that results in incorrect or unexpected behaviour.
• Debugging
▫ Process of locating and correcting syntax and logic errors in a
program.
40
Edit-Compile-Debug-Loop
Begin
Edit
Program
Compile
Program
Compiler True
Errors?
False
Test
Program
Run-time True
Errors?
False
End
41
Step 1: Analysis
Step 2: Design
1. Begin
2. Input curYear
3. Input yearBorn
4. age = curYear – yearBorn
5. Output age
6. End
46
Step 3: Coding
#include <iostream>
using namespace std;
int main()
{
int yearBorn;
int curYear;
int age;
cout << "Please enter the current year: ";
cin >> curYear;
cout << "Please enter the year you were born: ";
cin >> yearBorn;
age = curYear - yearBorn;
cout << "Your age is " << age;
cout << endl;
return 0;
}
47
Compilation Process
hello.obj hello
hello.o hello.exe
Source Object Executable
Code Compiler Code Linker Program
hello.cp
p Library
hello.C
A library is a collection of code that has
been programmed and translated by
other programmers
49
Maintenance
Codes in C++
• /* This is a program that computes the sum of two integer numbers */
• #include <iostream.h> //preprocessor directive
• main()
• { int x, y, sum; //declaration of variables
• cout<<”Enter first number:”; //user promt
• cin>>x; //input from console
• cout<<”Enter second number:”; //user prompt
• cin>>y; //input from console
• sum=x+y; //add x and y
• cout<<endl <<”Sum= “<<sum; //display output to console
return 0; //return a value to the environment and program
//ended successfully
• }
52
Example 3 - Rectangle
Example 3(Continued)
• Analysis:
• Input:
▫ Get length of the rectangle
▫ Get width of the rectangle
• Process:
▫ Find the perimeter using the following equation:
perimeter = 2 * (length + width)
▫ Find the area using the following equation:
area = length * width
• Output:
▫ Display perimeter, area
Example 4
• Every salesperson has a base salary
• Salesperson receives $10 bonus at the end of the month for each
year worked if he or she has been with the store for five or less
years
• The bonus is $20 for each year that he or she has worked there if
over 5 years
• Additional bonuses are as follows:
▫ If total sales for the month are $5,000-$10,000, he or she receives a
3% commission on the sale
▫ If total sales for the month are at least $10,000, he or she receives a
6% commission on the sale
55
Example 4 (continued)
1. Input: base salary, no of service years, total
sale
2. Process:
• Calculate bonus
• Calculate additional bonus
3. Output: pay check
56
Example 4 (continued)
• Calculate bonus using the following formula:
if (noOfServiceYears is less than or equal to five)
bonus = 10 * noOfServiceYears
otherwise
bonus = 20 * noOfServiceYears
Example 4 (continued)
Example 5
• 10 students in a class
• Each student has taken five tests and each test is
worth 100 points.
• Design an algorithm to calculate the grade for
each student as well as the class average.
▫ Design an algorithm to find the average test score.
▫ Design an algorithm to determine the grade.
• Data consists of students’ names and their test
scores.
59
Example 5 (continued)
Example 5 (continued)
• Algorithm to determine the grade.
if average is greater than or equal to 90
grade = A
otherwise
if average is greater than or equal to 80 and less than 90
grade = B
otherwise
if average is greater than or equal to 70 and less than 80
grade = C
otherwise
if average is greater than or equal to 60 and less than 70
grade = D
otherwise
grade = F
61
Example 5 (continued)
• Main algorithm is as follows:
1. totalAverage = 0;
2. Repeat the following steps for each student in the class.
a. Get student’s name.
b. Use the algorithm as discussed above to find the average test score.
c. Use the algorithm as discussed above to find the grade
d. Update totalAverage by adding current student’s average test score.
3. Determine the class average as follows:
classAverage = totalAverage / 10
62