SlideShare a Scribd company logo
1 of 28
http://www.comp.nus.edu.sg/~cs1010/
UNIT 2
Algorithmic Problem Solving
Unit 2: Algorithmic Problem Solving
1. Problem Solving Process
2. Algorithm
3. Control Structures
4. Examples of Pseudocodes
5. Euclid’s Algorithm
CS1010 (AY2014/5 Semester 1) Unit2 - 2© NUS
Problem Solving Process
CS1010 (AY2014/5 Semester 1) Unit2 - 3© NUS
Analysis
Design
Implementation
Testing
Iterative
process
Problem Solving Process
CS1010 (AY2014/5 Semester 1) Unit2 - 4© NUS
Analysis
Design
Implementation
Testing
Iterative
process
Problem Solving Process
CS1010 (AY2014/5 Semester 1) Unit2 - 5© NUS
Analysis
Design
Implementation
Testing
Iterative
process
Algorithmic
Determine
problem
features
Write
algorithm
Produce
code
Check for
correctness and
efficiency
What is an
algorithm?
Algorithm (1/3)
CS1010 (AY2014/5 Semester 1) Unit2 - 6
 An algorithm is a well-defined computational
procedure consisting of a set of instructions,
that takes some value or set of values as
input, and produces some value or set of
values as output.
© NUS
Input Algorithm Output
‘Algorithm’ stems from ‘Algoritmi’, the Latin form of al-
Khwārizmī, a Persian mathematician, astronomer and geographer.
Source: http://en.wikipedia.org/wiki/Algorithm
Algorithm (2/3)
CS1010 (AY2014/5 Semester 1) Unit2 - 7
 An algorithm has these properties:
© NUS
Exact Terminate
Effective General
Each step
must be exact.
(Or it will not be
precise.)
The
algorithm
must
terminate.
(Or no solution
will be obtained.)
The
algorithm
must be
effective.
(i.e. it must solve
the problem.)
The algorithm
must be
general.
(Within the
constraints of the
system/language.)
Algorithm (3/3)
CS1010 (AY2014/5 Semester 1) Unit2 - 8
 Ways of representing an algorithm:
© NUS
Flowchart Pseudocode
lynda.com
Algorithm: Example #1
CS1010 (AY2014/5 Semester 1) Unit2 - 9© NUS
Algorithm: Example #2 (1/2)
CS1010 (AY2014/5 Semester 1) Unit2 - 10© NUS
 Find maximum and average of a list of numbers:
Flowchart
start
sum  count  0
max  0
end of
input?
Enter num
increment count
sum  sum + num
Yes
No
num > max?
Yes
No
max  num
ave  sum/count
end
Terminator box
Process box
Decision box
print max, ave
Algorithm: Example #2 (2/2)
CS1010 (AY2014/5 Semester 1) Unit2 - 11© NUS
 Find maximum and average of a list of numbers:
sum  count  0 // sum = sum of numbers
// count = how many numbers are entered?
max  0 // max to hold the largest value eventually
for each num entered,
count  count + 1
sum  sum + num
if num > max
then max  num
ave  sum / count
print max, ave Are there any errors
in this algorithm?
The need to initialise variables.
The need to indent.
Pseudocode
Algorithm: Pseudocode
CS1010 (AY2014/5 Semester 1) Unit2 - 12© NUS
 We will write algorithms in pseudocode instead
of flowchart as the former is more succinct
 However, there are no standard rules on how
pseudocodes should look like
 General guidelines:
 Every step must be unambiguous, so that anybody is
able to hand trace the pseudocode and follow the
logic flow
 Use a combination of English (keep it succinct) and
commonly understood notations (such as  for
assignment in our previous example)
Control Structures (1/2)
CS1010 (AY2014/5 Semester 1) Unit2 - 13
 An algorithm is a set of instructions, which are
followed sequentially by default.
 However, sometimes we need to change the
default sequential flow.
 We study 3 control structures.
