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 4 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 17:24:27

[BAHASA INGGERIS] BUKU TEKS SAINS KOMPUTER TINGKATAN 4

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

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

Flowchart • initializer: Declaration of counter variable with initial value. The counter detects the number of repetitions. For example, int i=1; declare i as a counter variable and count starts with 1. Syntax • termination:An expression that is a condition to stop the loop. If the variable declared in the initializer is i, then in the terminator, write the expression i<=10 if repetition is allowed up to the 10th round. What if 100 repetitions are allowed? • adder: An expression to update the value of the counter variable on each loop. An integer value, usually 1, is added to the counter after each iteration. For example, the expression i++; add 1 to the counter. This can also be written as i=i+1; Conditionals and Loops SET COUNTER with INITIAL_VALUE. Finished goo.gl/rSPeZY Computer Science Form 4 False Start COUNTER A group of statements that need to be repeated Update Figure 1.35 Flow chart and syntax for the for loop control True 92 <Block of statements to repeat> for(start ; end; adder) { } COUNTER < CHECK whether STOP_VALUE? Repeat Control The for control repeats for a specified number of times. This is determined by a counter variable that starts with a specific index number such as 0 or 1. The index number will be automatically added to the end of the statement block. The increment is usually 1 but can be set in the increment section. This addition will be made each time the block of statements has been repeated and will continue until the repeated boolean condition becomes false. For Machine Translated by Google


