Transcript Case study
Case study 1: Calculate the approximation of Pi
• •
Calculate the approximation of Pi by formula
1 1 1 4 3 5 7
with error 1e-4.
...
Algorithm 1. pi = 0, s = 1, n = 1, t = s/n 2. while fabs(t) > 1e-4 do 1. pi = pi + t 2. n = n +2 3. s = -s 4. t = s / n; 5. end while 3. Pi = 4 * pi
CP104 Introduction to Programming
Repetition and loop
Lecture 15 __ 1
Implementation
#include
CP104 Introduction to Programming
Repetition and loop
Lecture 15 __ 2
Case Study 2: Fibonacci Sequence
•
Calculate the first 40 number of Fibonacci sequence: F(1) = 1, F(2) = 1, …, F(n) = F(n-1) + F(n-2)
•
Algorithm 1. f1 = 1, f2 = 1, i = 1 2. For i from 1 to 20 do 1.
2.
3.
Print f1 and f2 f1 = f1 + f2 f2 = f2 + f1 End of for loop
CP104 Introduction to Programming
Repetition and loop
Lecture 15 __ 3
Implementation
#include
CP104 Introduction to Programming
Repetition and loop
Lecture 15 __ 4
Case Study 3: Simple Encryption and Decryption
•
Problem: Convert a plain text to a cipher text by alphabet of module k. Where 0
• •
Encryption Algorithm: 1. Get a key k 2. While the input character c is not \n 3. Convert c into its cipher text by using the kth letter forward 4. End while Encryption Algorithm: 1. For key k 2. While the input character c is not \n 3. Convert c into its plain text by using the kth letter backward 4. End while
CP104 Introduction to Programming
Repetition and loop
Lecture 15 __ 5
Implementation
#include
CP104 Introduction to Programming
Repetition and loop
Lecture 15 __ 6
Reading Data from a File
#include
CP104 Introduction to Programming
Repetition and loop
Lecture 15 __ 7
Structure Chart for Computing Solar Collecting Area Size
CP104 Introduction to Programming
Repetition and loop
Lecture 15 __ 8
Program to Approximate Solar Collecting Area Size
CP104 Introduction to Programming
Repetition and loop
Lecture 15 __ 9
Program to Approximate Solar Collecting Area Size (cont’d)
CP104 Introduction to Programming
Repetition and loop
Lecture 15 __ 10
Program to Approximate Solar Collecting Area Size (cont’d)
CP104 Introduction to Programming
Repetition and loop
Lecture 15 __ 11