© NUS
Control Structures (2/2)
CS1010 (AY2014/5 Semester 1) Unit2 - 14© NUS
• DefaultSequence
• Also called
branchingSelection
• Also called
loopRepetition
True False
?
True
False ?
Data Representation
CS1010 (AY2014/5 Semester 1) Unit2 - 15
 Internal representation: bits (binary digits) 0 and 1
 1 byte = 8 bits
 In programming, we need variables to hold data. A
variable has an associated data type and occupies
memory space. In the following slides, variables are
shown as boxes.
 Some data types in C (list is not exhaustive)
 Integers: int, short, long (int is most common)
 Real numbers: float, double
 Characters: char
 Self-reading: Lesson 1.4 in reference book
© NUS
Control Structures: Sequence (1/2)
CS1010 (AY2014/5 Semester 1) Unit2 - 16
 Task: Compute the average of three integers
© NUS
Each box represents a variable.
Important concepts: Each variable has
a unique name and contains a value.
A possible algorithm:
enter values for num1, num2, num3
ave  ( num1 + num2 + num3 ) / 3
print ave
Variables used:
num1 num2 num3
ave
Another possible algorithm:
enter values for num1, num2, num3
total  ( num1 + num2 + num3 )
ave  total / 3
print ave
Variables used:
num1 num2 num3
ave
total
Control Structures: Sequence (2/2)
CS1010 (AY2014/5 Semester 1) Unit2 - 17
 Task: Compute the average of three integers
 How the program might look like
© NUS
// This program computes the average of 3 integers
#include <stdio.h>
int main(void) {
int num1, num2, num3;
float ave;
printf("Enter 3 integers: ");
scanf("%d %d %d", &num1, &num2, &num3);
ave = (num1 + num2 + num3) / 3.0;
printf("Average = %.2fn", ave);
return 0;
}
Unit2_prog1.c
Control Structures: Selection (1/3)
CS1010 (AY2014/5 Semester 1) Unit2 - 18
 Task: Arrange two integers in ascending order (sort)
© NUS
Algorithm A:
enter values for num1, num2
// Assign smaller number into final1,
// and larger number into final2
if (num1 < num2)
then final1  num1
final2  num2
else final1  num2
final2  num1
// Transfer values in final1, final2 back to num1, num2
num1  final1
num2  final2
// Display sorted integers
print num1, num2
Variables
used:
num1 num2
final1 final2
True False
?
Control Structures: Selection (2/3)
CS1010 (AY2014/5 Semester 1) Unit2 - 19
 Task: Arrange two integers in ascending order (sort)
© NUS
Algorithm B:
enter values for num1, num2
// Swap the values in the variables if necessary
if (num2 < num1)
then temp  num1
num1  num2
num2  temp
// Display sorted integers
print num1, num2
Variables
used:
num1 num2
temp
Compare Algorithm A with Algorithm B.
True False
?
Control Structures: Selection (3/3)
CS1010 (AY2014/5 Semester 1) Unit2 - 20
 How the program might look like for Algorithm B
© NUS
// This program arranges 2 integers in ascending order
#include <stdio.h>
int main(void) {
int num1, num2, temp;
printf("Enter 2 integers: ");
scanf("%d %d", &num1, &num2);
if (num2 < num1) {
temp = num1; num1 = num2; num2 = temp;
}
printf("Sorted: num1 = %d, num2 = %dn", num1, num2);
return 0;
}
Unit2_prog2.c
True False
?
Control Structures: Repetition (1/3)
CS1010 (AY2014/5 Semester 1) Unit2 - 21
 Task: Find sum of positive integers up to n (assume n>0)
© NUS
Algorithm:
enter value for n
// Initialise a counter count to 1, and ans to 0
count  1
ans  0
while (count <= n) do
ans  ans + count // add count to ans
count  count + 1 // increase count by 1
// Display answer
print ans
Variables
used:
n
count
ans
Initialisation is
very important!
True
False
?
Control Structures: Repetition (2/3)
CS1010 (AY2014/5 Semester 1) Unit2 - 22
 Important to trace pseudocode to check its correctness
