naming, algorithms#1 ctps 2018 · 2019. 5. 20. · 1. start 2. declare sum, count, num 3. set sum =...
TRANSCRIPT
Department of CSE,Coimbatore
Naming, Algorithms#1
CTPS 2018
LN #4
(2 Hrs)
Objectives
❖To understands the importance of naming
❖To understand the characteristics of algorithms
❖To learn to write algorithms
Department of CSE,Coimbatore
Names
• An identifier (or name) is used to identify the entities, eg., variables,
module names.
• Naming conventions increase readability.
Good naming practices
1. Never use I (lowercase L ) or O (uppercase O ) as variable or constant
names.(Confused for 1 or a 0)
2. What about the length of the name?
“total_number_of_entries_with_mangled_or_out_of_range_dates ”?
• This is an extremely descriptive name.
• First, they are difficult to type.
• Second, remembering the exact wording of such a long name is not easy.
• What happens when you try to use this variable in a statement?Department of CSE,Coimbatore
3. Connection character (e.g. first_name, First-name)
• What about first$name???
4. Case sensitivity (e.g.Name,name,NAME)
5. Don´t use negative logic for your variable names.
• Good Example: IsEnabled.
• Bad Example: IsNotEnabled.
It’s always easier to read and understand a statement that is expressed in a positive language than that in a negative language.
7. Reserved words or keywords?
• (PI, Cu(copper))
• What about assigning PI=24(hours of a day), Cu in chemistry to represent metal gold?
Department of CSE,Coimbatore
Guidelines for Naming
• Names should be unique.
• One item should not have more than one name.
• Eg. “get the data”,using multiple words like “load”, “fetch”, “get” may be
confusing.
• A name should be descriptive. Eg. FileAgeInDays is better than
“faid”.
• Descriptive names reduce confusion.
• They help us understand the role of the item.
• They help us to understand the content of the item.
Department of CSE,Coimbatore
Try it yourself
✓Assume that a user need to create an e-mail account. List the fields
required to be filled in registration form and suggest suitable names,
datatype (number, string, boolean) and range of values
for the attributes (fields) identified.
______________________________________________
______________________________________________
______________________________________________
______________________________________________
______________________________________________
Department of CSE,Coimbatore
Proper name selection
• Computer scientists have long recognized the critical importance ofchoosing correct names for the elements of a program.
• Computer scientists also recognize that a set of well-namedprogramming elements shows a mastery of the logic and nature ofthe underlying computation.
• An element is well named if the name descriptively and correctlyreflects the central essence of the element.
• Proper naming thus enables a computer scientist to more clearlyreason about the algorithm and data of the program.
• Poorly named program elements reflect a confused understanding ofthe elements and also make clear-headed reasoning more difficult.
Department of CSE,Coimbatore
✓ Appropriate choices of names are keystone for good style.
✓ Poor naming makes is difficult to understand (leads to confusion).
• In the Figure: Importance of naming, Algorithm2 uses appropriate
names.
Department of CSE,Coimbatore
Algorithm 1
1. Get a,b,c
2. If a<24 && b<60 && c<60
Then Return true
Else Return false
Algorithm 2
1. Get hours, minutes, seconds
2. If hours<24 && minutes<60
&& seconds<60
Then Return true
Else Return false
Figure: Importance of naming
• Two algorithms for computing cost of gas filling is given in
Algorithm 1 (Version 1)and Algorithm 2 (Version 2).
✓ Can you comment on the names in terms of their readability?Which
algorithm follows proper naming conventions?
Department of CSE,Coimbatore
1. C 3.75
2. Size 10
3. Money Size * C
Algorithm 1
1. INRPerGallon 3.75
2. TankCapacity 10
3. INRToFill TankCapacity *
INRPerGallon
Algorithm 2
Figure: Version #1 Figure: Version #2
• An algorithm using an exchange rate of 10 to determine the BRL
that corresponds with US$3.75 is given in Figure: Concurrency
conversion.
✓ What will happen in the above examples if descriptive names are
replaced with names like x,y,z etc.
Department of CSE,Coimbatore
1. USD 3.75
2. ExchangeRate 10
3. BRL USD * ExchangeRate
Figure: Currency conversion
✓Given that width = 17, height = 2.0 and delimiter = ‘ . ’
✓For each of the following expressions, find the value of the expression
and type (of the value of the expression) (number, string,boolean)
1. width/2
2. width/2.0
3. height/3
4. 1 + 2 * 5
5. delimiter * 5
Department of CSE,Coimbatore
Given that width = 17, height = 2.0, and delimiter = '.'
For each of the following expressions, can you find the
value of the expression
type (of the value of the expression)
width/2 = 17/2 ------------- 8(Integer)
width/2.0 =17.0/2.0 ----------8.5 (Float)
height/3 =2.0/3 -----------0.66 (Float)
1 + 2 * 5 ---------11
delimiter * 5 -------ASCII value of ‘.’ (46)* 5 = 230
Ability to
• Understand
• Execute
• Evaluate
• Create algorithms
Algorithmic thinking
Department of CSE,Coimbatore
ALGORITHM
• An algorithm is a sequence of finite instructions,often used for calculation and data processing.
• It is an effective, step-by-step method of solving aproblem.
• A method in which we write a list of well-definedinstructions for completing a task.
• It will start from an initial state, proceed through awell-defined series of successive states, eventuallyterminating in an end-state.
Department of CSE,Coimbatore
CHARACTERISTICS
Department of CSE,Coimbatore
1. Finiteness. An algorithm must always terminate
after a finite number of steps.
2. Definiteness. Each step of an algorithm must be
precisely defined; the actions to be carried out must
be unambiguously specified for each case.
3. Input.An algorithm has zero or more inputs.
4.Output. An algorithm has at least one desirable
output.
5. Effectiveness. All operations to be performed in the
algorithm must be sufficiently basic.
Problems (Tasks), Algorithms, Programs
Department of CSE,Coimbatore
Department of CSE,Coimbatore
Expressing Algorithms
Testing the correctness of algorithms
Department of CSE,Coimbatore
Test the algorithm by choosing different
sets of input values, carrying out the
algorithm (tracing the computational
states), and checking to see if the resulting
solution does, in fact, work.
Facebook registration
• To log in to facebook account we first enter the facbook URL
www.facebook.com in our browser like Google, Firefox, Safari,
Internet Explorer etc. This request is sent to the facebook
server and it responds by sending us the home page of facebook.
• Next, we enter our registered Email ID and Password and click
the Login button.
• Then our login credential is checked. If it is correct, we are
show our profile. On the other hand, if the login credential is
wrong then an error occurs and we are prompted to re-enter
our Email ID and Password.
1. Start
2. Enter www.facebook.com in your browser. (Input)
3. facebook Home page loads (PROCESS)
4. Enter your Email ID and Password (Input)
5. Is Email ID and Password Valid? (DECISION)
then Display facebook Account (Output)
else Log in error (PROCESS) and go to step 3
6. Stop
Area and circumference of circle
Step 1 : Start
Step 2 : Set the value of pi to Pi
Step 3 : Read radius r
Step 4 : Compute area and circumference
Step 5 : Display area and circumference
Step 6 : Stop
Area and circumference of circle
Step 1 : Start
Step 2 : Set Pi =3.14
Step 3 : Read r
Step 4 : Area=Pi*r*r
Step 5: Circumference=2*Pi*r
Step 6 : Display area and circumference
Step 7 : Stop
Area and circumference of circle
Step 1 : Start
Step 2 : Declare Pi, r,Area,Circumference
Step 3 : Set Pi =3.14
Step 4 : Read r
Step 5 : Area=Pi*r*r
Step 6: Circumference=2*Pi*r
Step 7 : Display area and circumference
Step 8 : Stop
Calculate the Interest of a Bank Deposit
Step 1: Start
Step 2: Declare Amount, Years, Rate, Interest
Step 3: Read Amount
Step 4: Read Years
Step 5: Read Rate
Step 6: Interest=Amount*Years*Rate/100
Step 7: Print Interest
Step 8: Stop
Write an Algorithm for
Step1: Start
Step2: Read/input x
Step3: If (x<0) then f =-x
Step4: If x (>=0) then f =x
Step5: Print f
Step6: Stop
Department of CSE,Coimbatore
Determine whether a number is Even or Odd
Step 1: Start
Step 2: Declare N, Remainder
Step 3: Read N
Step 4: Remainder = N modulo 2
Step 5: If (Remainder is equal to 0)
then answer = “Number is even”
else answer = “Number is odd”
Step 6: Print answer
Step 7: Stop
Determine Whether A Student Passed the Exam or Not
Step 1: Start
Step 2: Declare M1,M2,M3,M4,average_grade
Step 3: Input grades of 4 courses M1, M2, M3, M4
Step 4: average_grade=(M1+M2+M3+M4)/4
Step 5: If (average_ grade < 60 )
then print "FAIL”
else print "PASS”
Step 6: stop
1. Start
2. Get cash amount .
3.Set Hs (hundreds) and Fhs (five hundreds) to 0.
4. If (amount < 500)
Then Hs = amount/100
Else Fhs = amount / 500
Hs = (amount mod 500) / 100
5. Display the amount, Fhs and Hs.
6. Stop
Denomination while dispensing cash (assuming
availability of only 100 and 500 Rs. Notes)
Department of CSE,Coimbatore
An algorithm with a natural number, n, as its input , to
calculate : S = ½ + ¼ + ... +1/n
1. Start
2. Read n
3. Set i =2 , S = 0
4. While ( i<=n)
4.1 S= S + (1/i )
4.2 i ← i + 2
5. Display S
6. Stop
Department of CSE,Coimbatore
Multiway selection
IF decision_1
THEN sequence_1
ELSE IF decision_2
THEN sequence_2
ELSE IF decision_3
THEN sequence_3
ELSE sequence_4
Determine Largest of 3 Numbers
Step 1: StartStep 2: Declare N1,N2,N3, MAXStep 3: Input N1, N2, N3Step 4: if (N1>N2)
then if (N1>N3) then MAX N1else MAX N3
endifelse if (N2>N3)
then MAX N2else MAX N3
endifendif
Step 5: Print “The largest number is”, MAXStep 6: Stop
Read an employee name, overtime hours
worked , hours absent and determine the
bonus payment.
Bonus Schedule
OVERTIME – (2/3)*ABSENT Payment
>40 hours
>30 but 40 hours
>20 but 30 hours
>10 but 20 hours
10 hours
50
40
30
20
10
Step 1: Input NAME,OVERTIME,ABSENT
Step 2: if (OVERTIME–(2/3)*ABSENT > 40)
then PAYMENT= 50
else if (OVERTIME–(2/3)*ABSENT > 30)
then PAYMENT =40
else if (OVERTIME–(2/3)*ABSENT > 20)
then PAYMENT = 30
else if (OVERTIME–(2/3)*ABSENT > 10)
then PAYMENT = 20
else PAYMENT = 10
endif
Step 3: Print “Bonus for”, NAME “is inr”, PAYMENT
Take as input the user’s bank account balance and
the type and level of account they have. Based on
this information and the below rate table, determine
the interest rate .
Sum of 5 numbers
1. Start
2. Declare sum, count, num
3. Set sum = 0, count = 0 (Initialize)
4. Enter num (Input /Read )
5. Find sum + num and assign it to sum (Compute)
6. Increment count by 1 (Compute)
7. If (count < 5) (Decision)
then go to step 3 (Repeat)
else Print sum (Output / Display)
8. Stop
Sum of 5 numbers
1. Start
2. Declare sum, count, num
3. Set sum = 0, count = 0 (Initialize)
4. Enter num (Input /Read )
5. sum= sum + num (Compute)
6. count = count +1 (Compute)
7. If (count < 5) (Decision)
then go to step 3 (Repeat)
else Print sum (Output / Display)
8. Stop
Sum of 5 numbers
1. Start
2. Declare sum, count, num
3. Set sum = 0, count = 0
4. While (count < 5)
4.1 Enter num
4.2 sum= sum +num
4.3 count = count +1
5. Print sum
6. Stop
Sum of n numbers
1. Start
2. Declare sum, count, num,n
3. Set sum = 0, count = 0
4. While (count < n)
4.1 Enter num
4.2 sum= sum +num
4.3 count = count +1
5. Print sum
6. Stop
0! = 1
1! = 1 = 0! x 1
2! = 1 x 2 = 1! x 2
3! = 1 x 2 x 3 = 2! x 3
4! = 1 x 2 x 3 x 4 = 3! x 4
5! = 1 x 2 x 3 x 4 x 5 = 4! x 5
6! = 1 x 2 x 3 x 4 x 5 x 6 = 5! x 6
✓ Do you see a pattern emerging?
✓ Can you write an algorithm employing this pattern?
p = 1 = 0!
p = p x 1 = 1!
p = p x 2 = 2!
p = p x 3 = 3!
p = p x 4 = 4!
p = p x 5 = 5!
p = p x 6 = 6!
A Refresher on Factorial
Department of CSE,Coimbatore
p = 1 = 0!
p = p (whose value now is 0!) x 1 = 1!
p = p (whose value now is 1!) x 2 = 2!
p = p (whose value now is 2!) x 3 = 3!
p = p (whose value now is 3!) x 4 = 4!
p = p (whose value now is 4!) x 5 = 5!
p = p (whose value now is 5!) x 6 = 6!
The pattern!!
Department of CSE,Coimbatore
Factorial of a given number
1. Start
2. Set fact=1 , i =1
3. Read n
4. While (i < = n)
3.1 fact = fact * i
3.2 i = i +1
5. Print fact
6. Stop
Sum all the even numbers between 1 and 20 inclusive
and then displays the sum.
Step1 : Start
Step 2: Declare sum, count
Step 3: Set sum = 0, count = 1
Step 4: REPEAT
4.1 IF (count mod 2 is equal to 0)
THEN sum = sum + count
4.2 count = count + 1
UNTIL count > 20
Step 5: DISPLAY sum
Step 6: Stop
Read integer, check if it is –1, if so quit. If not, add this
number to the sum and repeat read.
Step 1: StartStep 2: Declare sum, xStep 3: Set sum = 0Step 4: Read xStep 5: While (x != -1) do
5.a : sum = sum + x5.b: Read next x
Step 6: Stop
Consider the previous example set.
Three situations are possible
• 2nd number can be less than the temporary maximum number.
• It could be equal to the temp. max. no.
• It could be greater than the temp. max. no.
Situations 1 & 2, the temp. max. no. is unchanged. Situation 3, the
2nd number becomes the new temp. max. no.
This has to be repeated till the end of the set.
8 136211971556
Find maximum number in a set of numbers
Department of CSE,Coimbatore
1.Get an array a[0,...n-1] of n elements where n ≥ 1.
2. Set temporary maximum max to first array element i.e. a[0].
3. While less than n array elements have been considered repeatedly
do
a)If next element greater than current maximum then assign it
to max.
4. Return the maximum max for the given array.
Algorithm to find maximum number
Department of CSE,Coimbatore
What has been described?
• Naming and importance of naming
• Characteristics of algorithm
• Algorithms for various problems using combinations of
control structures
Credits
•Programming Languages,2nd edition,Tucker and Noonan
•www.cse.msu.edu/ Organization of Programming Languages-Cheng (Fall 2004)
•Computing Without Computers,A Gentle Introduction to Computer
• Programming,Data Structures and Algorithms,Version 0.15,Paul Curzon
•Google images
•http://courses.cs.vt.edu/cs2104/Fall12/notes/T16_Algorithms.pdf
•http://bisma.in/algorithm-and-its-characteristics/
Department of CSE,Coimbatore