Write a program to display all odd integers from -30 to 30. you ? Did you know? } + amount); } } total result 50+51+.......+59+ 60 System.out.print(i); 2 The expression <test> will begin to be evaluated 6 End of loop } System.out.print(i + ","); initial to the counter Mind Test int total=0; public static void main(String[] args){ Steps for implementing control for: is true, then <statement> will be executed public static void main(String[] args){ } } public class Example37{ (b) Write a program to display all even integers from -10 to 20. } 3 If the value } System.out.println("Amount: " } if ((i % 2) == 1) sum = sum + i; for(i=1;i<=10;i+=1){ 5 Repeat steps two through four (a) Use a for loop 4 The counter is updated using <update> int i; 1 Concentration of value for(int i=2;i<=100;i+=1){ to determine for(int i=0;i<=30; i+=1){ public class Example38{ public static void main(String[] args){ public class Example36{ CHAPTER 1 PROGRAMMING Example 38 Example 37 Example 36 Write a program for a for loop to print the numbers 1 to 10. Solution Use a for loop to determine the sum of 2+3+4+5+...+99+100. Example output: Example output: Example output: Solution Solution 93 Machine Translated by Google


Do the following activities. Aida has kept her money of RM500 in the bank. Every year, Aida receives an interest rate of 10% on the balance in the account. How much will Aida's savings be left after five years if she never withdraws her savings in the bank? You must use the for loop control to determine the answer. Example output: Solution 1 Choose a student. Students are asked to stand at one corner of the white board. Give a "marker" pen. 2 The teacher will stand between the students and the whiteboard. Announce to the class that the teacher wants to see students repeat to write the same word six times. Ask the students in the class to count the repetitions made. 3 In one corner of the other, place a chair. Teamwork 94 System.out.println("Remaining 5 years: " double balance = 500.0; Computer Science Innovation for(int i=1;i<=5;i+=1){ } public static void main(String[] args){ } Computer Science Form 4 online banking. Thanks to the contribution of programming experts, the online banking system makes it easier for people to create + balance); public class Example39{ banking matters if you don't have time to go to the bank. The age of the world at the fingertips today has made all the affairs of human life easier. If before, all bank affairs balance = balance + (0.1 * balance); 21 Repeat Control Structure For required an individual to go to the bank, now everything can only be done through } Example 39 Machine Translated by Google


Block Finished False Start repeating statement True CHAPTER 1 PROGRAMMING true? Figure 1.36 Flow chart and syntax for the while loop control Still Flowchart Syntax 5 The student will ask the teacher if he is allowed to stop. The teacher will ask the class how many repetitions the student has done. (a) What is the minimum number of repetitions that can be made? (d) Under what circumstances are students not allowed to repeat and the game is terminated? turned back to the teacher. (e) Does the number of repetitions need to be known in advance? students return to their seats and the game ends. The question is: 4 Pupils are asked to walk to the whiteboard, write "Hello world!", walk towards the chair and then (c) What conditions allow repetition? 7 When the class agrees that this student has reached the desired number of times, allow (b) What is the maximum number of repetitions that can be made? 6 If another student does not allow to stop, the teacher will instruct the student to repeat each previous step again. 95 <Block of repeated statements> } while (<boolean condition>){ Repetition Control The while repetition control makes a test first on the input. If the input meets the boolean condition, the instruction block in the loop will be executed. If the condition is not met, loop control will stop and control will move to the command line after loop control. Figure 1.36 shows the while loop control. While Machine Translated by Google


96 Example 40 Example 41 (c) Write a Java program using the flow chart that has been drawn as Example output: Determine the output of the following Java code: (b) Draw a flow chart for solving the above problem. Solution: (a) Write pseudocode for the solution to the above problem. reference. Use the while loop control to display all numbers in descending order from the positive integers of the user entered numbers up to zero. The purpose of doing so is so that the same boolean condition will be tested multiple times. This is because, if this step is not made, then the boolean condition being tested will have the boolean value "True" forever. After the statements in the repeat block are executed, determine whether the program needs to update the value in the condition. The repeat control contains an option control but try to pay attention to the direction of the arrow for a "True" result. Does the arrow loop back to the arrow entering the selection control rhombus? Did you know? you ? n-=1; } int n=5; while(n>0){ 4 Repeat steps 3 and 4 end_while public class Example40{ Computer Science Form 4 public static void main(String[] args){ } 1 <expression> evaluated 2 If <expression> is true, <statement> is executed. } 3 If <expression> is false, end the loop. (a) Read input nom As long (nom > 0) begin_as long Display nom=nom-1; While loop in Java with examples System.out.print(n + ","); goo.gl/qCyMB0 Steps to implement the while control: Machine Translated by Google


Example 42 97 Write a program that prompts the user to enter a password. The user's password must be the same as the value in the record, which is the value in the SecretPathRecord variable. The program will prompt the user again if the password test fails. Example output: Solution (c) public class Module1{ (b) while(!strPassword.equals(SecretPasswordRecord)){ while (nom>0){ True strPassword=scanner.next(); Based on Example 42, use a while loop control to display all the numbers in sequence Scanner scanner=new Scanner(System.in); Mind Test Scanner scanner=new Scanner(System.in); Finished Start } } System.out.println(nom + public static void main(String[] args){ name>0? public class Example42{ Show nom-- nom -= 1; } System.out.println(); int nom=scanner.nextInt(); decreases from the negative integer of the number entered by the user up to -10. System.out.print("Please enter password:"); public static void main(String args[]){ } CHAPTER 1 PROGRAMMING } Read nom final String SecretPath Record="Banana"; " "); String strPassword = new String(); False } Machine Translated by Google


22 While Loop Control Structure True Infinity Loop/Endless Loop Repeated statement blocks An example of an infinite loop: Make sure that the boolean condition being tested is always updated in the repeated statement block so that the boolean condition test will produce false results later. Computer Science Form 4 However, the break keyword and the optional if-then control can be used to stop the infinite loop. Is there any possibility that the statement block in the loop will repeat endlessly? As long as the boolean condition being tested produces a yes result, the loop will repeat again. Therefore, the loop is called an infinite loop. Infinity loops are not a good thing and should be avoided. Do the following activities. System.out.println("The loop refuses to stop"); Syntax while(true) Flowchart 98 (b) The maximum number of repetitions that can be made. 6 The teacher will check the conditions again. If the check is correct, the student is asked to repeat the previous steps. 1 Choose a student. Students are asked to stand at one corner of the blackboard. Give a stick of white chalk. 7 If the conditions are not complied with, students are asked to return to their seats and the game ends. (e) Does the number of repetitions need to be known in advance? 5 If the class says yes, the student is allowed to walk to the blackboard, write "Hello world!", and then walk around the chair and then turn back to the original corner. 4 Pupils will ask permission to write "Hello world!" from the teacher. The teacher can ask (c) What conditions allow repetition? class is the sentence "Hello world!" not enough (d) Under what circumstances are students not allowed to repeat and the game is terminated? 2 The teacher will stand between the students and the blackboard. Think of a new condition and announce it to the class. For example, announce that the teacher wants to see the sentence "Hello world!" 6 times on the blackboard. 8 Ask the students to think about the following and draw conclusions: 3 In one corner of the other, place a chair. (a) The minimum number of repetitions that can be made. Is it possible that there is nothing at all? Teamwork you ? Did you know? Machine Translated by Google


What is the output for the following loop control? Loop While <Boolean condition> Example 43 <Block of repeated statements> Do you ? Did you know? Loop Control The dowhile loop control is similar to the while loop control. The distinguishing feature of the do-while loop control is that this control performs the test after the instruction block in the loop is executed. Thus, the do-while loop control guarantees that the instruction block will be executed even once. Do-While 99 Start True do { Still x 3 = true? System.out.println(no + no = no + 1;} while(no <= 12); 3 If <expression> is true, repeat steps 1 to 2 Block int number = 1; CHAPTER 1 PROGRAMMING 4 If <expression> is false, end the loop 1 <statement> executed Figure 1.37 Flow chart and syntax for do-while loop control Finished " 2 <expression> is evaluated + no *3); repeating statement " Steps of do while control implementation : False Flowchart Look at Figure 1.37. A sequence of repeating command blocks is located before the boolean condition test symbol. A "True" arrow will follow if the boolean condition test produces a true result. The "True" arrow will point to the flow line before the command block repeats. Conversely, in a while loop control, the "True" arrow from the boolean condition test symbol will point to the loop command block before returning to the boolean condition test symbol. If "False", repeat control will stop and control will move to a new command line. Syntax Machine Translated by Google


100 Example 44 Did you know? you ? Solution Example output: Example output: Write a do-while control loop that will request an integer number from the user 5 times before displaying the total number entered. Solution counter = counter + 1; sum += no; • Form for System.out.println(no + * 3); } do { } do { }while(no <= 12); int number = 1; <statement>; " public class Example43{ <prefix>; while ( <test> ) { <statement>; double sum; + sum); public static void main(String[] args){ ; <update> ) <statement>; <prefix>; " • Do while form no = no + 1; for (<prefix> ; <test>). public class Example44{ }while(counter <= 5); Computer Science Form 4 no = scanner.nextDouble(); Summary for for, while and do while control statements. } } while ( <test> ); } Scanner scanner=new Scanner(System.in); int counter = 1; <update>; public static void main(String[] args){ + no <update>; } System.out.println("The total is " • While form Do { x 3 = double number; Machine Translated by Google


Teamwork Did you know? you ? An application receives two integer numbers from the user and displays the difference between the two numbers. After that, the application will ask the user if they want to repeat it. The user enters the word "Yes" if they want to repeat, or else if they don't want to repeat it. Write a Java program for this application. 4 Pupils are asked to walk to the blackboard, circle a number, and then walk towards Solution teacher. 3 In one corner of the other, place a chair. The teacher is next to the chair. The teacher will write a comparison operator (less than, greater than or equal to) followed by a number between 3 and 8 on a piece of A4 paper. For example, < 5. This paper is a secret condition that was kept secret from the student earlier. 2 Choose a student. Students are asked to stand at one corner of the blackboard. Give a stick of white chalk. Example output: 1 Write 10 numbers from 0 to 9 on the blackboard. 5 Before being allowed to walk around the chairs, the teacher will ask the class if there is an option 101 input=scanner.next(); String input; no2 = scanner.nextInt(); Continue statement Scanner scanner=new Scanner(System.in); System.out.println("Difference: " abs(no2 - no1)); do { } 23 Do-While Repeat Control Structure public class Example45{ no1 = scanner.nextInt(); CHAPTER 1 PROGRAMMING public static void main(String args[]){ Additional info: The break statement is used to exit the loop. }while(input.equals("Yes")); + Math. The finally statement is used to ensure that the loop executes even if an exception is not expected. } is a control statement that allows for int no1; System.out.println("Type Yes to continue .."); continues directly to the next loop without having to execute another statement inside the loop. This statement can be used in for, while and do while loops. int no2; Example 45 Machine Translated by Google


102 1.4.4 Repetitive Control Structure Involving Operators and and On the other hand, the decrement operator (ÿÿ) decreases the value of a variable by a certain number of numbers. Class Math Boolean Increment Decrement , Did you know? you ? Table 1.13 Expression of figures It all means the same thing! Computer Science Form 4 • i++ while (<boolean condition>){ i += 2 will add 2 to 5. i += 1 will add 1 to 9. • i = i +1 } } • i + =1 Expression Meaning <Block of repeated statements> <update value in condition> <Block of repeated statements> <update value in condition> Example while (<boolean condition>){ 7 If the choice does not comply with the conditions, the student is asked to return to the seat and the game terminated. (c) What conditions allow repetition? 6 Pupils are asked to repeat the previous steps by choosing a new number. (b) The maximum number of repetitions that can be made. students comply with the conditions of confidentiality. The whole class can see the condition except the student. If so, the teacher will allow the students to walk around the chair and then turn back to the original corner. (e) Does the number of repetitions need to be known in advance? (a) The minimum number of repetitions that can be made. (d) Under what circumstances are students not allowed to repeat and the game is terminated? 8 Ask the students to think about the following and draw conclusions: i+=2 i = i + 2 Suppose i contains 9. So, the new value of i is 10. Suppose i contains 5. i+=1 i = i + 1 So, the new value of i is 7. Operators Increment (++) and Decrement (––) The increment operator (++) and decrement operator (– –) are commonly used in repetition control as counters. The increment operator (++) is the addition of the value of a variable by a certain number of numbeMachine Translated by Google


while (<boolean condition>){ i -= 2 will decrease 2 from 5. Expression Meaning i++; <Block of repeated statements> while (<boolean condition>){ Example i--; Example } i -= 1 will decrease 1 from 9. --i; while (<boolean condition>){ i -= 3 will decrease 3 from 2. } <update value in condition> <update value in condition> <Block of repeated statements> ++i; } <update value in condition> <update value in condition> }) i += 3 will add 3 to 2. Expression Meaning while (<boolean condition>){ <Block of repeated statements> <Block of repeated statements> Suppose i contains 2. Suppose i contains 2. So, the new value of i is 3. i+=3 i = i + 3 Suppose i contains 9. i-=3 i = i – 3 So, the new value of i is 5. So, the new value of i is -1. i-=1 i = i – 1 So, the new value of i is 8. Suppose i contains 5. i-=2 i = i – 2 Math.random() is a Java subroutine for randomly generating numbers. Math.random() uses the system time as a seed value to start the random number generation. This subroutine is used whenever needed to generate a random number between 0 and 1. What if a random number is needed in the range 1 to 6? If the required random number is between 1 and 10, use the expression (int)(Math.random()*10) + 1. If the required random number is between 1 and 100, then the expression (int)(Math. random()*100) + 1 is used. Increment and decrement after the value of the variable is used in the rest of the expression. Table 1.14 Decreasing expressions Ebbs and flows happen before the value of the variable is used overexpression. Ebbs and flows occur CHAPTER 1 PROGRAMMING goo.gl/RZqgGH you ? Did you know? 103 Math.random() Machine Translated by Google


104 Solution Write Java code to generate 20 random numbers for dice. Dice only have six combinations, namely 1, 2, 3, 4, 5 and 6. Boolean flag What if the program allowed the user to decide whether to continue with another set of 20 random numbers? In this case, the code above can be placed in a do-while loop control and a Boolean variable is used to control the repetition. This variable operates as a flag, or determining flag. Before entering the next loop, the user is asked if they want to continue the program again. If "True", the flag is set as True. Otherwise, the flag is set as False. System.out.println(); } Computer Science Form 4 for (i = 1;i<=20;i++){ flag=true; System.out.print((int)((Math.random() * 6) + 1) + "); }else{ stop”); boolean flag=true; if(scanner.next().equals("yes")){ do { int i; System.out.println(“-------------------------------------“); }while(flag); } Scanner scanner=new Scanner(System.in); System.out.println("Type yes to continue. No to } public class Example46{ " flag=false; Figure 1.38 Output 20 numbers with option to repeat public static void main(String[] args){ } Example 46 Machine Translated by Google


Write Java code that randomly generates 20 dice numbers and the user is given the option to repeat the process. System.out.println("Type yes to continue. No to } " case 1: count1++; breaks; int diceNo; System.out.println("* Dice number 1 = System.out.println("* Dice number 2 = System.out.println("* Dice number 3 = System.out.println("* Dice number 4 = System. out.println("* Dice number 5 = System.out.println("* Dice number 6 = System.out.println(); System.out.println(“--------------------------------“); } " } public static void main(String[] args){ System.out.print(diceNo+ " "); "%"); } public class Example47{ "%"); do { case 5: count5++; breaks; + count5 + flag=true; + count3 + case 3: count3++; breaks; + count1 + + count2 + Scanner scanner=new Scanner(System.in); " int count1=0,count2=0,count3=0,count4=0,count5=0,count6=0; case 2: count2++; breaks; " stop”); }while(flag); System.out.println(); switch(diceNo){ int i; "%"); " flag=false; "%"); diceNo= (int)(Math.random() * 6 + 1); } + count6 + case 6: count6++; for (i = 1;i<=20;i++){ "%"); " }else{ if(scanner.next().equals("yes")){ case 4: count4++; breaks; "%"); boolean flag=true; + count4 + CHAPTER 1 PROGRAMMING 105 Solution Example output: Example 47 Machine Translated by Google


106 Example 48 Solution The experiment of determining the frequency of dice numbers 1, 2, 3, 4, 5 and 6 as a result of 100 random tosses is quite difficult to do manually. Suppose the result of the experiment is the percentage frequency of each dice number in 100 tosses. Counters In addition to the i counter commonly used in for loop controls, other counters can be declared to perform calculations in problem solving. This counter is declared by the programmer outside the loop control as a variable of type int and is assigned the original value of 0. In the body of the loop control block, this counter will be incremented or decremented depending on the type of problem using the Increment or Decrement operator. Conditions involving changing counter values are tested using optional control structures such as switch-case or if-else. Computer Science Form 4 To understand the role of the counter further, see the following example. Machine Translated by Google


Obesity 26.5 – 30.9 Fat 20.7 – 26.4 Normal Less than 20.6 More than 45.3 Skinny Danger 31.0 – 45.2 CHAPTER 1 PROGRAMMING BMI Status (a) accepts the value of a person's weight (in kg) and the value of a person's height (in m). 1 Body Mass Index or better known as BMI (Body Mass Index) is a measurement that shows the relationship between a person's weight and height. BMI can be measured by taking a person's weight (in kilograms) and dividing it by twice a person's height (in meters). Write a Java program that can, After getting the BMI result, you can see the chart in the table shown below to determine your category. Example output: (c) display the status as in the table above based on the BMI value obtained . BMI = height (m) 3 height (m) (b) calculate BMI based on the weight and height values obtained in question (a). weight (kg) 107 Formative Training 1.4 Machine Translated by Google


Initialize Display the counter and (a) for(n = 2;n<=20; n+=3){ counter (b) for(n = 150;n<=40;n-=15){ System.out.println(n + <=72? counter + 9 } False } counter = 9 Finished space " "); counter = Computer Science Form 4 System.out.println(n + True " "); Start 108 control part only. 4 A factorial is the result of multiplying a number by the next smaller number until the number 1. The factorial of 5 is 5 3 4 3 3 3 2 3 1 = 120. Use the do-while loop control to find the factorial of a positive integer entered by the user. (a) Write a program using the Java programming language based on the flowchart above. Show it The user's password must be the same as the value in the record, which is the value in the SecretPathRecord variable. The program will display the command again if the password test fails. Use the for loop control structure to display all even integers between those two numbers. (b) Draw a flow chart. (c) Write a Java program based on the algorithm you designed earlier. 6 Write a program that prompts the user to enter a password. 2 Determine the output for the following loop control. 3 Write a Java program that asks the user to enter two integers, namely noStart and noEnd. (a) Write pseudocode for solving this problem. (b) What output do you expect? Users can only try three times before the application closes itself. 5 Study the following flowchart. Machine Translated by Google


109 100 16 "TECHNICIAN" 25 "CLERK" 101 "ADMIN" 113 “Access denied” 145 “System and data access” 12 “Total reach” 2 5 “Data access only” "MANAGER" 111 “System access only” Others 10 Rewrite the following if statement using a switch...case statement. 9 Write a program that can read the Book Code and Number of books data as shown in the figure shown below. Also display the code that has the highest and lowest number of books. 7 Write an if...else...if statement based on the table shown below. 8 Rewrite the program below using the while statement. Number of books (a) Test code +p); " Display + count); " p = i + 1; otherwise System.out.println (“Count result = + null); System.out.println(i + Book code System.out.println(“Count result = for (i = 0; i<=9; i++) } if (i>=9) { System.out.println ("end\n"); int count = 29; if (count % 10 == 0) " CHAPTER 1 PROGRAMMING " int p, i; - Machine Translated by Google


110 Register At least 18 years old At least 18 years old "You need to register first before voting" "You need to re-enter the password" Under 18 years old "You are too young and ineligible to vote" "You deserve to vote" True False Register Not Registered Not Registered "You can proceed to the next transaction" Random Number [3] : 27 Qualification Message int points = 3, score; Status score += 5; if (points == 1) A random number between 1 and 100 is: else if (points == 4) Age (b) else if (points == 3) Random Number [4] : 96 score += 26; Random Number [5] : 90 Value Transaction message else if (points == 2) Random Number [1] : 23 Computer Science Form 4 score += 10; Random Number [2] : 56 subroutine Math.random() method. An example output is shown as below: Write a program that can determine whether your transaction can continue or not using if...else...if statements :- 12 Write a Java program that can determine whether a person is eligible to vote or not based on age and registration status (registered or never registered) and display the message below: 11 Write a Java program that can receive a number between 1 and 100 randomly using 13 The variable declaration is given as below: boolean pass = true; Machine Translated by Google


1.5 Best practice in general is a technique or methodology that has been proven through a reliable experience or study, to get the desired result. Best practice in a field is a commitment to use all available knowledge and technology to ensure good outcomes. Best practice programming is when programmers can practice the practices that are commonly followed to produce good programs. The diagram below shows the visible differences between program code developed using programming best practices and program code developed without applying programming best practices. Which diagram makes you better understand what the programmer is trying to convey? CONTENT Best Practices STANDARD LEARNING STANDARDS 111 //Output declaration + Figure 1.39 A program that uses programming best practices //Input declaration certain program int number1 = 20; public class Subtract_Two_Numbers { //Output to be displayed } 1.5.2 Detect, identify, translate error messages and repair errors public static void main(String[] args){ System.out.println(" Subtraction result is " result ); 1.5.3 Identify the value of the variable in the section // Step 3: Display the result*/ double results; //The process subtracts number1 - number2 1.5.1 Differentiate types of errors in programs (syntax, runtime and logic) // Program to Calculate the Subtraction of Two Numbers result = number1 - number2; CHAPTER 1 PROGRAMMING 1.5.4 Produce readable programs using good style (comments, meaningful variable names, indentation) int number2 = 13; } // Step 2: Calculate the result of subtracting number1 - number2 /* Step 1: Read number1 and number2 Programming Machine Translated by Google


1consistent indents Enabler 4 Comments 2Meaningful variable data types double as a variable. Figure 1.41 Best practices in programming + result ); is case sensitive. public static void main(String[] args){ Netbeans in • Consistent use of indentation makes program code easy to read and understand for other users. A consistent way of writing indents should be done from the beginning of the program code to the end of the code. int number2 = 13; double results; (b) There are no blank spaces between words. If there is more than one word, use an underscore ( _ ) or close the words into one word. • Can't consist of blank spaces and reserved/special words like 'print' result = number1 - number2; Smart Figure 1.40 A program that does not use programming best practices phone (d) Use of lowercase letters with capital letters such as passwords, variables Computer Science Form 4 public class Subtract_Two_Numbers { Use of Java int number1 = 20; } • Choose the appropriate data type so that the variable size is not too small or large and conserve resources . For example, use the integer data type for whole numbers instead of doubles. For example, caraPertama is different from CaraPertama. Game Construction • Keep the scope small to avoid confusion and be easy to maintain ie: (a) Do not start with a number. For example, use cara1 instead of 1cara. • A name that is meaningful and easy to understand. The use of abbreviations whose meaning is not clear or the use of letters such as x and y is not recommended. https://goo.gl/uwbGeQ Daily Application For example, way 1 or wayFirst or way_1. and 'value'. System.out.println("The subtraction result is " } (c) Not the same as keywords in Java. For example, the use of integers or • Comments should be clearly written in two to three short lines to describe the function of the code and fill the coding column space. 112 The following are the best programming practices that must be followed by a programmer in producing a good program code, or it can also be said the factors that affect the readability of the program code. Machine Translated by Google


For the diagram above, what causes the program to have a syntax error? Try to pay close attention to the code of the program. Understand the error message it is trying to convey. As you can see, one notation “ “ is missing. "public The existing class " notation HelloMalaysia". is only to cover } } one " " notation on the While the main method "public { static void main (String[] args)" does not end with the notation "}". The diagram below has been completed with the notation "{}". " } The example program contains a notation syntax error that has been corrected Error Syntax error, insert "}" to complete ClassBody Figure 1.42 Types of errors in programming at HelloMalaysia.main(HelloMalaysia.java:9) } public static void main(String[] args){ Exception in thread "main" java.lang.Error: Unresolved compilation problem: System.out.println("Hello Malaysia!"); Syntax System.out.println("Hello Malaysia!"); CHAPTER 1 PROGRAMMING Logic public class HelloMalaysia { Running Time An example of a program that contains a syntax error } public static void main(String[] args){ public class HelloMalaysia { 113 Example 49 Errors may be encountered when you run the program for your first project. Errors that often occur during the programming process are divided into three types, namely syntax, runtime and logic. Syntax errors refer to errors that occur due to the following: b Use of unfamiliar objects or characters. The following will explain in more detail the types of errors and the factors that cause them. a Grammatical errors such as spelling and punctuation errors. Syntax Error 1.5.1 Types of Errors in Programs Syntax Error Notation has been completed Machine Translated by Google


The figure below shows the syntax error. When declaring a variable or constant, the data type must also be declared along with the name of the variable. Try to pay attention to the program below. The "High" variable is not specified with its data type. The tall variable should be declared as “int Tall;”. Syntax Error 114 Exception in thread "main" java.lang.Error: Unresolved compilation problems: public static void main(String[] args){ } Mind Test } int Height = 4; Height cannot be resolved to a variable public class AreaTriangle { public static void main(String[] args){ at Triangle Area.main(Triangle Area.java:12) System.out.println ("Area of Triangle is : Height = 4; } http://goo.gl/vrDCrk + Area); " Height cannot be resolved to a variable int Site = 6; Computer Science Form 4 Try to test your mind by answering the programming quiz. Area = (1.0 / 2) * Base * Height; Career Science double Width; System.out.println ("Area of Triangle is : Computer Area = (1.0 / 2) * Base * Height; " int Site = 6; This article displays advice and career tips from experts in the field of programming. + Area); double Width; } public class AreaTriangle { Example 50 Machine Translated by Google


While making the variable declaration, he has accidentally lumped the "High" variable with char x. While the program was running, the compiler issued a run-time error. Calculation of non-numerical data (non-numerical) Ah Chong checked his program and found that the "Height" variable had been populated with "x" instead of a number. Ah Chong is writing a program to calculate the area of a triangle. Example 51 http:// goo.gl/ 6pMi06 System.out.println ("Area of Triangle is : } com Example of a runtime error message (Computation of non-numeric data) Computer Science Innovation " int Site = 6; Area = (1.0 / 2) * Base * Height; x cannot be resolved to a variable CHAPTER 1 PROGRAMMING int Height = x; //Display the output at Triangle Area.main(Triangle Area.java:12) // Declaration of input variable double Width; // Process involved in enumeration A robot designed by ASUS to be a digital companion for the elderly. https://www.zenbo.asus. // and output // area of the triangle } Example of a non-error-free program at run time (Computation of non-numeric data) Exception in thread "main" java.lang.Error: Unresolved compilation problem: Run-time Errors + Area); public static void main(String[] args){ public class AreaTriangle { Runtime Errors Runtime errors are errors encountered when a running program is interrupted due to several factors. This error occurs if the programmer tries to perform an impossible arithmetic operation. Syntax Error 115 Examples are as follows: a Calculation of non-numerical data (non-numerical) c Finding the square root of a negative number b Division by the digit 0 Machine Translated by Google


After this program is run, an error message like the figure below will be displayed. What happened? Can you identify where the runtime error is likely to occur? Let's check together. A runtime error also occurs if a mistake is made when finding the square root of a negative number. As we all know, negative numbers have no square root. Try to pay attention to the formula used. The division of the three numbers is with the digit 0, which is one of the factors to the occurrence of runtime errors. The diagram below shows the non-error-free program code to calculate the average of three numbers. See the diagram below. The output that will come out is as shown. 116 int y = -25; public class HelloWorld { Exception in thread "main" java.lang.ArithmeticException: / by zero at Average_Three_Numbers.main(Average_Three_Numbers.java:10) System.out.println("\n" + Math.sqrt(x)); System.out.println(Math.sqrt(y)); public static void main(String[] args) { Example of a non-error-free program at runtime (Division by digit 0) int x = 9; System.out.println(d); } Computer Science Form 4 Example of a non-error-free program at runtime (Finding the square root of a negative number) } public class Root_Power_of_Two { public static void main(String[] args) { } Example of a runtime error message (Division by digit 0) int a, b, c, d; a = 3; b = 5; c = 10; d = (a + b + c)/0; } Example 52 Example 53 Machine Translated by Google


Logical Error 117 This error occurs when the program is not working as intended. Logical errors are undetectable or rarely detected by the compiler. If the output produced does not meet what is desired, the programmer needs to check all aspects of the output of the project such as calculations, text and spacing. Only the programmer can detect logic errors through the output produced. public static void main(String[] args){ int number1 = 20; System.out.println("The subtraction result is " } //Program to Calculate the Subtraction of Two Numbers + result ); result = number1 + number2; Example of non-error-free runtime output (Finding the square root of a negative number) http:// goo.gl/ 0YMZS int number2 = 13; An example of inaccurate output indicates a logic error occurred CHAPTER 1 PROGRAMMING double results; public class Subtract_Two_Numbers { } Logical errors in Java An incorrect mathematical formula is used to calculate the subtraction of two numbers After writing the program code, the output data obtained is wrong. Because the compiler could not detect the error, Azian had to check the program he had written. However, Azian can estimate where the error occurred in the program code based on the output data displayed as shown in the figure below. Azian and Mei Ling want to create a program that can calculate the subtraction of two numbers. Example 54 Logical Error Machine Translated by Google


Differentiate the types of errors and and also state any similarities, if any. Present your findings to classmates. (Suggestion – use the i-Think map if appropriate). Do this research in groups of two to three people. Talk to your friends. The program below is a simple program to calculate the ideal weight and height for an individual. However the program below is not an error free program. List the types of errors that may occur in the program code below and state how the error will appear when a program is run. Use the search engine facility to find more information. If the individual has a weight less than or equal to 55 and a height less than or equal to 145, then the output display is "You are slim" and vice versa. } Scanner input = new Scanner (System.in); System.out.println("You are fat"); System.out.println("Please enter weight: "); } } public class UsingIfNotScanner { else { public static void main(String[] args) if(weight <= 55 && height >= 155){ Computer Science Form 4 import java.util.Scanner; System.out.println("You are slim"); int weight = input.nextInt(); } int height = input.nextInt(); System.out.println("Please enter height: ") Teamwork 118 24 Let's do some research! Machine Translated by Google


} circle area = pi * radius; at LuasBulatan.main(LuasBulatan.java:5) solution Common runtime errors System.out.println("The area of the circle is " Syntax error, insert ";" to complete BlockStatements Figure 1.43 (b) The compiler detects an error in the program code Figure 1.43(a) double areaCircle; Luasbulatan cannot be resolved to a variable final double pi= 3.142; public static void main(String[]args){ Figure 1.43 (a) The program for calculating the area of a circle is not error-free int radius = 5 Exception in thread "main" java.lang.Error: Unresolved compilation problems: CHAPTER 1 PROGRAMMING http:// goo.gl/ g2924s + circle area); public class AreaCircle { } 1. Review the program on the declaration section. on Figure 1.43(b) is displayed. What happened? 2. Make sure all notation is typed completely. After understanding the differences described for the three program errors in programming, you will be able to detect, identify and interpret error messages and repair errors. Figure 1.43(a) shows a program to calculate the area of a circle that is not error free. Let's trace the error that occurred and make a fix! When the program in Figure 1.43(a) is run, an error dialog box 1.5.2 Detection, Identification and Translation of Error Messages and Error Repair 119 Machine Translated by Google


120 The declaration of the variable int radius = 5 is not terminated with a “;” symbol. • The area of a circle is declared as double the area of the circle; i.e. Circle is spelled with capital letters, but in the output program line, System.out.println("Circle area is " + circlearea), Circle is spelled with lowercase letters. 1 Syntax Error • Each complete line of the program will end with a “;” symbol. Logical Error Description Logic Error Fix Error Repair Identify the Type of Error 5. After detecting and fixing the syntax error, the program can be run but the answer on the output display is not correct. 3. Make sure that the name of the declared variable is the same as the name of the variable that will be called back in the program. What is meant is the same in terms of spelling and the use of lowercase and uppercase letters. (REMEMBER! In Java programming, the use of lowercase and uppercase letters is case sensitive.) 1. Review the program on the use of formulas section. 4. Once the error is identified, the syntax error can be fixed. 2. From Figure 1.43(a), we can detect an error in the formula for calculating the area of a circle. Daily Application Online purchases have been programmed to avoid congestion at the ticket machines. make it easier for passengers. In addition, LRT tickets can also be purchased online. LRT ticket purchase Computer Science Form 4 Figure 1.43 (c) Display of inaccurate circle area output data at the ticket machine already circle area = pi * radius; + circle area ); double areaCircle; System.out.println("The area of the circle is " int radius = 5; + areaCircle ); circle area = pi * radius * radius; System.out.println("The area of the circle is " int radius = 5 We can detect errors in programs such as the following examples: The correct answer for the area of the circle in Figure 1.43(a) is 78.55 but the system gives the answer 15.709 (Figure 1.43(c)). What happened? See Figure 1.43(c). Machine Translated by Google


In pairs, retype the program below in the Java platform environment. Run your program. Make a “Screenshot” of the program you have typed and display any errors you may get. The effect of the error. Discuss with your partner what types of errors might occur. Identify the error and fix it. Enter the program code containing the error and the code after it has been fixed in the table below. Teamwork you ? Did you know? 4. Once the error is identified, the logical error can be corrected. 3. Logical errors are difficult to detect at an early stage. This error can often be detected when the display of the desired result does not match what is desired. Program code is not error Error type error free Why did you choose that type of error? Justify your answer Free program code int Kilometers = 20; circle area = pi * radius * radius; public class AreaCircle { System.out.println("Area of circle is " area of Circle); public class kilometerToMeter { 25 Identify and correct errors double areaCircle; final double pi= 3.142; int radius = 5; Figure 1.44 Program to calculate the area of a circle without error int meter; System.out.println("\n" + kilometers + The "\n" syntax is used to create line spacing . “\n” also indicates to insert a new line of text. "Kilometers" CHAPTER 1 PROGRAMMING public static void main(String[]args){ + public static void main(String[] args) { } } 121 Machine Translated by Google


122 * Variables are used to store input data and output data. 5 * If the user enters the desired variable value, the processor will process the input data value and produce a new value which is the output. To calculate the area of a circle, students can enter any value as an input variable into the ÿj2 formula . If the student enters the input value 5 as the radius value, 5 and In programming, variables are used as a means for the computer to receive, send, process and cause operations on an input. the processor will perform the calculation which is ÿj2 or 3.142 the resulting output is 78.55. Therefore, the value of the input variable is 5 and the value of the output variable is 78.55. public static void main(String[]args){ int radius = 5; Mind Test + areaCircle); wide 78.55 If you enter the input value 8 as the radius value for a cylinder } circle area = pi * radius * radius; radius Value (Variable data) System.out.println("The area of the circle is " Output double areaCircle; Variables Variable items final double pi= 3.142; Input Computer Science Form 4 public class AreaCircle { } 5 with a height of 12 cm, what is the value of the output variable for the volume of the cylinder? Program to calculate the area of a circle 1.5.3 Determining Values for Variables in Certain Parts of the Program Example 55 Machine Translated by Google


https:// goo.gl/ tYR8YL Total price double ticket_price = 45.00; You and your friend went to Zoo Negara to pass the time on the weekend. My Malaysia The Alien Hive game was designed and developed by Appxplore, a video game development company operating in Kuala Lumpur. }} Input public static void main(String[] args) { 3 import java.text.DecimalFormat; + ticket_price DecimalFormat df = new DecimalFormat("#.00"); If there is a 30% discount for schoolchildren, state the input and output variables for the total price of the total ticket price of you and your friend. CHAPTER 1 PROGRAMMING The ticket price for an individual is RM25.00. double sum_price; number_of tickets Mind Test Output int number_of_tickets = 3; Since its launch in 2013, the video game has been downloaded three million times. Variable items This syntax is used to set decimal place values + "RM" + 45.00 " public class Ticket Price { Variables 135.00 System.out.println("\n" + "Ticket price for " "one passenger = df.format(ticket_price)); The program calculates the total price of bus tickets purchased Value (Variable data) Example 56 Azliza and her two friends want to buy bus tickets from Melaka to Johor using the ticket machine at the Melaka bus station. The price of the trip for one passenger is RM45.00. State the input and output variables for buying a bus ticket at a ticket machine. The following is the program code used to calculate the total ticket price to be paid by Azliza and her two friends. Solution Did you know? you ? df = new DecimalFormat; DecimalFormat ("#.00"); DecimalFormat import java.text. 123 Machine Translated by Google


124 Give justification for your answer. Talk to your partner. Identify the value of the data variable for the program below. sugar = 3.00 * 5 * (100 - 3) / 100; double sugar; This website is an easy to use online compiler. You need to type the program code and you will be helped to double purchase_amount; Daily Application This website can be used for many programming languages. double milo; https://repl.it Computer Science Form 4 double liquid_milk; public static void main(String[]args){ purchase_sum = milo + condensed_milk + flour; test and ensure your code is error free. DecimalFormat df = new DecimalFormat("#.00"); import java.text.DecimalFormat; milo = 19.90 * 3 * (100 - 5 ) / 100; public class Calculate_Purchase_Total { liquid_milk = 2.80 * 6 * (100 - 2) / 100; Teamwork What is good style? Let's explore! b Use meaningful variable names. To produce a good and easy-to-understand program, the programmer needs to use a good style such as the following: c Use indents that are comfortable to read. a Placing a comment on each function created. 1.5.4 Generating Readable Programs Using Good Style (Comments, Meaningful Variable Names and Indentation26 Identify the value of a variable in a specific part of a subroutine Machine Translated by Google


Comment Comment Comment Comment “/* */” and “/** */ as comment syntax. The statement is green /* Variable declaration*/ The use of the notation "//" refers to comments. // Variable declaration Comment type The compiler ignores all text that is in /* up to /* even if it is on different lines. /** Variable declaration*/ This comment is a documentation comment. The compiler ignores comments of this type just like comments that use /* and */. , Description The compiler ignores all text starting with the // notation up to the last text in the same line. /**Declaration of input and output variables*/ double Width; + Area); /* A simple program to calculate the Area of a Triangle //Display the output comments Java documentation Step 1: Read the Site public static void main(String[] args){ int Site = 6; } Program with the use of comments CHAPTER 1 PROGRAMMING */*/ Step 4: View Wide // Process involved in enumeration Table 1.15 Types of comments and their descriptions public class AreaTriangle { // area of the triangle Area = (1.0 / 2) * Base * Height; " http:// goo.gl/ iu1SMo Step 2: Read Aloud int Height = 4; System.out.println ("Area of Triangle is : } Step 3: Calculate Area Comment Example 57 125 Comments refer to markers created by the programmer for each built program. Every programming language has specific code for comments. In Java programming, commented code needs to use a predefined syntax. If the syntax is not entered on the comment line in the program, the system will issue a syntax/compile error. Comment notation in Java needs to be done correctly. There are three comment notation styles that can be used: Machine Translated by Google


Meaningful variables Indent 126 int Site = 6; Computer Science Form 4 /* Program to calculate the area of a triangle*/ Area = (1.0 / 2) * Base * Height; public class AreaTriangle { //Display the output // Process involved in enumeration } // area of the triangle Use of meaningful variable names and use of indentation Science Innovation int Height = 4; " Computer double Width; } public static void main(String[] args){ System.out.println ("Area of Triangle is : + Area); You can visit the website to set the indent for your program code https://goo.gl/ CNlMC8 /**Declaration of input and output variables*/ Indent Meaningful Variables To calculate the area of a triangle, the formula used is "1/2 * * q". If the programmer only p declares a variable that should be used as p and q only, the variable name is meaningless. But if the programmer uses the site and height variable names, then other programmers are easy to understand. Example 58 When writing a program, the programmer needs to think of variable names that have a simple spelling and make sense in the program being executed. Refer to example 58. Indentation refers to a way of writing programs that makes reading easier. The reading of the program will start with an indent, i.e. a line of text a few character positions inward, from the left or right margin of the page. Refer to the diagram in example 58. Machine Translated by Google


127 Discuss. Plan and produce programs together with your friends. Adan, Samy and Tan were asked by the teacher to develop a simple program to calculate the volume of a cylinder. The program must be able to receive input data from the user and be able to display output data to the user. The program must be error-free and use programming best practices such as the use of comments, indents and meaningful variable names. You can use the checklist as suggested below. None (b) Criteria Comment (c) The variable character length ranges from 1 to 256 characters. Yes (/) or No (X) mark (a) CHAPTER 1 PROGRAMMING There is Variable means Variables that have two words can be accepted in writing programs without using an underscore (underscore "_") Variable data value The use of simple and meaningful variable names is encouraged in program writing. Input Indent Output Teamwork 3 List the programming style that a programmer should practice. 4 What do you understand by the use of indentation in computer programming? 6 List the factors that affect the readability of program code. Justify your answer. 1 State whether the following statements are true or false. 2 What do you understand about variables in a computer program? Explain. Justify your answer. 5 List three types of errors that often occur in Java programming. Briefly describe two of the three types of errors. Formative Training 1.5 27 Comments, Meaningful variables and Indents Machine Translated by Google


} Computer Science Form 4 System.out.println("The result of division is " df.format(result)); y = "World " public class Result_Division_of_Two_Numbers { import java.text.DecimalFormat; + String x, y, z; z = "Malaysia"; DecimalFormat df = new DecimalFormat("#.00"); x = "Hello "; result = (number1 + number2) / 2.0; int number2 = 6; public class HelloWorld { double results; public static void main(String[] args) { public static void main(String[] args) { } System.out.println(x + y + "to" + "\n" + z); int number1 = 5; } Your program must be able to read degrees Fahrenheit of type double data from the user. Celsius=(5.0 / 9) * (Fahrenheit - 32) Rewrite the program. You need to update the code of the program to make it easier for other programmers to read and understand the program. Emphasize the use of comments and indents in the program. from Fahrenheit to Celsius. The conversion formula is as below. 9 You need to write a program that can calculate and make unit conversions for temperature 7 Below is an example of a program to calculate the division operation for two numbers. 8 Below is a code snippet of a non-error-free program. You need to detect and repair errors in the program by retyping the program in the Java platform environment. State the type of error and suggest the most appropriate way to resolve it. Then, the program can convert that value to Celsius and display the result correct to two decimal points. Emphasize the use of comments and indents in your program. 128 Machine Translated by Google


1.6 STANDARD CONTENTS LEARNING STANDARDS Data Structures and Modular 129 array 1.6.1 Explain the structure of a onedimensional array : (ii) Declare the value (ii) Accumulate the initial value 1.6.4 Write modular programs that contain structures 1.6.3 Differentiate between function and procedure on subature CHAPTER 1 PROGRAMMING way 1.6.2 Using subroutines and understanding the concept of passing parameters to subroutines and returning data Figure 1.45 "Break-and-Manage" is more effective Is this a good method in teaching and learning? A program contains computer code to process data into information. Data needs to be stored in variables so that it can be processed. Computer code instructions and variables are stored in source code files. Computer code should be easy to write, easy to read and simple As an analogy, imagine there is a book called "Semua Mata Pelajaran Form 4" and only one teacher will teach all the subjects. In the book, there are no separate chapters or subtopics. Everything is written in just one paragraph from page one to the last page. Can you imagine the difficulty of writing computer code for such a complex system? Only when needed, the associated group will be called. A simple program may contain only a few lines of commands and variables. For complex programs such as school book loan systems and other information management systems, perhaps hundreds of thousands of command lines and hundreds of variables are neededUse a more systematic structure for variables and commands. Variables can be broken into "small groups" called arrays. Computer instructions can also be broken down into several "small groups" called functions. updated. How? Machine Translated by Google


0 An algorithm is a method of performing certain processes on data such as sorting , searching , finding prime numbers and processing random numbers and graphics. Figure 1.46 A simple variable using only one box What is the difference between an algorithm and a data structure? score Data can be organized in the form of arrays and vectors, linked lists , stacks and queues . What are the disadvantages of arrays ? Computer Science Form 4 Data structure is a specific method to store data in an organized manner in memory so that it is easy to reach for processing to produce information according to the user's needs. Mind Test In this subtopic, you'll study simple variables like memory cells and how they differ from arrays. You will see the advantages of arrays as lists of data compared to simple variables. Such is the case with computer programs. The books in the analogy shown in Figure 1.45 are like variables while the teachers who specialize in the subject are like program instructions in a source code file. An array is a variable that allows the collection of several data values (elements) at a time by storing each element in an indexed memory space. The same is the case with the teachers who teach the knowledge. Teachers who specialize in certain subjects are more knowledgeable in that subject only. If a student wants to ask a Math problem, the student can look for a math teacher to get further explanation. One of the most important data structures is an array. See Figure 1.45. What if the content of a book is divided into separate chapters and bound into several different books? Isn't the knowledge in thick books easier to manage and read? Do you need to bring all the books if the subject is not taught on certain days? Information management systems involve processing a large amount of data. In order to manage data so that it is more organized and easy to achieve, the concept of data structure is introduced. As good as any algorithm, if the data is not organized, data access and processing becomes less efficient. In fact, writing computer code becomes very difficult. A variable is a memory slot that has been reserved to store data. Usually, simple variables only store one data value at a time. See memory space for simple variables below. 130 One Dimension array ) you ? 1.6.1 Array Structure ( Did you know? Machine Translated by Google


Did you know? you ? Figure 1.47 Memory block diagram for a simple variable with a value of 34 score Markah, a room for Integer residents 0 CHAPTER 1 PROGRAMMING http:// goo.gl/ FQql8g Figure 1.48 A simple variable is likened to a house with one room for a specific guest Computers have very large arrays. This is because arrays are the best way to process the very large data found in computers. Fundamental Programming Structures in Java Both of the above steps can be done at once in one command. Example 1: A simple variable analogy: Example 2: What if there is a lot of integer type data that needs to be stored? For example, data of integer type 34, 56, 78, 89, 56 and 95 should be stored in a variable. We just need to declare more variables, right? is a simple variable named score and only allows one value to be stored and that value must be of type int only. If Java needs to store 34 worth of data, just dump the value 34 into the score variable. The Java code can be written as follows. In Java code, variable values are declared with the following syntax: In the following analogy, the variable that has been declared is likened to an empty room that can be occupied by only one occupant at a time. This means, if the data type of the variable is an integer, then the value that can be stored is only an integer. In the following empty house analogy, the name of the house is a mark and this house only allows integer type guests to come and stay. Example 3: Now, try to imagine the house Figure 1.48 shows an analogy for an empty house. This house is called "Bilik Bujang". This house has only one room for one resident only. The occupants must be specific, for example for school staff who are teachers and bachelors. 131 int score = 34 typeDataVariable name; score = 34 int score; Machine Translated by Google


132 you ? Did you know? Arrays are not only available in one dimension but also two dimensions. How to distinguish between these dimensions? Protein: Computer Science Form 4 Java Arrays potatoes, fish, chicken and rice. The foods listed above are considered one dimensional. But, if you classify them according to the food pyramid like proteins, carbohydrates, fats and vitamins, the list becomes two-dimensional. For example, (rice and potatoes) Carbohydrates: Suppose you list all the foods you eat during lunch. For example, http:// goo.gl/ YrU7Qm (fish and chicken) • Declare array names The examples above involve the use of simple data types. A simple data type uses a memory cell as a variable to store a data. is the appropriate name given by the programmer. Each array has a specific data type. An int array holds only integer type elements. The same is the case with double, String and other types of data. In Java code, the syntax for declaring an array structure is as follows: Example 4: What if there are 100 marks to save? The use of variables seems to be less economical if the number of data stored is large. Try to think. Is it okay to declare 100 variables? An array is a collection of one or more pieces of data called elements. In daily life, usually the same data will be stored in a list. In the context of computer programming, a list of data is referred to as an array. The syntax shown above consists of two lines. The first line declares the name of the array. The second line declares the size of the array. typeData refers to the array data type. The "angle bracket" symbol [], is a special symbol to indicate that the variable is an array type and not a simple variable, for example int [] for an integer array, double [] for a double array or String [] for a String array. Array name Array Declaration Array name = new Datatype [Arraysize]; int score2 = 56 typeData [] nameArray; int score3 = 78 int score1 = 34 int score6 = 95 int score5 = 56 typeData [] nameArray; int score4 = 89 Machine Translated by Google


score list 0 0 [5] 0 0 0 [4] [3] 0 [5] score [4] 0 [2] Figure 1.49 Memory space for arrays [1] 0 [2] score list [3] CHAPTER 1 PROGRAMMING 0 Table 1.16 Memory space of simple variables versus array memory space 0 [0] 0 0 [1] 0 [0] 133 Array index starts from zero. So, in the example of six elements, the indices are 0, 1, 2, 3, 4 and 5. Notice that the element values are 0 in each cell. This is because this array has not yet been assigned any value. In this example, the int array type is an integer. The symbol [] refers to the type of the variable which is an array. The name of the array is listScores. Example: The first line must be written before the second line. The declaration of an array named listScores is made in the following order: In the second line, the number of elements in the array is declared. The new keyword is used to set the size of the array. This is followed by the data type of typeData and the size of the array in brackets []. Example: In this example, the array variable can contain six variable elements of type integer, as specified in new int[6]. Six free memory spaces are allocated to store integer type data and all of them are for an array named listScores. Look at the memory space for an array in the following table and compare it to the memory space of a simple variable. Note that arrays are collections of memory cells with a name and an index. • Array size: Simple Variables Array variable int [] listScore; listScore = new int[6]; listScore = new int[6]; Array name = new Datatype [Arraysize]; int [] listScore; Machine Translated by Google


listScores[1] = 56; listScores[3] = 89; listScores[4] = 56; listScores[2] = 78; listScores[0] = 34; listScores[5] = 95; Did you know? you ? In computer memory, the elements in an array are always placed next to each other in a block of memory. After declaration, values are accumulated by calling the array elements one by one: See the analogy in Figure 1.50. Imagine a long building with the name Asrama Bujang. There are six rooms for a single teacher for each one. Note that each room has a room name that uses an index. An index is a list of numbers starting from zero. The index makes it easier for "AsramaBujang" building owners to track which rooms are empty and update the room status. For example, the room numbers are no[0], no[1], no[2], no[3], no[4] and no[5]. Array declarations provide memory space that is still free. Because of this, value needs to be given through the process of concentration. 134 Array Compilation Index 1 Figure 1.50 An analogy for an array type variable is a building with many rooms Array name • The name of room no[5] is the sixth room. • Room name no[6] does not exist in this example. The elements 56 2 Figure 1.51 A memory cell showing the elements in an array • The rooms with names no[0] - no[5] are Single Dormitory building type. 95 Computer Science Form 4 • The first room is no[0]. 56 78 0 Let's think for a moment. 89 3 5 listAge 4 34 Machine Translated by Google


[5] Mind Test 56 89 [0] Arrays score [4] 78 What happens if a variable is not declared first? score Table 1.17 Simple variable memory block diagram versus array memory block diagram [3] [1] [2] 34 56 95 [2] score list 78 CHAPTER 1 PROGRAMMING http:// goo.gl/ JiHxCA 56 [0] 34 [1] 34 int [] listScore = {34,56,78,89,56,95} { } Initial value concentration int [] score = {56,78,34}; // array public static void main(String [] args) Memory Structure Differences between Simple Variables and Array Memory Initialization of Array Values 135 Simple Variables Array variable The size of the array is determined automatically by concatenating the values based on the number of data in the curly braces "{" and "}". All data to be stored is of the same type. Let's say a teacher wants to record the marks for the Information Technology (TM) subject he is teaching. In the program segment below shows an example of the difference between declaring a simple variable and declaring an array: In computer memory, this information is stored as follows: Declaration The combination of data type int and brackets [] is to declare the name listScore as an integer array variable. Because the initial stack is used, the size of the array does not need to be enclosed in the [] declaration brackets. In initial value stacking, stacking is done at the time of declaration. For example: Machine Translated by Google


Programs that Use Arrays Good luck! 34 and friends score 3 Array class Mind Test trying to find score 1 56 marks2 that? Try you What is an array class Computer Science Form 4 consists of various static methods 78 which aims to find arrays, compare arrays and populate array elements. the answer. Elements can be called using an array index. For example, the following array is declared: In the computer memory, this information is stored as follows: This is different from declaring without using an array. Each data will be stored in a different variable and placed in the memory space at a different location as shown in the diagram below: Data is stored in different addresses in memory. What happens if the teacher wants to add score data? Does the teacher need to declare a different additional variable to hold the score values? Imagine if the data to be added is a lot and the data will be stored randomly in any location and not organized. This will cause the process of accessing data from memory to be processed to produce information will be slow because the data is placed in a different address space in memory. use the following syntax to call the elements. All score data is stored in a single variable name, the score variable. If there is an addition of score data, the teacher only needs to add the data value without declaring a new variable name. Data is stored sequentially in memory space. The above arrays each have three elements with indices 0, 1 and 2. Therefore, In the Mark list example, each element is called with the following program codes: 136 int [] listScore = {86,78,80}; array_name[index] • listScore[2] will return the value 80 • listScore[1] will return the value 78 } public static void main(String [] args) • listScores[0] will return the value 86 { int score1 = 56, score2 = 78, score3 = 34; Machine Translated by Google


137 [0] weekday "Sunday" String [] Weekdays = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", (i) System.out.println(weekday[7]) (iii) System.out.println(weekday["3"]) "Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday" (i) System.out.println(weekday[0]) (iii) System.out.println(weekday[6]) [6] (ii) System.out.println(weekday[3]) (iv) System.out.println(weekday[4]) [2] [3] [4] "Sunday"}; (ii) System.out.println(weekday[10]) (iv)System.outprintln(weekday[Tuesday]) [1] CHAPTER 1 PROGRAMMING [5] Example 59 Example 59 describes the weekday array. This array contains string type data (String). The elements in the array are the names of the days of the week. Note that the order of the elements is important because they follow index order. Remember the first index number in the array? (iv) Friday (iii) Sunday Solution: (ii) Runtime error daysWeek[10] outside the bounds of the array. (d) Why can't the following codes be used? Given an array of weekdays as follows: (c) (i) Monday weekday. In an array memory block, the arrangement of elements is in sequential order. (ii) Thursday Each element is referenced using a block name followed by an index number. (b ) What is the size of the weekday array? (a) System.out.println(weekday[4]); (iii) Syntax errors . Element calls are not allowed because the index is not an integer but a String. (iv) Syntax errors . Element calls are not allowed because they do not use index numbers. (c) What value does the following code print? (b) 7 (e) The elements in an array are always placed next to each other in the same memory block. Array names refer to blocks of memory. In the example above, the name of the block is (d) (i) Weekday[7] runtime error out of bounds of array. (a) Write the Java code to print the element "Friday". (e) Draw a memory block diagram for the array above. Make sure the drawing contains the array name, index and elements. Machine Translated by Google


Solution: (a) List the three array variables in the above program. (ii) 17 (c) Determine the output of the program above. (b) (i) People Provided full Java program code. (iii) High list[3] (i) listName[2] (ii) Age list[1] (a) Name list, Age list, Height list (c) (b) Write the elements for the following code: (iii) 175.0 138 My software package; public class MyClass { public static void main(String[] args){ System.out.print(listNames[i] + "\t"); System.out.print(listAge[i] + "\t"); System.out.print(listHeight[i]); System.out.println(); } Computer Science Form 4 double [] listHeight = {182.1,172.5,173.2,175.0}; System.out.println("NAME\tAGE\tHEIGHT(cm)"); for(int i=0;i<4;i++){ } int [] listAge = {16, 17, 16, 17}; } String [] listName = new String[4]; listNames[0] = "Adam"; listNames[1] = "Alia"; listNames[2] = "People"; listNames[3] = "Devi"; Example 60 Machine Translated by Google


athlete[4] = "Pandelela"; "Malaysia","Singapore","Thailand", "Vietnam"}; athlete[0] = "Misbun"; athlete[2] = "Chong Wei"; athlete[5] = "Rajagopal"; 28 Arrays 1.6.2 Using Subatur [0] ASEAN countries "Brunei" "Cambodia" "Philippines" "Indonesia" Null State the differences you can find between the array and the array you have studied. "Malaysia" "Singapore" "Thailand" "Vietnam" [5] [5] athlete Null Apart from the arrays we have studied, there are also some other types of arrays. What type of array is it? "Malaysia" [1] [4] "Chong Wei" CHAPTER 1 PROGRAMMING [3] "Laos" [4] "Pandelela" "Rajagopal" [6] [0] Mind Test [7] [1] my country [2] [2] "Misbun" [8] [3] Ways, Understanding Concepts Passing Parameters to Subroutines and Returning Data Take a piece of A4 paper. Draw a memory block for the following statements: Once your memory block is ready to be drawn, compare your answer with the answer below. Answer: The principal will divide the teaching duties among the teachers under his management. In everyday life, heavy responsibilities are usually divided into tasks to be carried out separately. Small tasks are easier to monitor and execute. For example, the responsibility of educating students is the task of the school. (b) String [] countriesASEAN = {"Brunei","Cambodia","Philippines", "Indonesia","Laos", (a) (b) (a) String my country = "Malaysia"; (c) (c) String [] athlete = new String [6]; Individual Activities 139 Machine Translated by Google


140 Without modularization After modularization Figure 1.52 Subprogramming is a method of modularization, similar to the division of tasks among teachers Main module 2 Organize tasks Science teacher Method 1 4 Receive the results of the assignment 3 Directing the execution of tasks (Subprogram 3) Module Figure 1.53 Modularization of computer code Principal Module Computer Science Form 4 1 Dividing tasks Malay teacher (play subroutine) play() only Module (Subprogram 2) way 3 English teacher Mathematics teacher method 2 (Subprogram 1) (Subprogram 4) Such is the case with computer programs. Long computer code files, perhaps tens to thousands of lines, are difficult to write, read, review or update. Therefore, related lines of computer code can be assembled into a single module. Thus, long computer codes can be divided into modules. Each module is shorter and specializes in a specific purpose. Machine Translated by Google


141 Return data type Name Container (Body) static void subSet01 () Special keywords (headers) System.out.println("Hello world."); } Body parameters way static void subAtur01() subature Header { It's easier to tackle computer projects CHAPTER 1 PROGRAMMING Easier to test, debug and repair Allows programming tasks to be divided among different group members The main() subroutine is used to execute all types of Java programs . Complex projects become simpler way to reuse Advantages of using a module or substructure structure Figure 1.54 Advantages of using modules or software Easier These modules are called subsystems. A subprogram is a structure for a collection of computer code. Among the list of statements found in a subprogram is, • process data • display information A subsystem has a head and a body. An example of a program is as follows. The subroutine header has the following components: • accept data input you ? Did you know? Machine Translated by Google


Click to View FlipBook Version