© NUS
Algorithm:
enter value for n
count  1
ans  0
while (count <= n) do
ans  ans + count
count  count + 1
// Display answer
print ans
count ans(count <= n)?
Assume user enters 3 for n.
1 0
true 12
true 33
true 64
false
Output: 6
True
False
?
Control Structures: Repetition (3/3)
CS1010 (AY2014/5 Semester 1) Unit2 - 23
 How the program might look like
© NUS
// Computes sum of positive integers up to n
#include <stdio.h>
int main(void) {
int n; // upper limit
int count=1, ans=0; // initialisation
printf("Enter n: ");
scanf("%d", &n);
while (count <= n) {
ans += count;
count++;
}
printf("Sum = %dn", ans);
return 0;
}
Unit2_prog3.c
True
False
?
Euclid’s Algorithm (1/3)
CS1010 (AY2014/5 Semester 1) Unit2 - 24
 To compute the greatest common divisor
(GCD) of two integers
 First documented algorithm by Greek
mathematician Euclid in 300 B.C.
 Also known as Euclidean Algorithm
© NUS
1. Let A and B be integers with A > B ≥ 0.
2. If B = 0, then the GCD is A and algorithm ends.
3. Otherwise, find q and r such that
A = q.B + r where 0 ≤ r < B
4. Replace A by B, and B by r. Go to step 2.
Euclid’s Algorithm (2/3)
CS1010 (AY2014/5 Semester 1) Unit2 - 25© NUS
 q is not important;
r is the one that
matters.
 r could be obtained
by A modulo B (i.e.
remainder of A / B)
 Assumption on A > B
unnecessary
1. Let A and B be integers with A > B ≥ 0.
2. If B = 0, then the GCD is A and algorithm ends.
3. Otherwise, find q and r such that
A = q.B + r where 0 ≤ r < B
4. Replace A by B, and B by r. Go to step 2.
 We will rewrite the
algorithm
Euclid’s Algorithm (3/3)
CS1010 (AY2014/5 Semester 1) Unit2 - 26
 Euclid’s algorithm rewritten in modern form
© NUS
// Assume A and B are non-negative
// integers, but not both zeroes.
Algorithm GCD(A, B) {
while (B > 0) {
r  A modulo B
A  B
B  r
}
result is A
}
Let’s trace GCD(12, 42)
B(B > 0)? Ar
12
true
42
42 1212
true 12 66
true 6 00
false
Result: 6
Summary
CS1010 (AY2014/5 Semester 1) Unit2 - 27
 In this unit, you have learned about
 The process of algorithmic problem solving
 The properties of an algorithm
 The three control structures
 How to write algorithms in pseudocode
 Tracing algorithms to verify their correctness
© NUS
End of File
CS1010 (AY2014/5 Semester 1) Unit2 - 28© NUS

More Related Content

What's hot

Performance analysis and randamized agoritham
Performance analysis and randamized agorithamPerformance analysis and randamized agoritham
Performance analysis and randamized agorithamlilyMalar1
 
Complexity Analysis
Complexity Analysis Complexity Analysis
Complexity Analysis Shaista Qadir
 
02 order of growth
02 order of growth02 order of growth
02 order of growthHira Gul
 
Electrical Engineering Exam Help
Electrical Engineering Exam HelpElectrical Engineering Exam Help
Electrical Engineering Exam HelpLive Exam Helper
 
01. design & analysis of agorithm intro & complexity analysis
01. design & analysis of agorithm intro & complexity analysis01. design & analysis of agorithm intro & complexity analysis
01. design & analysis of agorithm intro & complexity analysisOnkar Nath Sharma
 
Analysis of algorithn class 2
Analysis of algorithn class 2Analysis of algorithn class 2
Analysis of algorithn class 2Kumar
 
Algorithm chapter 2
Algorithm chapter 2Algorithm chapter 2
Algorithm chapter 2chidabdu
 
Anlysis and design of algorithms part 1
Anlysis and design of algorithms part 1Anlysis and design of algorithms part 1
Anlysis and design of algorithms part 1Deepak John
 
CS8451 - Design and Analysis of Algorithms
CS8451 - Design and Analysis of AlgorithmsCS8451 - Design and Analysis of Algorithms
CS8451 - Design and Analysis of AlgorithmsKrishnan MuthuManickam
 
