The words you are searching are inside this book. To get more targeted content, please make full-text search by clicking here.

[UNOFFICIAL] BUKU TEKS SAINS KOMPUTER TINGKATAN 5 DALAM BAHASA INGGERIS (AUTO-TRANSLATE)

Discover the best professional documents and content resources in AnyFlip Document Base.
Search
Published by Tunku Irfan, 2023-08-18 16:53:42

[BAHASA INGGERIS] BUKU TEKS SAINS KOMPUTER TINGKATAN 5

[UNOFFICIAL] BUKU TEKS SAINS KOMPUTER TINGKATAN 5 DALAM BAHASA INGGERIS (AUTO-TRANSLATE)

Keywords: sains komputer,buku teks sains komputer,sains komputer buku teks,buku teks sains komputer tingkatan 5,sains komputer tingkatan 5

3 Compare the element in the middle whether it is greater than the element sought. There are three comparison processes that can be implemented, namely: 2 Compare the element in the middle whether it is smaller than the element sought after. 1 Compare the element in the middle to see if it is the same as the element you are looking for. Binary search is suitable for use when there is a large number of data that has been sorted. Basically, the binary search process is as in Figure 3.1.23. Binary search 5 Make sure that a display like the following is generated: Part 2: 2 Draw a flow chart for the program that has been built in Part 1, which is a program to sort the number of pencils found in five students from the least to the most (in ascending order). My Malaysia! 1 Take a new piece of paper. and a digital library of Dr. Malay manuscripts. Teoh Wei Lin (USM): Optimal design research based on parameter estimation Dr. Salfarina Abdullah (UPM): Contribution in the development of software architecture Dr. Afnizanfaizal Abdullah (UTM): Research in Artificial Intelligence and Bioinformatics Group (AIBIG) Source: http:// www.mimos. Zaini Ahmad (UKM): Research in Numerical Methods for Computing Fuzzy-valued Functions and its Application to Differential Equations. Figure 3.1.23 Binary search process On 31 October 2013, five Malaysians received the MIMOS Prestigious Award (MPA) for their outstanding achievements in research, development, and commercialization to improve global science in Malaysia as well as innovate in the field of computer science. CHAPTER 3 Web-Based Programming 143 my/ paper/ honouring achievements-that drive-malaysias-global competitiveness/ Find the location in the middle of the list Dr. Zahidah Zulkifli (UM): Research in the field of paleography Get the element in the middle of the list Compare with the searched element The award recipients are: Dr. Muhammad Continue the search process from the sub-List Machine Translated by Google


