Lecture 3 – Common Algorithms
Lecture 3
Objectives
Common Algorithms
Total T l Average Counting Minimum value and maximum value
Ranged value Unlimited l U li i d value
1
Mohd Hanapi Abdul Latif
Total / Sum group of values
The algorithm in this application may be used to solve sol e problem such as s ch
To calculate the total of payment for N employees; To sum the amount that a customer has to pay; To calculate the total of salary that a person receives in a year; and To l l t the total T calculate th t t l payment of ticket f a show. t f ti k t for h
Mohd Hanapi Abdul Latif
Total / Sum group of values
Steps Example – display the sum of 10 prices double price, sumPrice; p , ; sumPrice=0.0; 1. Introduce a variable to store the sum of values and initial it to zero. 2. In a repetition structure, sum the a number.
for (int bil = 0; bil < 10; bil++) { //input and sum value of price price=inp.nextDouble(); sumPrice= sumPrice + price; } System.out.println(“The sum prices is RM: ”+sumPrice); of 10
3. Display or use the summed value after the loop
2
Mohd Hanapi Abdul Latif
Common mistakes
Variable to sum numbers is not initialized Variable to sum numbers is initialized in the loop. p for (int cnt=0; cnt < 10; cnt++) { sumNum = 0.0; System.out.print ("Enter a number: "); no = inp.nextDouble(); sumNum += no; } Incorrect arithmatic expression to sum numbers. for (int cnt=0; cnt < 10; cnt++) { : no = inp.nextDouble(); sumNum = no; : }
Mohd Hanapi Abdul Latif
Counting of occurrence
Counting the occurrence of item such as the number of odd values, h b f dd l the numbers of all values that the user keys in, the number of male gender, the number of students that have cgpa between 3.00 until 4.00
3
Mohd Hanapi Abdul Latif
Steps
Example – count the number of prices that is higher than RM50.00 g
1) Introduce a variable of type double price; int and initial it to zero. int