multi threaded and distributed algorithms
multi threaded and distributed algorithms multi threaded and distributed algorithms
multi threaded and distributed algorithms Dr Shashikant Athawale
 

What's hot (20)

Performance analysis and randamized agoritham
Performance analysis and randamized agorithamPerformance analysis and randamized agoritham
Performance analysis and randamized agoritham
 
Daa unit 2
Daa unit 2Daa unit 2
Daa unit 2
 
Lec7
Lec7Lec7
Lec7
 
MLE Example
MLE ExampleMLE Example
MLE Example
 
Complexity Analysis
Complexity Analysis Complexity Analysis
Complexity Analysis
 
02 order of growth
02 order of growth02 order of growth
02 order of growth
 
Electrical Engineering Exam Help
Electrical Engineering Exam HelpElectrical Engineering Exam Help
Electrical Engineering Exam Help
 
Data Structures- Hashing
Data Structures- Hashing Data Structures- Hashing
Data Structures- Hashing
 
01. design & analysis of agorithm intro & complexity analysis
01. design & analysis of agorithm intro & complexity analysis01. design & analysis of agorithm intro & complexity analysis
01. design & analysis of agorithm intro & complexity analysis
 
Unit 3
Unit 3Unit 3
Unit 3
 
Analysis of algorithn class 2
Analysis of algorithn class 2Analysis of algorithn class 2
Analysis of algorithn class 2
 
Algorithm chapter 2
Algorithm chapter 2Algorithm chapter 2
Algorithm chapter 2
 
Anlysis and design of algorithms part 1
Anlysis and design of algorithms part 1Anlysis and design of algorithms part 1
Anlysis and design of algorithms part 1
 
3 analysis.gtm
3 analysis.gtm3 analysis.gtm
3 analysis.gtm
 
CS8451 - Design and Analysis of Algorithms
CS8451 - Design and Analysis of AlgorithmsCS8451 - Design and Analysis of Algorithms
CS8451 - Design and Analysis of Algorithms
 
multi threaded and distributed algorithms
multi threaded and distributed algorithms multi threaded and distributed algorithms
multi threaded and distributed algorithms
 
algorithm Unit 2
algorithm Unit 2 algorithm Unit 2
algorithm Unit 2
 
20BCE1734.pdf
20BCE1734.pdf20BCE1734.pdf
20BCE1734.pdf
 
Algorithm Homework Help
Algorithm Homework HelpAlgorithm Homework Help
Algorithm Homework Help
 
Control System Homework Help
Control System Homework HelpControl System Homework Help
Control System Homework Help
 

Viewers also liked

Algorithm and Data Structures - Basic of IT Problem Solving
Algorithm and Data Structures - Basic of IT Problem SolvingAlgorithm and Data Structures - Basic of IT Problem Solving
Algorithm and Data Structures - Basic of IT Problem Solvingcoolpie
 
17 Trees and graphs
17 Trees and graphs17 Trees and graphs
17 Trees and graphsmaznabili
 
Introduction to Genetic Algorithms
Introduction to Genetic AlgorithmsIntroduction to Genetic Algorithms
Introduction to Genetic AlgorithmsAhmed Othman
 
Trees data structure
Trees data structureTrees data structure
Trees data structureSumit Gupta
 
How to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your NicheHow to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your NicheLeslie Samuel
 

Viewers also liked (6)

Algorithm and Data Structures - Basic of IT Problem Solving
Algorithm and Data Structures - Basic of IT Problem SolvingAlgorithm and Data Structures - Basic of IT Problem Solving
Algorithm and Data Structures - Basic of IT Problem Solving
 
Trees and graphs
Trees and graphsTrees and graphs
Trees and graphs
 
17 Trees and graphs
17 Trees and graphs17 Trees and graphs
17 Trees and graphs
 
Introduction to Genetic Algorithms
Introduction to Genetic AlgorithmsIntroduction to Genetic Algorithms
Introduction to Genetic Algorithms
 
Trees data structure
Trees data structureTrees data structure
Trees data structure
 