Did you know? You { If the number referred to is the SAME as the number sought document.write('<br>Referred middle number:',no[middle index],'(See you)'); document.write(“<br>Referred middle number: “, Sorted numbers no[Middleindex],” (Go to the right side) “); <body> is different from Java. } while (no[MiddleIndex] != noSearch && StartIndex < EndIndex) } </script> 144 Computer Science Form 5 { if (no[MiddleIndex] < noSearch) <script> Middle index = Math.floor((End index + Start index)/2); if (no[Midindex] == noSearch) indexInitial = indexMiddle + 1; var noSearch = 2; sought after Use of symbols “ “, ' ', + and in JavaScript Figure 3.1.24 JavaScript program and output (binary search) no[Middleindex],” (Go left) “); document.write(“Search No:”, noSearch); Middle index recalculation } , </body> otherwise <html> { } var no = [1,2,3,4,5]; As long as the referenced number is NOT the same as the number } if (no[Midindex] > noSearch) { document.write(“<br>Referred middle number: “, var indexStart = 0, indexEnd = no.length - 1, indexMiddle = Math.floor((indexEnd + indexStart) / 2); indexEnd = indexMiddle - 1; { </html> EXAMPLE 7 Example 7 shows the search for a number (ie 2) in a list of numbers using the binary search method. The JavaScript program and output are shown in Figure 3.1.24. In this method, the numbers in the list are the sorted numbers. Machine Translated by Google


no[middle index]> indexEnd = Figure 3.1.25 Flow chart (binary search) indexCenter+1 TRUE Middle index = Math.floor((End index + Start index)/2) noSearch? has been sorted FAKE "No Search" Start SAME as the number sought indexMiddle = Math . Finished referred to is NOT the same as the number sought FAKE no = 1,2,3,4,5 TRUE CHAPTER 3 Web-Based Programming 145 indexMiddle-1 noSearch? Initial index = 0 no[Middleindex] != noSearch && Startindex < Endindex referred to Display text FAKE Show "See you" floor((End index + Start index)/2) no[middle index]= The number that Display noSearch value TRUE noSearch = 2 FAKE TRUE As long as the number noSearch? no[middle index]< indexEnd = no.length-1 If the number indexEnd = Middle index recalculation EXAMPLE 8 Example 8 shows the determination of even numbers from a list of numbers using the binary search method. The JavaScript program and output are shown in Figure 3.1.26. However, determining whether the numbers in the list are even or odd is necessary Even or odd number searches can still be performed using binary searches. The flow chart for Example 7 is shown in Figure 3.1.25. Machine Translated by Google


if (no[MiddleIndex] < noEven) List of numbers document.write(“<br>Middle number referenced: “, no[Middleindex], “ (Find an even number) “); } { no[i]%2==1 (searched number) } { <body> noEven = no[i]; Recalculate the middle index </script> { var noEven; { { 146 Computer Science Form 5 { which has been sorted { } } As long as the number referred to is not the same as the even number sought <html> if (no[MiddleIndex] > noEven) } Middle index = Math.floor((End index + Start index)/2); } If the referenced number is the same as the even number sought var StartIndex = 0, EndIndex = no.length - 1, MiddleIndex = Math.floor((EndIndex + StartIndex)/2); <script> } else </body> for(i=0; i<5; i++) </html> indexEnd = indexMiddle - 1; var no = [11,23,38,48,150], i; indexInitial = indexMiddle + 1; while (no[Midindex] != noEven && Startindex < Endindex) Determine the even number no[i]%2==0 if ((no[i]%2 == 0)) if (no[MiddleIndex] == noEven) implemented first. To determine whether a number is even, the number must be divided by 2 and the remainder must be 0, while to determine whether the number is odd, the number must be divided by 2 and the remainder must be 1. Odd numbers Determination of even numbers, the number must be divided by 2 and the remainder must be 0 Determination of odd numbers, the number must be divided by 2 and the remainder must be 1 The '%' operator is used for operations to get the balance Even number The '%' operator is used for operations to get the balance Machine Translated by Google


The flow chart for Example 8 is shown in Figure 3.1.27. Display noEven indexEnd = indexMiddle + 1 FAKE Start Determine the even number (the number to be searched for) no[middle index]< middle index Recount As long as the number referred to Figure 3.1.26 JavaScript program and output for binary search (even number search) TRUE no[middle index]< TRUE Math.floor((indexEnd + FAKE i < 5? indexEnd = no.lengthÿ1 no [middle index] Figure 3.1.27 Binary search flowchart (even number search) Finished TRUE i = 0 noEven = no[i] SAME as number even sought Display “Referred middle number: noEven? no[i]%2 == 0? A sorted list of numbers no[Midindex]!= noEven == noEven? FAKE NOT EQUAL to the even number sought indexEnd = indexMiddle ÿ 1 TRUE CHAPTER 3 Web-Based Programming 147 TRUE Middle index = Math.floor((End index + Start index)/2) i = i + 1 FAKE Initial index)/2) FAKE If the number FAKE Initial index = 0 indexMiddle = Display “(Find an even number)” noEven? TRUE Start index < End index? no = 11,23,38,48,150 referred to Machine Translated by Google


50 Motorcycle 56 200 71 Type of Transportation 250 0 186 150 Airplane 205 Car Train Carbon Monoxide Emissions Per Kilometer By Transport Type 100 Bus 96 The maximum value refers to the largest value in a list of values. The process of finding the maximum value can be implemented as shown in Figure 3.1.28. Carbon Monoxide Emissions Per Km Individual Work Calculations to Obtain Maximum, Minimum and Mean Values 148 Computer Science Form 5 ACTIVITY 4 Getting Maximum Value (Binary Search) (b) Next, find the value of 186, which is the emission of monoxide by a bus using Search Client Scripting Program for Finding Values using Binary Search Write a complete flow chart for the program that was built in Part 1. Given statistical information on carbon monoxide emissions based on the type of transport as below: 96, 186, 71, 56). Part 2: 75% of carbon monoxide is released from transportation such as cars and buses. In urban areas, harmful carbon monoxide emissions account for 50% to 90% of air pollution. Write a client scripting program that can: (a) receive the list of carbon monoxide emission values shown in the figure above (205, (c) Display the message "Monoxide emissions by a bus" if the value in (b) is found. Objective: Produce a client scripting program to find a value from a list of values using the binary search method. Part 1: Binary search. Machine Translated by Google


Example 9 shows the process of finding the largest number (maximum value) in a list of numbers. The JavaScript program and output are shown in Figure 3.1.29. EXAMPLE 9 Give the maximum initial value Compare the referenced numbers Figure 3.1.29 JavaScript program and output (getting the maximum value) latest no.length to count the number of numbers in the list Considered -1 is noMaximum (choose the lowest number) Get the maximum value CHAPTER 3 Web-Based Programming 149 Reason: The referenced number is LARGER than the current value of noMaximum Compare the values in the list with the maximum initial value Assign a prefix value to noMaximum. Figure 3.1.28 The process of finding the maximum value GREATER than noMaximum noMaximum is now the number being referenced. } for(i=0; i<bilNumber; i++) i,bilNumber = no.length; if (no[i] > noMaximum) </body> { </script> noMaximum = no[i]; <html> </html> { document.write(noMaximum); var no = [5,1,4,12,8], noMaximum = -1, } <body> <script> There is only one comparison process, which is to compare the value referenced in the list whether it is greater than the maximum value. Machine Translated by Google


EXAMPLE 10 The process of finding the maximum value can be used to find other values such as the tallest building and the longest distance. The flowchart for Example 9 is shown in Figure 3.1.30. Example 10 shows that there is a list of distance values, which is the travel distance from home to school for 5 students. The program will be able to help find the longest distance taken by students to come to school. Assign a prefix value to noMaximum. FAKE Finished TRUE Considered -1 is noMaximum (choose the lowest number) noMaximum is now the number being referenced. Reason: Referenced number no = 5,1,4,12,8 no. length to count the number of numbers in the list TRUE i < billNumber? Start noMaximum = no[i] 150 Computer Science Form 5 LARGER than noMaximum noMaximum = -1 FAKE display Compare the numbers referred to either MORE billNumber = no.length GREATER than the current value of noMaximum Figure 3.1.30 Flow chart (getting the maximum value) i = 0 i = i + 1 noMaximum no[i]> noMaximum? Machine Translated by Google


Refer to the distance values in the list one by one using the index of the array. Compare that distance with the longest distance. 2 Next, refer to the first distance in the list. Display the Longest distance after all distance values in the list have been referenced. Mind Test list. 4 Repeat the same steps with the other distances in The process implemented in the program to find the longest distance is as follows: The JavaScript program and output are shown in Figure 3.1.31. If the distance is greater than the initial value, then the longest distance has changed to the first distance. Otherwise, the initial value of the longest distance will remain. 1 Set the initial value for the longest distance. Get the lowest value such as –1 to represent the initial value for the longest distance. If the referenced distance is longer than the Longest distance, then make the referenced distance value the current Longest distance. 3 Compare the first distance with the initial value of the longest distance. Then, try to follow the process to get the maximum value of a list as shown in Example 10. (among 5 students): “ + longest distance + </script> } distance. for(i = 0; i < bilDistance; i++) { CHAPTER 3 Web-Based Programming 151 Figure 3.1.31 JavaScript program and output (getting the longest distance to school) bilDistance = distance.length; Considered -1 is the longest distance </html> 6 7 8 9 4 5 3 { length to count the number of distance values in the list if (distance[i] > Longestdistance) List of distances taken by 5 <body> students to come to school Specify the maximum value for the list of values shown above. distanceLongest = distance[i]; <html> } “km”); </body> var distance = [10,8,8,12,5], Longest distance = -1, i, document.write("The longest distance taken by students to school <script> Machine Translated by Google


The flow chart for Example 10 is shown in Figure 3.1.32. Science Innovation Computer Display the longest distance uum-news/ 3950-i-ria List of distances taken by 5 students for TRUE Malaysia–Thailand showcased innovative products covering the categories of computer engineering, computer science and programming, multimedia, data management and 2017-draws-record FAKE among the students. is the distance referred to bilDistance = distance.length http:// www.uum.edu. storage. 152 Computer Science Form 5 distance.length to count the number of distance values in the list FAKE (I-RIA) was held by the University 5 students):" distance[i]> Display the text "The longest distance taken by the th student from the latest value of assign a prefix value to Longest distance. Innovative Expo participation Finished Compare the distances referred to either TRUE Reason: referenced distance distance = [10,8,8,12,5] This expo becomes a platform for educational institutions in Malaysia and the Indonesian Region– in list. Start i = 0 i < bilDistance? my/ index.php/ en/ North Malaysia and the state government of Kedah to unearth innovative talents i = i + 1 Longest distance now Longest distance = ÿ1 Source: school (between Longest distance considered -1 is the Longest distance (choose the shortest distance) Longest distance? Research, Invention and Application Figure 3.1.32 Flow chart (getting the longest distance to school) On May 8, 2017, LONGER than Longest distance distanceLongest = distance[i] come to school LONGER Machine Translated by Google


Figure 3.1.33 The process of finding the minimum value } </html> <script> document.write(noMinimum); <body> if (no[i]< noMinimum) Assign a prefix value to noMinimum. } Reason: The referenced number is LESS than the current value of noMinimum no.length to count the number of numbers in the list noMinimum is now the number being referenced. var no =[5,-1,4,12,8], noMinimum = 999, i, bilNumber = no.length; Give a minimum initial value for(i = 0; i < bilNumber; i++) LESS than noMinimum Considered 999 is noMinimum (choose the highest number) Compare the numbers referred to either MORE </script> </body> Figure 3.1.34 JavaScript program and output (getting the minimum value) noMinimum = no[i]; <html> CHAPTER 3 Web-Based Programming 153 { { Get the minimum value The JavaScript program and output are shown in Figure 3.1.34. latest Compare the values in the list with the minimum initial value Example 11 shows the process of finding the smallest number (minimum value) in a list of numbers. Getting the Minimum Value EXAMPLE 11 There is only one comparison process, that is: comparison of the value referred to in the list is smaller than the minimum value. The minimum value refers to the smallest value in a list of values. The process of finding the minimum value can be implemented as shown in Figure 3.1.33. Machine Translated by Google


EXAMPLE 12 The process of finding the minimum value can be used to find other values such as the lightest box and the shortest river. The JavaScript program and output are shown in Figure 3.1.36. The process implemented in the program to find the weight of the lightest bag is as follows: Example 12 shows the weight of school bags (in kg) for six students taken and recorded as in the list. The program will be able to determine the weight of the lightest bag among the bags. 1 Set the initial value for the weight of the lightest bag. Get the highest value such as 999 to represent the initial value of the lowest weight. The flow chart for Example 11 is shown in Figure 3.1.35. Mind Test billNumber = no.length FAKE Figure 3.1.35 Flow chart (getting the minimum value) noMinimum is now the number being referenced. i = 0 How to get its minimum value? TRUE Reason: Referenced number no = 5,-1,4,12,8 Assign a prefix value to noMinimum. TRUE i < billNumber? Start noMinimum = no[i] FAKE no.length to count the number of numbers in the list no[i]< noMinimum? Display noMinimum Compare the numbers referred to either MORE Assumed 999 is noMinimum (choose the highest number) LESS than the current value of noMinimum The following shows a list of values. 7 2 3 5 6 9 4 154 Computer Science Form 5 noMinimum = 999 LESS than noMinimum Finished i = i + 1 Machine Translated by Google


<script> <html> “kg”); { billWeight = weight.length; CHAPTER 3 Web-Based Programming 155 for(i = 0; i < billWeight; i++) { Figure 3.1.36 JavaScript program and output (getting the weight of the lightest bag) if (weight[i] < weightLightest) document.write("Lightest bag weight (among 6 students): " <body> + weightLightest + </script> } weightLightest = weight[i]; var weight = [3,3,2,5,4,5], weightLightest = 999, i, </html> } </body> weight.length to count the number of weight values in the list If the referenced weight value is less than the lowest weight, then make the referenced weight value the latest lowest weight. Display the lowest weight after all weight values in the list have been referenced. 4 Repeat the same steps with the other weights in the list. Refer to the bag weight values in the list one by one using the index of the array. Compare that weight with the lowest weight earlier. Considered 999 is the lowest weight 3 Compare the first weight with the initial value of the lowest weight. If the value of the weight is smaller than the initial value, then the lightest weight has changed to the first weight. Otherwise, the initial value of the lowest weight will remain. 2 Next, refer to the first weight in the list. School bag weight list of 6 students Machine Translated by Google


School bag weight list lightest weight? weight = [3,3,2,5,4,5] Finished weight[i] < display i = 0 Lightest weight = 999 TRUE which is referred to as either LIGHTER than Reason: referenced weight Flow Chart For Finding Maximum Value And Minimum Value the lowest. TRUE FAKE i = i + 1 Figure 3.1.37 Flow chart (getting the lightest bag weight) of 6 students Lightest weight Start Considered 999 is the lowest weight (choose the largest number) FAKE Lightest weight weightLightest = weight[i] 156 Computer Science Form 5 billWeight = weight.length weight.length to count the number of weight values in the list LIGHTER than the latest value for the lowest weight Compare weight i < bilWeight? The lowest weight is now the weight referenced in the list. assign a prefix value to weight ACTIVITY 5 Build a flow chart for an application that has a list of cake making costs for six types of cakes, namely 3.00, 2.50, 1.50, 3.10, 4.00, 2.00 and find and display the highest (maximum) and lowest (minimum) cake costs. The flow chart for Example 12 is shown in Figure 3.1.37. Individual Work Machine Translated by Google


1 Sum up the values in the list of values 3 The mean value is calculated by dividing the total value by the number of values in the list (Formula: Mean = Total/Number) 2 Get the number of values in the list Mean refers to the average value in a list of values. To get the average, the following are the steps that need to be implemented: Example 13 shows the process of calculating and obtaining the average value (mean) of a number of numbers. An example JavaScript program and output are shown in Figure 3.1.38(a) and 3.1.38(b). The numbers are entered by the user and then the program will calculate the sum of the numbers. The average will be calculated using the formula average = total ÷ number. To calculate the average value, the total and number values need to be obtained first. The formula for sum is sum = sum + no while the formula for number is numerator = numerator + 1. Getting the Mean Value EXAMPLE 13 document.write(average); Figure 3.1.38(a) JavaScript program (getting the mean value) counter = counter + 1; </html> no = parseInt (prompt("Enter a number:")); repeat = confirm("Repeat again?"); <html> </body> Formula: sum/numerator Initializes the counter, sum and average (ie the initial value is 0) sum = sum + no; Calculate the average value. var no, counter=0, repeat=false, sum=0, average=0; do Counting the number (by adding 1 to the numerator) and calculating the sum (by adding the value to the sum) number entered by <body> <script> }while(repeat == true); user (prompt) and ensure integer value (parseInt) CHAPTER 3 Web-Based Programming 157 </script> { average = sum/counter; Reason: There are no more values to calculate Machine Translated by Google


Ask the user to click "OK" if the user wants to enter the number again Asking the user to click "Cancel" if the user wants to finish entering the number. Displays the average value. Asks the user to enter a number. Asks the user to enter a number. 158 Computer Science Form 5 Figure 3.1.38(b) Output (getting the mean value) Machine Translated by Google


Assigns initial values to counters, sums and averages. Input the number represented by no Display the average next text "Enter a number:" CHAPTER 3 Web-Based Programming 159 repeat value = true? Calculate the average value. counter = 0 repeat = false Counting the number numerator = numerator + 1 (by adding 1 to the numerator) and calculating the sum (by adding the value to the sum) Start FAKE Figure 3.1.39 Flow chart (getting the mean value) Flow Chart for Finding the Mean Value Display a confirmation box with the text "Retry again?" average = 0 Enter a repeat value for number repeats (ie true or false) Formula: total = total + no sum = 0 average = sum/numerator Finished Display the accompanying prompt box TRUE Sum/counter Repeat if you want to receive a value ACTIVITY 6 The flow chart for Example 13 is shown in Figure 3.1.39. Objective: Show the steps to find the mean value from a list of values. The dengue epidemic is an increasingly contagious epidemic in Malaysia. Every year, the total number of cases involving dengue outbreaks is increasing. The bar chart on the next page has shown the total number of dengue outbreak cases in five states in Malaysia in 2015. Individual Work Machine Translated by Google


Number of cases (thousands) Based on the graph above, draw a flow chart showing the steps to get the mean value Science Innovation Example 14 shows the process of counting the number of names entered by the user. or the average for the total number of dengue outbreak cases in five states in Malaysia in 2015. Computer The program will count the number of names using the formula counter = counter + 1 as soon as the name is entered by the user. The JavaScript program and output are shown in Figures 3.1.40(a) and 3.1.40(b). 25000 The Total Number of Dengue Outbreak Cases in Five States in Malaysia in 2015 15000 Selangor 5115 Kelantan 45000 40000 5000 10000 50000 Kuala Lumpur 43560 30000 11291 silver 0 35000 Johor 20000 5673 6180 http:// www.moh.gov.my/ index.php/ pages/ view/ 1674 Hilman Nordin from the University The increase in the number of deaths due to the dengue epidemic has prompted application developers in Malaysia, ie Portal of the Ministry of Health Malaysia Malaya to develop the iContageo application. This application helps Malaysians to anticipate the location of "hotspots" for dengue outbreaks based on complaints from citizens. Hilman Nordin is one of the people involved in developing the application. https:// govinsider.asia/ inclusive gov/ malaysia-launches-dengue alertsapp/ Source: Source: 160 Computer Science Form 5 Getting the Count Value 2 The count value is calculated by increasing the counter by 1 for each value reached or referenced (Formula: counter = counter + 1). To calculate and get the count value, the following are the steps that need to be implemented: 1 Uses a representation as a counter and assigns the prefix value of the counter as 1. 3 Displays the final value of the counter, which is the count value. Count counts the number of values in a list. EXAMPLE 14 Machine Translated by Google


Accepts any value (example: name) <html> repeat = confirm("Repeat again?"); </body> </ html> counter = counter + 1; </script> <body> <script> var name, counter = 0, repeat = false; do }while(repeat == true); Gives an initial value to the counter (ie the initial value is 0) Figure 3.1.40(a) JavaScript program (getting the value of count ) value Reason: There are no more values to calculate next { Repeat if you want to accept name = prompt("Enter your name:"); document.write(counter); CHAPTER 3 Web-Based Programming 161 Counting numbers (by adding 1 to the counter) Asks the user to enter a name. Asks the user to click "OK" if the user wants to enter the name again. Asks the user to enter a name. Machine Translated by Google


Figure 3.1.40(b) Output (getting the count value) 162 Computer Science Form 5 Asks the user to click "OK" if the user wants to enter the name again. Asking the user to click "Cancel" if the user wants to end the name entry. Displays the number of names that have been entered. Asks the user to enter a name. Machine Translated by Google


ACTIVITY 7 Individual Work The flow chart for Example 14 is shown in Figure 3.1.41. 1 Open the Notepad software. Part 1: Do this activity in the computer lab. Display the accompanying prompt box Input name Display the counter Accepts any value (example: name) CHAPTER 3 Web-Based Programming 163 FAKE Figure 3.1.41 Flow chart (getting the count value) Gives an initial value to the counter (initial value is 0) and an initial value to repeater is false counter = 0 numerator = numerator + 1 Calculates the count (by adding 1 to the counter) Start Finished Enter a repeat value to repeat the name Reason: There are no more values to calculate Repeat if you want to receive the next value Flow Chart for Finding Count Values Display a confirmation box with the text "Retry again?" repeat = false text “Enter your name:” repeat value = true? TRUE Machine Translated by Google


repeat = confirm("Next participant?") ; do <body> <script> var name, counter=0, repeat=false; }while(repeat==true); participant:”); counter=counter+1; counter); </ script> </ body> </ html> <html> + 164 Computer Science Form 5 name = prompt("BESTARI SCHOOL CHARITY RUN \nEnter name document.write("Number of participants registered so far: " { Students can enter several participant names and make sure the number (output) displayed is correct. 5 Here is an example of the output produced: 2 Draw a flow chart for the program that has been built in Part 1, which is a program to count and get the number of participants in the Bestari School charity run based on the names of the registered participants. 1 Take a new piece of paper. Chrome. 4 Open the Activity7.html file through a web browser such as Internet Explorer or Google 2 Type the given HTML and JavaScript program: Part 2: 3 Save as Activity7.html Machine Translated by Google


Constraints 12 front 5 -1 -1 12 -1 Advantage 5 Use of push() and shift() in JavaScript 5 Mind Test Concentration of values in a queue structure (queue) in front back back In your opinion, how can the queue function be applied in the queue number system at a bank? back push(5) push(-1) in front in front back shift( ) CHAPTER 3 Web-Based Programming 165 push(12) 1 enqueue – Inserting data into the queue Figure 3.1.43. example above. •The initial value is entered through the back of the array memory space. Queue operations can be performed using the 'push()' and 'shift()' functions in Figure 3.1.42 or 'unshift()' and 'pop()' for array objects as shown in 2 The push(-1) command will insert the value -1 from the back into the queue, that is after the value 5 is inserted. The same goes for the push(12) command. 3 The shift() command will output the first value entered, which is the value 5 in To understand the concept of queuing, try students to imagine a queue number system at a bank counter. Customers will be called and served according to the order of ticket number taken. These four functions are very easy to use by simply calling the functions. •The initial value is issued through the front of the array memory space. Queue is a linear data structure, which is the accumulation of values in memory space in an orderly manner. Queue can discard the old value, which is the value that was entered first. This method is called FIFO (first-in, first-out). These functions are not suitable for use if: There are two important operations in the queue, namely: •Having a large queue (having a long queue or a large queue value) Queue operation 1 The push(5) command will insert the value 5 from the back into the queue. 2 dequeue – Removes old data in the queue •The values need to be moved each time the 'shift()' function is called and used. Description: because its implementation uses an array. Machine Translated by Google


Example 15 shows the stacking of numbers into a list known as a queue. using the push() subroutine. Next, the process of removing numbers from the queue is also performed using the shift() method subroutine. The first number placed will be removed from the queue. The JavaScript program and output are shown in Figure 3.1.42. EXAMPLE 15 noNew = -1; numbers 5, –1, 12 into the Queue. </html> document.write(“<br>”,queueNo); </script> queueNo.push(noNew); var queueNo = [], noNew, noExit; document.write(“<br><br>List of Latest Numbers in Queue:<br>----------------------”); document.write(“<br>New Number Entered: “, noNew); noExit = queueNo.shift(); 166 Computer Science Form 5 <script> noNew = 12; queueNo.push(noNew); The shift( ) function to remove numbers from Figure 3.1.42 JavaScript program and output (accumulation of values in the queue structure - subroutine <html> </body> document.write(“<br>New Number Entered: “, noNew); The push ( ) function is used to place document.write(“<br><br>List of Latest Numbers in Queue:<br>----------------------”); document.write(“<br>”,queueNo); noNew = 5; Queue is empty document.write(“<br><br>Issued Number: “, noIssued); queueNo.push(noNew); document.write(“<br>New Number Entered: “, noNew); Queue push() and shift()) <body> Machine Translated by Google


Enter the value into the Queue queueNo.push( ) Input value (noNew = -1) Function: shift ( ) is used to remove numbers from Show value CHAPTER 3 Web-Based Programming 167 Display the values in the Queue Remove the value of queueNo.shift( ) Set Queue empty queueNo = [ ] Queue is empty Display the text “New Number Entered” Enter the value into the Queue queueNo.push( ) Start Queue Input value (new no = 12) Function: push ( ) is used to put numbers 5, –1, 12 into the Queue Enter the value into the Queue queueNo.push( ) ENDED Show value Input value (new no = 5) Display the values in the Queue Display the text “New Number Entered” Show value Figure 3.1.43 Flow chart (accumulation of values in the queue structure) Display the text “New Number Entered” •The initial value is entered through the front of the array memory space. •The initial value is issued through the back of the array memory space. The flow chart for Example 15 is shown in Figure 3.1.43. Use of unshift() and pop() in Javascript Machine Translated by Google


12 -1 5 5 12 -1 using the unshift() subroutine. Next, the process of removing numbers from the queue is also implemented using the pop() method subroutine. The first number placed will be removed from the queue. The JavaScript program and output are shown in Figure 3.1.44. Example 16 shows the assembling of numbers into a list known as a queue. noNew = 12; exit no = queueNo.pop(); back unshift(-1) <script> 168 Computer Science Form 5 Queue is empty queueNo.unshift(noNew); Functions: front 5 back </body> (Queue):<br>-----------------------”); document.write(“<br>”,queueNo); Function: unshift ( ) is used to put numbers 5, –1, 12 into the Queue queueNo.unshift(noNew); from Queue in front document.write(“<br><br>Issued Number: “, noIssued); in front var queueNo = [], noNew, noExit; queueNo.unshift(noNew); <body> document.write(“<br>New Number Entered: “, noNew); front -1 unshift(12) pop ( ) to pop a number </html> </script> back noNew = -1; <html> document.write(“<br>”,queueNo); document.write(“<br>New Number Entered: “, noNew); document.write(“<br><br>List of Latest Numbers in Queue (Queue):<br>-----------------------”); back pop( ) noNew = 5; document.write(“<br>New Number Entered: “, noNew); unshift(5) document.write(“<br><br>List of Latest Numbers in Queue 2 The command unshift(-1) will insert the value -1 from the forward direction into the queue. 1 The command unshift(5) will insert the value 5 from the front direction into the queue. Description: The same goes for the unshift(12) command. 3 The pop() command will output the earliest value entered, which is the value 5 even though 5 is at the back of the queue. EXAMPLE 16 Machine Translated by Google


Input value (new no = 5) Figure 3.1.44 JavaScript program and output (accumulation of values in the queue structure – unshift() and pop() subroutines) Display the text “New Number Entered” Show value Enter the value into the Queue queueNo.unshift( ) Display the text “New Number Entered” A Start Set Queue is empty queueNo = [ Input value (noNew = -1) Show value Display the values in the Queue Display the text “New Number Entered” Show value ] Enter the value into the Queue queueNo.unshift ( ) Queue is empty CHAPTER 3 Web-Based Programming 169 Function: unshift ( ) is used to put the numbers 5, –1, 12 into the Queue Enter the value into the Queue queueNo.unshift ( ) Input value (new no = 12) The flowchart for Example 16 is shown in Figure 3.1.45. Machine Translated by Google


As previously learned, client scripting programs can be written using JavaScript. Client JavaScript programs can be written and embedded in HTML documents and interpreted by browsers. In this topic, students will use constants, variables and different types of data in bubble sort, selection sort, binary search programs, get maximum, minimum, average and count values. So is the program in the concentration of values in the queue. Example: Examples of constant values: A constant is a memory space used to store temporary values while the program is being processed. A constant is like a variable but its value cannot change. The value cannot change because the specified value is a value that has been set in the program. A variable is a memory space used to store temporary values while the program is being processed. Its value can vary according to the use of the variable or the instructions to the variable. Each variable will be named according to the stored value. The name given to a variable is known as an identifier. •The number of days in a week, which is seven days. Const is a keyword used in JavaScript to refer to a constant. •Student's name. The name of the variable that can be given is the name of the Student. •The value of pi (ÿ), which is 3.142 (written in the form of three decimal points). •The value of employee wages. The variable name that can be given is salaryEmployee. 3.1.3 Programs That Have Different Constants, Variables, and Data Types for Client Scripting Languages Remove the value from the Queue Display the values in the Queue Figure 3.1.45 Flow chart (accumulation of values in the queue structure) Finished queueNo.pop( ) A 170 Computer Science Form 5 Constant Variables Machine Translated by Google


A data type is a type of value or various sets of data used in a program. Table 3.1.2 shows the basic data types in JavaScript. Pupils can perform processes such as sorting (bubble sort method or selection sort), finding specific values (binary search method), finding the maximum value (max), finding the minimum value (min), calculating the average value (mean) and calculating the number of values (count) to various types of values or data that have been described before. 100.50 Boolean "BMW 318i" The number of household members is entered into the population census variable and then sorted in ascending order using bubble sort. The JavaScript program and sample output are shown in Table 3.1.3. Example scripting program for bubble sort (Bubble Sort) 5 Data types false Data types true Number "Ali bin Abu" Sample data Number String (String) Example 17 shows a list of the number of household members in the population census taken and recorded. 2 Data Types for (i=0; i<billNumber-1; i++) </script> Table 3.1.3 JavaScript program example and bubble sort output (Number data type) temporary var = censusPopulation[0]; if (censusPopulation[j] > censusPopulation[j+1]) { var bilNumber = censusPopulation.length, i, j; document.write(population census); Table 3.1.2 Basic data types in JavaScript } censusPopulation[j] = censusPopulation[j+1]; document.write(population census); </html> document.write("List of the number of household members in the census (before sorting):<br>"); { temporary = censusPopulation[j]; <html> census (after sorting in ascending order - Bubble Sort):<br>"); } document.write("<br><br>List of the number of house members in censusPopulation[j+1] = temporary; </body> CHAPTER 3 Web-Based Programming 171 { var censusPopulation=[5,1,4,3,2]; 1 for (j=0; j<bilNumber-i-1; j++) } <body> <script> EXAMPLE 17 Machine Translated by Google


Description: } for (j=0; j<numberPatients-i-1;j++) { Table 3.1.4 Examples of JavaScript programs and bubble sort output (String data type) } “Ah Chong”]; 1 var billPatient = namePatient.length, i, j; temporary var = namePatient[0]; document.write("List of patients in the HEALTHY Clinic: (before sorting):<br>"); document.write(Patient name); document.write("<br><br>List of patients in Klinik HIHAT: (after sorting in ascending order- Bubble Sort):<br>"); for (i=0; i<numberPatients-1; i++) { 172 Computer Science Form 5 temporary=PatientName[j]; Patientname[j] = Patientname[j+1]; patientname[j+1] = temporary; String <html> <body> <script> var patient name = [“Siti Aminah”, “Ramasamy A/L Muthusamy”, } document.write(Patient name); </script> </body> </ html> if (PatientName[j] > PatientName[j+1]) { Sample output 1 Receive a list of the number of house members of type number. 2 Sort the number of household members in ascending order using the bubble sort method. Example 18 shows a list of patient names of type String stored in the PatientName variable and then sorted in ascending alphabetical order using the bubble sort method. The JavaScript program and sample output are shown in Table 3.1.4. Data types Example scripting program for Bubble Sort 2 EXAMPLE 18 Machine Translated by Google


Description: Table 3.1.5 Examples of JavaScript programs and selection sort output (String data type) CHAPTER 3 Web-Based Programming 173 Data types 2 Sort the names in ascending order alphabetically using the bubble sort method. 1 Receives a list of names of type String. Example of scripting program for selection sort (Selection Sort) 2 Example 19 shows a list of patient names of type String stored in the Patientname variable and then sorted in ascending alphabetical order using the select sort method. The JavaScript program and sample output are shown in Table 3.1.5. Sample output String EXAMPLE 19 if (PatientName[h] < PatientName[min]) { temporary = patientname[i]; <body> <script> var patient name=["Siti Aminah", "Ramasamy A/L Muthusamy", "Ah Chong"]; 1 var i,j,min,temporary; var billPatient = namePatient.length; document.write("List of patients in Klinik HIHAT: } if (min != i){ mean = i; for(j = i+1; j < billPatient; j++) { } <html> } for (i = 0; i < billPatients - 1; i++) { document.write("<br><br>List of patients in Klinik HIHAT: (after sorting in ascending order - Select Sort):<br>"); patientname[i] = patientname[min]; patientname[min] = temporary; mean = j; } document.write(Patient name); </script> </ body> </html> (before sorted):<br>"); document.write(Patient name); Machine Translated by Google


Description: 174 Computer Science Form 5 Table 3.1.6 Examples of JavaScript programs and binary search output (String data type) Data types 2 Sort the names in ascending order alphabetically using the select sort method. 1 Receives a list of names of type String. 2 Next, the process of searching for a patient named "Ramasamy A/L Muthusamy" is carried out using the binary search method. The JavaScript program and sample output are shown in Table 3.1.6. document.write(" (still in queue.)"); 3 String Example 20 shows a list of patient names of type String stored in the Patientname variable. Sample output Example of binary search scripting program (Binary Search) EXAMPLE 20 } } { </html> if (PatientName[MiddleIndex]==PatientNameSearch) document.write("List of patients in the HEALTHY Clinic :<br>"); otherwise if (PatientName[MiddleIndex]<PatientName) document.write("<br><br>Searched Patient Name: ", Search Patient name); while (Patient name [Middle index] != Patient nameSearch && </body> <script> if (PatientName[MiddleIndex] > PatientNameSearch) indexInitial = indexMiddle + 1; Middle index = Math.floor((End index + Start index)/2); indexEnd = indexMiddle - 1; var indexInitial = 0, indexEnd = namePatient.length – 1, document.write(Patient name); { { } StartIndex < EndIndex) <html> { var patient name=["Ah Chong", "Ramasamy A/L Muthusamy", "Siti Aminah"]; 1 var namePatientSearch="Ramasamy A/L Muthusamy"; </script> { <body> } Middle index = Math.floor((End index + Start index)/2); } Machine Translated by Google


Data types 3 Message "still in queue." will be displayed if the patient is still in the patient list. 2 Search for a patient named “Ramasamy A/L Muthusamy” using binary search. An example of a scripting program for stacking values in a queue structure 1 Description: 1 Has a list of patient names of String type. Example 21 shows the numbers that are 5.5, –1.3, and 12.95 of double type placed into the Queue using the unshift() function. Next, the pop() function is used to remove the number in the Queue, which is the number 5.5 (number) placed first. The JavaScript program and sample output are shown in Table 3.1.7. Sample output Number exit no = queueNo.pop(); 2 CHAPTER 3 Web-Based Programming 175 <body> <script> var queueNo = [], noNew, noExit; document.write(“<br>”,queueNo); </script> </ body> </html> Table 3.1.7 Example of a JavaScript program and output in setting values in a Queue (Number data type) document.write(“<br><br>List of Latest Student Numbers in Queue:<br>----------------------”); document.write(“<br>”,queueNo); <html> document.write(“<br><br>Student Number Released: “, noRelease); document.write(“<br><br>List of Latest Numbers noNew = 12.95; queueNo.unshift(noNew); document.write(“<br>Incoming Student Number: “, new no); noNew = –1.3; queueNo.unshift(noNew); document.write(“<br>Incoming Student Number: “, new no); In Queue:<br>----------------------”); noNew = 5.5; queueNo.unshift(noNew); document.write(“<br>New Number Entered: “, noNew); EXAMPLE 21 Machine Translated by Google


Description: 176 Computer Science Form 5 <html> <body> <script> var queueName = [], Newname, Exitname; New name = “Siti Maimunah”; queueName.unshift(NewName); document.write(“<br>Newly Entered Patient Name: “, newname); New name = “Ah Chong”; queueName.unshift(NewName); document.write(“<br>Incoming Patient Name: “, newname); document.write(“<br><br>List of Latest Patient Names in Queue):<br>----------------------”); document.write(“<br>”,queueName); Table 3.1.8 Examples of JavaScript programs and outputs for setting values in Queue (String data type) </script> </ body> </ html> New name = “Ramasamy A/L Muthusamy”; queueName.unshift(NewName); document.write(“<br>Incoming Patient Name: “, newname); Exit name = queueName.pop(); 2 document.write(“<br><br>Patient Name Released: “, nameRelease); document.write(“<br><br>List of Latest Patient Names in Queue):<br>----------------------”); document.write(“<br>”,queueName); Data types unshift(). 1 Put a list of numbers, namely 5.5, –1.3 and 12.95 into a Queue using the command Example 22 shows patient names such as "Siti Maimunah", "Ramasamy A/L Muthusamy" and "Ah Chong" are placed into the Queue using the unshift() function. Next, the pop() function is used to remove the name in the Queue, which is "Siti Maimunah" (first name) placed. The JavaScript program and sample output are shown in Table 3.1.8. String 1 Sample output An example of a scripting program for stacking values in a queue structure 2 Remove the earliest number entered into the Queue using the pop() command. EXAMPLE 22 Machine Translated by Google


Description: ACTIVITY 8 Part 1: Spicy sour paste items of type String. ÿ There is a list of retail items that determine the retail items subject to Goods and Services Tax (GST) (taxable) and retail items not subject to GST (non-taxable) as published by the Royal Malaysian Customs Department as follows: ÿ 2 Remove the first name entered into the Queue using the pop() command. Turkey Zero GST Rate 0% (c) displays the message "Zero GST Rate 0%" if the item name in (b) Build a complete flow chart for the program that was built in Part 1. Item name Tamarind Source: Royal Malaysian Customs Department Build a client scripting program that can execute the following commands: Chicken Standard GST Rate 6% ÿ Sample output Mind Test ÿ (b) find the name of the item, namely "Chicken" by using binary search. found. Gelatin 1 Put a list of String type into a Queue using the unshift() command. ÿ Binary Search Flow Chart Abalone (Updated on January 2, 2015) Various seafood/ meat/vegetable balls ÿ Objective: Show the steps to find a value from a list of values using the binary search method. ÿ (a) store a list of item names in a named variable Part 2: Individual Work Mentakab Zone Level Netball Competition, Pahang. If the group names are sorted by array, how many items are in the array Twenty-four groups have qualified to enter which can be identified by binary search to find out the specific location of a team in the array? CHAPTER 3 Web-Based Programming 177 Machine Translated by Google


Input Your Name Sequentially Start 178 Computer Science Form 5 Control Structure Finished Figure 3.1.46 Control structure in JavaScript Repeat Table 3.1.9 Examples of pseudocode and flowcharts (Sequential control structure) Print "Hello" and Your Name Options 3 Print "Hello" and Your Name 1 Start Pseudocode 2 Input Your Name Flowchart 4 End 3.1.4 Use of Control Structures in Client Scripting Languages Examples of controls: 6 •Must insert the ATM (Auto Teller Machine) card first before entering the pin number valid Sequential control structure means that instructions or statements are executed in the order as directed in a program code without checking any conditions. Table 3.1.9 is the syntax of the sequence control structure shown by the pseudocode and flowchart: • Repeat entering the pin number three times if the entered pin number is not Description: A control structure will control the flow of a program within a block of program code. This statement will determine whether the statement will be executed or not, including repeating the statement within a block of code. 1 Instructions are executed one by one, i.e. line by line. 2 Start with Name Input. •Continue the ATM transaction if the bank customer enters a valid pin number. 3 Next print "Hello" along with the Name. Figure 3.1.46 shows the control structure in JavaScript. for authentication when using an ATM machine. Sequence Control Structure Machine Translated by Google


Example Output Program Current year = 2017; 1 + age); 4 Example 23 shows a JavaScript program that uses a sequence control structure whose statements are executed one at a time to receive a name and display the name again as shown in Table 3.1.10. Table 3.1.11 shows an example of a JavaScript program and output to receive 2 integer type values, namely the current year and the year of birth. Next, the age count is made based on those years and the age is displayed at the end of the program. 2 Then print the name again. age = yearCurrent - yearBirth; 3 Program yearBirth = 1973; 2 1 The program receives the name, which is Siti Aminah. Example Output your name="Siti Aminah"; 1 Description: EXAMPLE 23 <head> <body> <head> <body> </head> </body> </script> </head> Table 3.1.11 Example JavaScript program and output (Sequence control structure) Table 3.1.10 Example JavaScript program and output (Sequence control structure) var yourname; var yearCurrent, yearBirth, age; <script> CHAPTER 3 Web-Based Programming 179 <script> </html> document.write("Hello " + your name); 2 </script> <html> </body> document.write("Your Age: " <title>Sequence Control Structure</title> <title>Sequence Control Structure</title> <html> </html> Machine Translated by Google


/ * Arithmetic operator symbols 2 Next, the program accepts the year of birth, which is 1973. 3 Program to calculate age by performing subtraction operation. Reject 1 The program accepts the current year, which is 2017. % Mix Share Multiplication Operation 4 Finally, the program displays the age value. – + Modulus (remainder to division) Did you know? You Optional Control Structure Description: Table 3.1.12 shows the arithmetic operators that can be used in JavaScript. An optional control structure requires a conditional statement that will execute a statement or a block of code enclosed with “{” and “}” in JavaScript. Conditional statements are implemented using statements called logical expressions that consist of relational operators. • discount=(50/100)*100; Data input example (interactively) • window.alert("Hello " + yourname); Sample data input (defined in the program) Among the statements found in the control sequence structure are data input, processes such as calculations (arithmetic operations), and output display or printing. Data input can be received from the user (interactively) or set in the program. • Current year=2017; • document.write("Your Age: " • your name = prompt("Enter your name: "); Example display: • age=yearDuring-yearBirth; + age); Examples of arithmetic operations JavaScript is a programming language developed by Brendan Eich. https:// www.w3.org/ of_JavaScript Source: The script's syntax is almost similar to Java, so it is given the name Javascript. Table 3.1.12 Arithmetic operators that can be used in JavaScript wiki/ A_Short_History_ JavaScript can process numbers that modify the content of a program. During its development, JavaScript was known as Mocha and the Livewire facility, then Livescript. community/ web/ 180 Computer Science Form 5 Machine Translated by Google


Finished FAKE CHAPTER 3 Web-Based Programming 181 Start Statement 2 ) if Statement 1 TRUE Table 3.1.14 Pseudocode and flowchart ( Table 3.1.13 Relational operators found in logical expressions TRUE terms? Statement if if... Table 3.1.13 shows the relational operators that can be found in logical expressions. •if...else... A logical expression will produce a Boolean value, i.e. true or false to determine whether a statement or a block of code will be executed or not. Two JavaScript statements used for the option control structure. If the condition in if is true, the statement will be executed. If otherwise, the statement will not be executed and will be skipped. Table 3.1.14 is the syntax of the optional control structure shown by the pseudocode and flowchart. Relational Operator Symbols Greater than <= Not the same as 1 Start >= Flowchart Greater than or equal to Smaller than 2 Statement 1 == Requirement != 3 If the Condition is TRUE Less than or equal to 3.1 Statement 2 4 End Pseudocode Equal to < > Machine Translated by Google


(fulfills the if condition) <head> </body> Student: "); <html> 1 document.write("You are </title> (does not meet the if condition) 2 Next, determine if the student number is equal to 123. <title>Option Control Structure Example 24 shows the use of if in a JavaScript program where the received student number is tested if the student number is 123. The message "You are a student at Taman ABC School" will be displayed if the student number is 123, and no message will be displayed otherwise (student numbers other than 123). The JavaScript program and output are shown in Table 3.1.15. if (noStudents == 123) 2 1 The program accepts student numbers. <body> Example Output <script> ABC Park School students"); </head> 3 3 If the student number is equal to 123, "You are a student of Taman ABC School" will be displayed (meeting the if condition). If the student number is not equal to 123, no command is performed (not meeting the if condition). </html> Program noStudent = prompt("No. </script> var noStudent; Description: EXAMPLE 24 Table 3.1.15 Examples of JavaScript programs and output if ( 182 Computer Science Form 5 ) Machine Translated by Google


Many conditions in if statements are available and can be combined together with else and else...if. If the condition is not met (if the condition is false), the else section or else...if will be referenced to identify the code block being executed. Table 3.1.16 is the syntax of the if...else control structure shown by the pseudocode and flowchart. 1 Start Program Flowchart 4 End (fulfills the if condition) 2 Statement 1 Example Output 3 3.1 Statement 2 Vice versa 4 3 If the Condition is TRUE Example 25 shows the use of if...else in a JavaScript program, that is, the received student number will be tested whether the student number is 123 or not. The message "You are a student of Taman ABC School" is displayed if the student number is 123 and the message "You are NOT a student of Taman ABC School" is displayed if the student number is not 123. The JavaScript program and output are shown in Table 3.1.17. Pseudocode 3.2 Statement 3 Statement if...else document.write("You are a student Finished <title>Option Control Structure <body> Table 3.1.17 Examples of JavaScript programs and output (if...else) FAKE document.write("You are NOT a student var noStudent; TRUE terms? </html> Statement 2 <head> Table 3.1.16 Pseudocode and flowchart ( </title> ABC Garden School"); ) ABC Garden School"); TRUE <script> otherwise noStudent = prompt("Student No.: "); 1 </script> Start if...else </body> <html> Statement 3 if (noStudents == 123) 2 </head> Statement 1 CHAPTER 3 Web-Based Programming 183 EXAMPLE 25 Machine Translated by Google


Description: 184 Computer Science Form 5 Table 3.1.18 Logical operators in logical expressions 3 If the student number is 123, "You are a student of Taman ABC School" is displayed (fulfills the if condition). Program ! (does not meet the if condition) Requirement Logical Operator Symbols Example Output OR 2 Determine whether the student number is 123. NOT The JavaScript program and output are shown in Table 3.1.19. AND 1 The program accepts student numbers. Example 26 shows that the exam score must be between 0 and 100. Therefore, to determine whether the entered score is between 0 and 100, the logical operator "&&" should be used. Example: if (Examscore >= 0 && Examscore <=100). 4 On the other hand, "You are not a student at Taman ABC School" will be displayed (does not meet the if condition). || && In an if...else statement, two or more Boolean conditions can be tested simultaneously by combining Boolean conditions through logical operators. Commonly used logical operators are AND, OR and NOT. Table 3.1.18 shows the logical operators that can be found in logical expressions. The AND logical operator is used when two or more Boolean conditions need to be combined and all conditions need to be true before executing the next statement. Logical Operator AND EXAMPLE 26 Machine Translated by Google


} else { if (Examscore >= 80 && Examscore <= 89) { CHAPTER 3 Web-Based Programming 185 } grade = "Grade E"; <body> <script> var exam score = 67, grade; if (Examscore >= 0 && Examscore <= 39) { { { if (Examscore >= 45 && Examscore <= 49) { } { if (Examscore >= 50 && Examscore <= 59) { grade = "Grade B"; } else grade = "Grade A"; { if (Examscore >= 70 && Examscore <= 74) { } else } else grade = "Grade C+"; Table 3.1.19 Example JavaScript program and output (AND) } else otherwise otherwise <html> grade = "Grade D"; if (Examscore >= 75 && Examscore <= 79) { grade = "Grade G"; grade = "Grade C"; grade = "Grade A-"; } else { if (Examscore >= 65 && Examscore <= 69) { grade = "Grade B+"; { if (Examscore >= 40 && Examscore <= 44) { { if (Examscore >= 60 && Examscore <= 64) { } 2 Program 1 Machine Translated by Google


2 Example 27 shows that the user has the right to vote if he is 21 years old and above or has been registered as a voter. Therefore, to determine voting eligibility, the entered age must be greater than or equal to 21 or the user has successfully registered previously as a voter and the logical operator '||' need to be used. Example: if (age>=21 || statusRegister==true). The JavaScript program and output are shown in Table 3.1.20. 3 Next the grade is displayed. both grade requirements will be kept. Example Output 3 2 Checking exam scores using the if command. Scores are checked by meeting both conditions such as score>=65&&score<=69 using the logical operator &&. If meets 1 Set an exam mark, which is 67. The logical OR operator } otherwise } " } + Exam marks + (" + grade + ")"); if (Examscore >= 90 && Examscore <= 100) { } } { } } } </body> } grade = "Grade A+"; </script> 186 Computer Science Form 5 } </html> document.write("Exam Marks: " Description: The OR logical operator is used when two or more Boolean conditions need to be combined and only one of the Boolean conditions needs to be true before executing the next statement. EXAMPLE 27 Machine Translated by Google


<body> <script> var age = 25, statusRegister = true; Table 3.1.20 Examples of JavaScript programs and outputs (OR) if (age >= 21 || statusRegister == true) { <body> <script> var age = 25, Register status = false; } </script> </ body> </ html> CHAPTER 3 Web-Based Programming 187 (meets one of the if conditions) document.write("You are eligible to vote."); if (age >= 21 || statusRegister == true) { document.write("You are eligible to vote."); } html> document.write("You are eligible to vote."); } else if (age >= 21 || statusRegister == true) { <body> <script> var age = 19, statusRegister = true; { document.write("You are not eligible to vote."); } </script> </body> </ html> { document.write("You are not eligible to vote."); } </script> </body> </ html> otherwise } else (meets both if conditions) { <html> (meets one of the if conditions) document.write("You are not eligible to vote."); <html> 1 2 Example Output 3 Program Age: 19 Register Status: true Age: 25 Register Status: true 4 Age: 25 Register Status: false Machine Translated by Google


<script> { </html> if (age >= 21 || statusRegister == true) 188 Computer Science Form 5 </body> Repetition based <html> } document.write("You are eligible to vote."); Repetitive Control Structure { <body> document.write("You are not eligible to vote."); Counter otherwise Repetition based Figure 3.1.47 Type of repetition control structure var age = 19, Register status = false; </script> Requirement } Repetitive Control Structure (does not meet both if conditions) displayed. 1 Set the value "age = 25" and "Registration status = true". 4 On the other hand, if both conditions are not met, the message "You are not eligible to vote" will be displayed Example Output 3 If one of the conditions is met, the message “You are eligible to vote” will be displayed. one of the conditions is age >= 25 or Register status = true. Program Age: 19 Register Status: false 2 Checking the value of age and status Register using the if command. Checking whether it meets Description: Repeat control structures require conditional statements that will execute a single statement or block of code repeatedly. A loop control structure executes a given statement as long as the condition is true. Figure 3.1.47 shows two types of repeat control structures. Counter-based iteration using the for... statement in JavaScript. Counter-based iteration will use one variable to iterate over the statement and the condition depends on the counter. Table 3.1.21 is the syntax of the counter-based iteration structure shown by the pseudocode and flowchart. Counter-based repetition Machine Translated by Google


3 If the counter condition is TRUE Program 3.3 Go to Step 3 4 1 Pseudocode 1 Start Flowchart Example Output 5 2 4 End 2 The initial value of the counter 3 Example 28 shows the code block will continue to print “Good Luck!” as long as the numerator is less than or equal to 3 (or as many as 3 times). The JavaScript program and output are shown in Table 3.1.22. 3.1 Statement 3.2 Update the counter </html> var counter; Example: Counter update value. Table 3.1.22 Example JavaScript program and output (counter-based iteration) Finished CHAPTER 3 Web-Based Programming 189 Counter end value. update Counter value </body> <script> Statement for(counter=1; counter<=3; counter++) True? The repetition will continue when the counter is less than or equal to 3. Example: counter incremented by 1 (counter++) document.write("Good Luck!<br>"); Table 3.1.21 Pseudocode and flowchart (counter-based iteration) The initial value of the counter the counter is set to 1 Repetition will stop when the counter exceeds 3. } <html> Counter terms This is the condition for repetition. Start Example: <body> TRUE </script> { FAKE The initial value of the counter. or continued –The value to end the counting process that determines the end iteration To implement a counter-based control structure, the for statement will be used. for has three components, namely: •Value expires •Initial value–The starting value for counting •Update value–Process to update counter value EXAMPLE 28 Machine Translated by Google


2 break. for(counter=1; counter<=3; counter++) </body> var counter; document.write("Good Luck!<br>"); 2 There is a counter value that is given an initial value of 1. 3 There is a counter end value, which is 3 to count the repetition of 3 times (starting from 1 to 3). </script> { 1 for is used in JavaScript to perform repetition. Example 29 shows the use of break, that is, the program will stop when the counter is 2 and terminate the iteration even if the end value of the counter is 3. The JavaScript program and output are shown in Table 3.1.23. </html> Example Output 5 Messages “Good Luck!” will be displayed 3 times. <html> breaks; Program 4 counter ++ is to update the counter value by adding one to the counter value (until the counter <=3 condition is not met). if (counter==2) 1 The program will continue to print “Good Luck!” as long as the numerator is less than or equal to 3. 2 If the counter is equal to 2, the repeating code block will be stopped and terminated by the statement } <script> Example 30 shows the use of continue, i.e. the program will continue when the counter is 2 and continue repeating. The JavaScript program and output are shown in Table 3.1.24. 1 <body> Table 3.1.23 Examples of JavaScript programs and output (break) 190 Computer Science Form 5 Description: Description: This repeat control also recognizes the break and continue keywords . Break keyword will cause the termination or cessation of a replay. Termination or termination occurs anywhere within the code block. The continue keyword will continue to execute and finish repeating the code block or statement and check the condition whether the condition is true. If true, the iteration will continue and continue again. EXAMPLE 29 EXAMPLE 30 Machine Translated by Google


3 If Condition is TRUE 3.1 Statement 3.2 Update condition 3.3 Go to Step 3 2 Pseudocode Example Output with 3. 1 The program will continue to print “Good Luck!” as long as the numerator is less or equal Program continue. 1 Repeat Type 4 End Flowchart 2 If the counter is equal to 2, the repeating code block will still be continued by the statement 2 The initial value of the condition while… 1 Start Conditional repetition document.write("Good Luck!<br>"); if (counter==2) continue; Table 3.1.24 Examples of JavaScript programs and output (continue) Finished FAKE Start Update terms <html> Table 3.1.25 Condition-based repetition structure (while...) The initial value of the condition CHAPTER 3 Web-Based Programming 191 TRUE <body> <script> var counter; for(counter=1; counter<=3; counter++) { TRUE? Statement } </script> </ body> </ html> Requirement Description: Condition-based repetition by using two types of statements in JavaScript, namely: while... The while statement executes a statement again as long as the condition is true while the do...while statement will execute the statement or block of code at least once and will continue the statement as long as the condition is true. Table 3.1.25 and Table 3.1.26 show the condition-based repetition structure. • do...while Machine Translated by Google


2 The initial value of the condition Example Output 4 If the condition is TRUE (condition met) the initial value of the repeat variable is 1 (condition not met) the initial value of the repeat variable is 4 Repeat Type Flowchart 4.1 Update requirements 4.2 Go to Step 3 Pseudocode 1 Start Example 31 shows "Greetings!" will be displayed first at least once and the conditions will be checked after the display. If the conditions are met the display will be executed again. The JavaScript program and output are shown in Table 3.1.27. do…while… 3 Statements Program 5 End EXAMPLE 31 Table 3.1.26 Conditionally controlled repetition structure (do... while) Start <body> <script> var repeat=1; 1 do{ document.write("Good Luck!<br>"); 2 repeat++; 3 }while(repeat<=3); 4 </script> </body> </html> FAKE TRUE terms? Finished The initial value of the condition <html> Table 3.1.27 Examples of JavaScript programs and output (do...while) requirement Update <body> <script> var repeat=4; do{ document.write("Good Luck!<br>"); repeat++; }while(repeat<=3); </ script> </ body> </html> Statement 192 Computer Science Form 5 <html> TRUE Machine Translated by Google


Click to View FlipBook Version