How to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your NicheHow to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your Niche
 

Similar to Unit2 algorithmic problem_solving

Ch-2 final exam documet compler design elements
Ch-2 final exam documet compler design elementsCh-2 final exam documet compler design elements
Ch-2 final exam documet compler design elementsMAHERMOHAMED27
 
01 - DAA - PPT.pptx
01 - DAA - PPT.pptx01 - DAA - PPT.pptx
01 - DAA - PPT.pptxKokilaK25
 
Mid term sem 2 1415 sol
Mid term sem 2 1415 solMid term sem 2 1415 sol
Mid term sem 2 1415 solIIUM
 
Unit i basic concepts of algorithms
Unit i basic concepts of algorithmsUnit i basic concepts of algorithms
Unit i basic concepts of algorithmssangeetha s
 
Data Structures and Algorithms Lecture 2: Analysis of Algorithms, Asymptotic ...
Data Structures and Algorithms Lecture 2: Analysis of Algorithms, Asymptotic ...Data Structures and Algorithms Lecture 2: Analysis of Algorithms, Asymptotic ...
Data Structures and Algorithms Lecture 2: Analysis of Algorithms, Asymptotic ...TechVision8
 
One More Comments on Programming with Big Number Library in Scientific Computing
One More Comments on Programming with Big Number Library in Scientific ComputingOne More Comments on Programming with Big Number Library in Scientific Computing
One More Comments on Programming with Big Number Library in Scientific Computingtheijes
 
Design & Analysis of Algorithm course .pptx
Design & Analysis of Algorithm course .pptxDesign & Analysis of Algorithm course .pptx
Design & Analysis of Algorithm course .pptxJeevaMCSEKIOT
 
Unit3 overview of_c_programming
Unit3 overview of_c_programmingUnit3 overview of_c_programming
Unit3 overview of_c_programmingCapuchino HuiNing
 
Problem solving using computers - Unit 1 - Study material
Problem solving using computers - Unit 1 - Study materialProblem solving using computers - Unit 1 - Study material
Problem solving using computers - Unit 1 - Study materialTo Sum It Up
 
Data structures notes for college students btech.pptx
Data structures notes for college students btech.pptxData structures notes for college students btech.pptx
Data structures notes for college students btech.pptxKarthikVijay59
 
Introduction to data structures and complexity.pptx
Introduction to data structures and complexity.pptxIntroduction to data structures and complexity.pptx
Introduction to data structures and complexity.pptxPJS KUMAR
 
Algorithm And analysis Lecture 03& 04-time complexity.
 Algorithm And analysis Lecture 03& 04-time complexity. Algorithm And analysis Lecture 03& 04-time complexity.
Algorithm And analysis Lecture 03& 04-time complexity.Tariq Khan
 

Similar to Unit2 algorithmic problem_solving (20)

Ch-2 final exam documet compler design elements
Ch-2 final exam documet compler design elementsCh-2 final exam documet compler design elements
Ch-2 final exam documet compler design elements
 
01 - DAA - PPT.pptx
01 - DAA - PPT.pptx01 - DAA - PPT.pptx
01 - DAA - PPT.pptx
 
Mid term sem 2 1415 sol
Mid term sem 2 1415 solMid term sem 2 1415 sol
Mid term sem 2 1415 sol
 
Code Tuning
Code TuningCode Tuning
Code Tuning
 
UNIT-2-PPTS-DAA.ppt
UNIT-2-PPTS-DAA.pptUNIT-2-PPTS-DAA.ppt
UNIT-2-PPTS-DAA.ppt
 
Unit i basic concepts of algorithms
Unit i basic concepts of algorithmsUnit i basic concepts of algorithms
Unit i basic concepts of algorithms
 
Data Structures and Algorithms Lecture 2: Analysis of Algorithms, Asymptotic ...
Data Structures and Algorithms Lecture 2: Analysis of Algorithms, Asymptotic ...Data Structures and Algorithms Lecture 2: Analysis of Algorithms, Asymptotic ...
Data Structures and Algorithms Lecture 2: Analysis of Algorithms, Asymptotic ...
 
One More Comments on Programming with Big Number Library in Scientific Computing
One More Comments on Programming with Big Number Library in Scientific ComputingOne More Comments on Programming with Big Number Library in Scientific Computing
One More Comments on Programming with Big Number Library in Scientific Computing
 
Design & Analysis of Algorithm course .pptx
Design & Analysis of Algorithm course .pptxDesign & Analysis of Algorithm course .pptx
Design & Analysis of Algorithm course .pptx
 
LMmanual.pdf
LMmanual.pdfLMmanual.pdf
LMmanual.pdf
 
Unit3 overview of_c_programming
Unit3 overview of_c_programmingUnit3 overview of_c_programming
Unit3 overview of_c_programming
 
Unit i
Unit iUnit i
Unit i
 
C++ in 10 Hours.pdf.pdf
C++ in 10 Hours.pdf.pdfC++ in 10 Hours.pdf.pdf
C++ in 10 Hours.pdf.pdf
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 
Unit i
Unit iUnit i
Unit i
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
Problem solving using computers - Unit 1 - Study material
Problem solving using computers - Unit 1 - Study materialProblem solving using computers - Unit 1 - Study material
Problem solving using computers - Unit 1 - Study material
 
Data structures notes for college students btech.pptx
Data structures notes for college students btech.pptxData structures notes for college students btech.pptx
Data structures notes for college students btech.pptx
 
Introduction to data structures and complexity.pptx
Introduction to data structures and complexity.pptxIntroduction to data structures and complexity.pptx
Introduction to data structures and complexity.pptx
 
Algorithm And analysis Lecture 03& 04-time complexity.
 Algorithm And analysis Lecture 03& 04-time complexity. Algorithm And analysis Lecture 03& 04-time complexity.
Algorithm And analysis Lecture 03& 04-time complexity.
 

Recently uploaded

Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
MICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptxMICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptxabhijeetpadhi001
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 

Recently uploaded (20)

Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
MICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptxMICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptx
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 

Unit2 algorithmic problem_solving

  • 2. Unit 2: Algorithmic Problem Solving 1. Problem Solving Process 2. Algorithm 3. Control Structures 4. Examples of Pseudocodes 5. Euclid’s Algorithm CS1010 (AY2014/5 Semester 1) Unit2 - 2© NUS
  • 3. Problem Solving Process CS1010 (AY2014/5 Semester 1) Unit2 - 3© NUS Analysis Design Implementation Testing Iterative process
  • 4. Problem Solving Process CS1010 (AY2014/5 Semester 1) Unit2 - 4© NUS Analysis Design Implementation Testing Iterative process
  • 5. Problem Solving Process CS1010 (AY2014/5 Semester 1) Unit2 - 5© NUS Analysis Design Implementation Testing Iterative process Algorithmic Determine problem features Write algorithm Produce code Check for correctness and efficiency What is an algorithm?
  • 6. Algorithm (1/3) CS1010 (AY2014/5 Semester 1) Unit2 - 6  An algorithm is a well-defined computational procedure consisting of a set of instructions, that takes some value or set of values as input, and produces some value or set of values as output. © NUS Input Algorithm Output ‘Algorithm’ stems from ‘Algoritmi’, the Latin form of al- Khwārizmī, a Persian mathematician, astronomer and geographer. Source: http://en.wikipedia.org/wiki/Algorithm
  • 7. Algorithm (2/3) CS1010 (AY2014/5 Semester 1) Unit2 - 7  An algorithm has these properties: © NUS Exact Terminate Effective General Each step must be exact. (Or it will not be precise.) The algorithm must terminate. (Or no solution will be obtained.) The algorithm must be effective. (i.e. it must solve the problem.) The algorithm must be general. (Within the constraints of the system/language.)
  • 8. Algorithm (3/3) CS1010 (AY2014/5 Semester 1) Unit2 - 8  Ways of representing an algorithm: © NUS Flowchart Pseudocode lynda.com
  • 9. Algorithm: Example #1 CS1010 (AY2014/5 Semester 1) Unit2 - 9© NUS
  • 10. Algorithm: Example #2 (1/2) CS1010 (AY2014/5 Semester 1) Unit2 - 10© NUS  Find maximum and average of a list of numbers: Flowchart start sum  count  0 max  0 end of input? Enter num increment count sum  sum + num Yes No num > max? Yes No max  num ave  sum/count end Terminator box Process box Decision box print max, ave
  • 11. Algorithm: Example #2 (2/2) CS1010 (AY2014/5 Semester 1) Unit2 - 11© NUS  Find maximum and average of a list of numbers: sum  count  0 // sum = sum of numbers // count = how many numbers are entered? max  0 // max to hold the largest value eventually for each num entered, count  count + 1 sum  sum + num if num > max then max  num ave  sum / count print max, ave Are there any errors in this algorithm? The need to initialise variables. The need to indent. Pseudocode
  • 12. Algorithm: Pseudocode CS1010 (AY2014/5 Semester 1) Unit2 - 12© NUS  We will write algorithms in pseudocode instead of flowchart as the former is more succinct  However, there are no standard rules on how pseudocodes should look like  General guidelines:  Every step must be unambiguous, so that anybody is able to hand trace the pseudocode and follow the logic flow  Use a combination of English (keep it succinct) and commonly understood notations (such as  for assignment in our previous example)
  • 13. Control Structures (1/2) CS1010 (AY2014/5 Semester 1) Unit2 - 13  An algorithm is a set of instructions, which are followed sequentially by default.  However, sometimes we need to change the default sequential flow.  We study 3 control structures. © NUS
  • 14. Control Structures (2/2) CS1010 (AY2014/5 Semester 1) Unit2 - 14© NUS • DefaultSequence • Also called branchingSelection • Also called loopRepetition True False ? True False ?
  • 15. Data Representation CS1010 (AY2014/5 Semester 1) Unit2 - 15  Internal representation: bits (binary digits) 0 and 1  1 byte = 8 bits  In programming, we need variables to hold data. A variable has an associated data type and occupies memory space. In the following slides, variables are shown as boxes.  Some data types in C (list is not exhaustive)  Integers: int, short, long (int is most common)  Real numbers: float, double  Characters: char  Self-reading: Lesson 1.4 in reference book © NUS
  • 16. Control Structures: Sequence (1/2) CS1010 (AY2014/5 Semester 1) Unit2 - 16  Task: Compute the average of three integers © NUS Each box represents a variable. Important concepts: Each variable has a unique name and contains a value. A possible algorithm: enter values for num1, num2, num3 ave  ( num1 + num2 + num3 ) / 3 print ave Variables used: num1 num2 num3 ave Another possible algorithm: enter values for num1, num2, num3 total  ( num1 + num2 + num3 ) ave  total / 3 print ave Variables used: num1 num2 num3 ave total
  • 17. Control Structures: Sequence (2/2) CS1010 (AY2014/5 Semester 1) Unit2 - 17  Task: Compute the average of three integers  How the program might look like © NUS // This program computes the average of 3 integers #include <stdio.h> int main(void) { int num1, num2, num3; float ave; printf("Enter 3 integers: "); scanf("%d %d %d", &num1, &num2, &num3); ave = (num1 + num2 + num3) / 3.0; printf("Average = %.2fn", ave); return 0; } Unit2_prog1.c
  • 18. Control Structures: Selection (1/3) CS1010 (AY2014/5 Semester 1) Unit2 - 18  Task: Arrange two integers in ascending order (sort) © NUS Algorithm A: enter values for num1, num2 // Assign smaller number into final1, // and larger number into final2 if (num1 < num2) then final1  num1 final2  num2 else final1  num2 final2  num1 // Transfer values in final1, final2 back to num1, num2 num1  final1 num2  final2 // Display sorted integers print num1, num2 Variables used: num1 num2 final1 final2 True False ?
  • 19. Control Structures: Selection (2/3) CS1010 (AY2014/5 Semester 1) Unit2 - 19  Task: Arrange two integers in ascending order (sort) © NUS Algorithm B: enter values for num1, num2 // Swap the values in the variables if necessary if (num2 < num1) then temp  num1 num1  num2 num2  temp // Display sorted integers print num1, num2 Variables used: num1 num2 temp Compare Algorithm A with Algorithm B. True False ?
  • 20. Control Structures: Selection (3/3) CS1010 (AY2014/5 Semester 1) Unit2 - 20  How the program might look like for Algorithm B © NUS // This program arranges 2 integers in ascending order #include <stdio.h> int main(void) { int num1, num2, temp; printf("Enter 2 integers: "); scanf("%d %d", &num1, &num2); if (num2 < num1) { temp = num1; num1 = num2; num2 = temp; } printf("Sorted: num1 = %d, num2 = %dn", num1, num2); return 0; } Unit2_prog2.c True False ?
  • 21. Control Structures: Repetition (1/3) CS1010 (AY2014/5 Semester 1) Unit2 - 21  Task: Find sum of positive integers up to n (assume n>0) © NUS Algorithm: enter value for n // Initialise a counter count to 1, and ans to 0 count  1 ans  0 while (count <= n) do ans  ans + count // add count to ans count  count + 1 // increase count by 1 // Display answer print ans Variables used: n count ans Initialisation is very important! True False ?
  • 22. Control Structures: Repetition (2/3) CS1010 (AY2014/5 Semester 1) Unit2 - 22  Important to trace pseudocode to check its correctness © NUS Algorithm: enter value for n count  1 ans  0 while (count <= n) do ans  ans + count count  count + 1 // Display answer print ans count ans(count <= n)? Assume user enters 3 for n. 1 0 true 12 true 33 true 64 false Output: 6 True False ?
  • 23. Control Structures: Repetition (3/3) CS1010 (AY2014/5 Semester 1) Unit2 - 23  How the program might look like © NUS // Computes sum of positive integers up to n #include <stdio.h> int main(void) { int n; // upper limit int count=1, ans=0; // initialisation printf("Enter n: "); scanf("%d", &n); while (count <= n) { ans += count; count++; } printf("Sum = %dn", ans); return 0; } Unit2_prog3.c True False ?
  • 24. Euclid’s Algorithm (1/3) CS1010 (AY2014/5 Semester 1) Unit2 - 24  To compute the greatest common divisor (GCD) of two integers  First documented algorithm by Greek mathematician Euclid in 300 B.C.  Also known as Euclidean Algorithm © NUS 1. Let A and B be integers with A > B ≥ 0. 2. If B = 0, then the GCD is A and algorithm ends. 3. Otherwise, find q and r such that A = q.B + r where 0 ≤ r < B 4. Replace A by B, and B by r. Go to step 2.
  • 25. Euclid’s Algorithm (2/3) CS1010 (AY2014/5 Semester 1) Unit2 - 25© NUS  q is not important; r is the one that matters.  r could be obtained by A modulo B (i.e. remainder of A / B)  Assumption on A > B unnecessary 1. Let A and B be integers with A > B ≥ 0. 2. If B = 0, then the GCD is A and algorithm ends. 3. Otherwise, find q and r such that A = q.B + r where 0 ≤ r < B 4. Replace A by B, and B by r. Go to step 2.  We will rewrite the algorithm
  • 26. Euclid’s Algorithm (3/3) CS1010 (AY2014/5 Semester 1) Unit2 - 26  Euclid’s algorithm rewritten in modern form © NUS // Assume A and B are non-negative // integers, but not both zeroes. Algorithm GCD(A, B) { while (B > 0) { r  A modulo B A  B B  r } result is A } Let’s trace GCD(12, 42) B(B > 0)? Ar 12 true 42 42 1212 true 12 66 true 6 00 false Result: 6
  • 27. Summary CS1010 (AY2014/5 Semester 1) Unit2 - 27  In this unit, you have learned about  The process of algorithmic problem solving  The properties of an algorithm  The three control structures  How to write algorithms in pseudocode  Tracing algorithms to verify their correctness © NUS
  • 28. End of File CS1010 (AY2014/5 Semester 1) Unit2 - 28© NUS