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

3.3 INPUT NUMBER_BALL END_WHILE Computer Science Form 4 8 1 Each student is asked to take out a piece of blank paper approximately A4 in size. 6 At the end of the activity, the teacher shows his answers to the students and asks the students to count the number of correct answers. Setup: This activity can be done in class. 2 The teacher will write the following game rules on the board: 4 The teacher will ask the students to write the answer in A4 paper as "OUTPUT number_ball". Sample answer: 4 The teacher put all 12 ping pong balls into a cloth sack. 5 Continue the activity until the ball removed from the sack is a negative number. Teamwork 2 The ping pong balls are given a number each from 0 to 9. Class activities: 4. END 42 3 Two more ping pong balls are given negative numbers, namely -1 and -2. 3 Start the activity. The teacher will take the ball from the sack and show it to the class. The teacher asks the students to see the number on the ping pong table as "INPUT number_ball". The teacher will write the answers on the teacher's A4 paper. The removed ball is not put back into the sack. Repeat Control 1. START 31745968 1 The teacher prepares 12 ping pong balls. 2. INPUT NUMBER_BALL 3. WHILE NUMBER_BALL > -1 START_WHILE 3.1 OUTPUT NUMBER_BALL 3.2 TAKE THE BALL FROM THE SACK Machine Translated by Google


43 Research operations analysts solve problems and create data-driven strategies in areas such as logistics and finance. Figure 1.18 Flowchart of writing an algorithm to produce a program. Error Difficult to understand Correction • Efficient, ie the algorithm works quickly and does not consume a lot of memory space. Figure 1.19 Relationship between algorithm errors and program errors Test the algorithm Does not meet the criteria Computer Algorithms are tested after being written for debugging purposes. Algorithm testing is done before the algorithm is written as computer code. See Figure 1.18. This is because, corrections at the code level take longer and are more expensive than corrections at the algorithm level. Error Error in Algorithm Test run error The algorithm that has been tested has the following characteristics: algorithm The goal of algorithm testing is to ensure that the logic of the algorithm is correct and to think about improving the algorithm so that it is more efficient. Analysts of this department are constantly working to find improvements to data operations so as not to disrupt data programs and constantly monitor data organization processes. Incomplete • Meet the software design criteria to be developed. Programming CHAPTER 1 PROGRAMMING organizer • Complete, which meets all the requirements of problem solving. Syntax error logic Write the algorithm • Easy to understand, so easy to write as a computer program. Carelessness Algorithms that do not meet the criteria will be difficult to understand, incomplete, less efficient and do not meet the software design criteria. This will result in the resulting software containing errors. This is because programmers rely on algorithms to produce programs. An algorithm that contains errors will cause the programmer to produce a program that also contains errors. The diagram below shows the relationship between algorithm errors and program errors. Inefficient 1.2.3 Testing and Fixing Errors in Algorithms Career Science Machine Translated by Google


incorrect conditional logic. To prevent these errors from occurring in the program, the algorithm must be easy to understand by the programmer, complete and meet the design criteria. Incorrect function Runtime errors include programs that fail to start, become very slow or unresponsive. These errors can be identified from output failures and warning displays in the program. Inaccurate output Example The algorithm does not display the decimal point for the area of the circle causing a loss of accuracy. • Division by zero. Table 1.4 Examples of logical errors Runtime errors can be traced to inefficient or incorrect algorithm design. For example: Did you know? (a) Syntax error – does not exist in the algorithm. Syntax errors occur due to careless use of programming languages such as Java. Syntax errors are usually found automatically by the programming language compiler software. Algorithm errors do not cause syntax errors. Desk-checking 44 Purpose of desk-checking Exception in thread "main" java.lang. The algorithm uses the circumference formula for the area of a circle. Example: You ? Algorithms can be tested manually, i.e. using paper and pen. This technique is called desk-checking. Computer Science Form 4 (c) Run-time errors – errors that arise when the program is executed. This error is caused by the use of inappropriate data types or incorrect stacking. Type of logic error • Repetition control structure that cannot stop because • Variables do not contain values or objects. This error is caused by carelessness until ignoring the criteria of the program. Incomplete function done before the algorithm is written as computer code. This is because corrections at the code level take longer than corrections at the algorithm level. (b) Logical errors – logical errors occur because the software produced does not perform the functions it should, is incomplete or the function produces inaccurate output. The algorithm is supposed to give two outputs which are the circumference and area of the circle but after testing, only one output has been displayed. • Incorrect sequence control structure. is a check whether the algorithm works with the correct logic or otherwise. NullPointerException Algorithm testing can prevent algorithm errors. Algorithm errors can cause two types of errors in the program that will be produced from the algorithm, see Table 1.4. This error is caused by an incorrect expression. Machine Translated by Google


1 Q1 So, if the age input is 18, the expected output is the application is allowed. The same goes for the age of 20, 30 and above. However, the age of 15 does not meet the requirements, therefore it is not allowed. The analysis can be summarized in the table shown below. 2 Identify "Obtained Output" Expected Output No Pn – nth variable 30 goo.gl/7BImwg The age to apply for a driver's license is 17 years and above. One of the systematic methods is to use the algorithm level testing table. This schedule ensures that each level in the algorithm is tested. The table format is as shown below. Doing a desk-check Not allowed Identify the values of some input-output pairs without using an algorithm. These values are easily known by testers based on criteria/ Algorithm testing is manual and thorough checking. Test input No – line number in the algorithm I/O Mrs Try to analyze the following situation: Applications are allowed 4 Analyze and improve the algorithm. Applications are allowed 3 Compare "Obtained Output" with "Expected Output". Mind Test Q2 2 15 Analysis: 1 Identify "Expected Output" Table 1.5 Examples of logical errors I/O – Input/Output 45 The goal of the review is to ensure that the algorithm is working with the correct logic. Test the algorithm using the input for the output that has been identified in step 1. The output obtained through the algorithm process is the "Obtained Output". Examples based on criteria: 20 P1 – the first variable 18 Algorithm testing is also known as desk-checking because this technique uses paper and pencil. Algorithm testing should be done systematically. Generally, testing involves the following steps: general facts or manual calculations. Step 2: Define "Obtained Output" P2 – the second variable CHAPTER 1 PROGRAMMING 3 Eligible height to join the basketball team is 170 cm and above. Make sure your analysis includes tested input information and expected output. Applications are allowed Algorithm Testing Steps Step 1: Identify the "Expected Output" Indicators: Machine Translated by Google


Applications are allowed Expected" Applications are allowed Expected Output 4 Not allowed (c) The next columns are for each variable. pseudocode. 15 Applications are allowed 2 Identify the variables used in the pseudocode. This is important because these variables will produce the columns of the table. can be used in our daily life. For example, our target for each subject is an A in the exam. Our targets are categorized as expected outputs. After the exam, the result we get is the output obtained either A, B, C and so on. If we do not reach the target, we will repair our weaknesses. The same is true of the concept found on desk ckecking. 1 3 Computer Science Form 4 Computer support specialists serve the public such as providing customer service and employees in the information technology department to help other employees. Computer support specialists focus on issues with data and communication networks. Applications are allowed 18 Not allowed Applications are allowed 15 Step 3: Compare "Obtained Output" with "Output Test input 3 Output Obtained (b) The first column is for row numbers. 1 Make sure the pseudocode has a number for each line. Concept used in desk checking # 2 Not allowed Computer 20 Expected Output Career Science Applications are allowed Output Obtained Applications are allowed Examples of processes in each level are such as receiving input through I/O columns, accumulating values in variable columns, changing data values in variable columns and displaying results in I/O columns. The output obtained through the algorithm process is called "Obtained Output". Example algorithm results WITHOUT errors: 2 4 (e) Number of table rows = number of algorithm level rows. Refer Applications are allowed 20 To produce Table 1.5 efficiently, make sure the following things are implemented: Daily Application Not allowed Test input 1 Not allowed Example algorithm results WITH errors: Not allowed (d) The last column of I/O is for user input and output 18 3 In the table you want to draw, enter 1 as the first line number for START and end with the last line number of the pseudocode. Not allowed 30 (a) Number of columns = number of variables + 2 acquired. 30 Applications are allowed # 46 If the "Obtained Output" equals the "Expected Output", the algorithm may be error-free. Repeat the above steps with several other "Expected Outputs" for verification. Machine Translated by Google


If not, check the language usage. Use simple, concise and consistent language. ? (e) If the condition in the loop structure is always "True", check the condition expression for errors to update the variable's value. (c) If the condition of the optional control structure always produces only "True" or only "False" all the time, remove one of the optional branches and change it to a sequential control structure. 3 Check the expression 1 Difficult to understand: Are the lines of the algorithm easy to follow at the moment CHAPTER 1 PROGRAMMING 2 Check the stack (c) Make sure the values are assigned to the appropriate variables. 5 Check the condition of the control structure Difficult to understand 3 Inefficient: Is the sequence and structure of the algorithm complex? required? (a) Check the expressions used for any mistakes. Algorithm error 4 Does not meet the criteria: Is the "Obtained Output" different from the "Expected Output"? Incomplete 2 Incomplete: Does the algorithm perform all the functions that (d) If the condition in the repetition structure is always "False", check if the repetition block is really needed. testing? 4 Check the sequence is correct 47 goo.gl/HWyvu2 Does not meet the criteria (b) Check the condition in the choice control structure and the repetition control structure so that it can produce both "True" or "False" results. (a) Statements that are not directly used should be discarded. 1 Check the variable name 6 Check the control structure branch An algorithm for error correcting cyclic redundancy checks If not, add lines of pseudocode for functions that are not included. (b) Check the order of the algorithm lines so that it is logical. Step 4: Fix Errors In Algorithms Inefficient Machine Translated by Google


48 Variable: name 1 Identify the "Expected Output": INPUT NAME 1. Start Computer Science Form 4 3 (a) Make sure each command line in the pseudocode is assigned a number. Based on Example 17, check if the following algorithm is error-free. Finished Finished Solution: Start INPUT NAME Check if the following algorithm is error free. This algorithm asks for a name input from the user and displays "Hello" followed by the input name as output. Expected Output No I/O Adam 3. DISPLAY "HELLO" Finished 2. INPUT NAME SHOW "HELLO" Test input (c) Draw the algorithm level testing schedule: Example: Follow these steps: Start (b) List all the variables in the algorithm: 4 SHOW "HELLO" STAY" 2 Define "Obtained Output" 1 Hello Adam Mind Test DISPLAY “SAFE INPUT NAME 2 This algorithm asks for a name input from the user and displays “Goodbye” followed by the input name as output. 4. End Example 17 Start Name Machine Translated by Google


2 Test input No 1 "Adam" Zhi-Yi Hello name?"Adam" Career Science Note: "null" is the value of a text data type variable that has not been populated with any value. (f) Compare "Obtained Output" with "Expected Output". In the following example, it appears that "Obtained Output" is different from "Expected Output". To confirm the results, repeat with other test inputs. CHAPTER 1 PROGRAMMING I/O – 2 No null Adam Hello Darshini Output Obtained I/O 4 Information security analysts play an important role in maintaining the confidentiality of an organization. "hello" null Name Expected Output 3 49 3 (e) Execute the instructions in each line. Those instructions may change the data in the variable. Update the data value of each variable on each row. Computer # Hello Zhi-Yi In conclusion, the algorithm contains errors. An error is an input failure displayed in the output. Hello 4 "Adam" Hello Adam 2 Name 3 Output Obtained: Hello Darshini Hello 1 – (d) Draw the algorithm level testing schedule: They examine the information technology security system and recommend security measures, including fixing the weaknesses of an organization's information technology system. 1 Machine Translated by Google


RM 0.40 Computer Science Form 4 and repaired? + name + name Hello Adam RM 0.50 3. After that, compare the price of food you expect with the actual price of food in your school canteen. Apply what you have learned about desk checking. RM1.50 Adam goo.gl/a1n26U What is the difference between an algorithm error and a program error? Hello Darshini 2. Then, go to your school canteen and construct a price table of the same food found Logic errors in Java Hello Zhi-Yi 4. End The line number that produces the inaccurate output is the third line. The associated line of pseudocode is: Expected Output You and your friends want to compare the prices of food sold in your school canteen with your expected prices. Do this activity based on the following instructions. MI Goreng 50 9 # Zhi-Yi 1. Start 2 So, the repaired pseudocode looks like the following: Mind Test Group activity The name of the food in your school canteen. Build a table as in instruction 1. Hello Adam Between algorithmic errors and program errors, which is easier to detect? Upon inspection, it seems clear that the name variable containing the user input is not in that line. Fix that line: 3. Display "Hello " Hello Darshini RM 1.50 Confectionery (one) Darshini The test is done several times for verification. 1 1. Create a table of food prices that you and your friends expect. For example, the price of a plate of nasi lemak, fried noodles, syrup, and sweets. An example table is as follows: Output Obtained 3. Display "Hello" Repeat the testing steps using the corrected pseudocode. This time, the result of "Obtained Output" matches "Expected Output". 3 Expected price Syrup Nasi lemak Test input Hello Zhi-Yi 3 Fixed errors in the algorithm. 2. Input name 3. Display "Hello" Desk checking Machine Translated by Google


Example 18 shows that the value of the variable z is changed several times. In algorithm line 2, z is accumulated with a value of 100, but in line 3 it is changed to 50. In line 4, the value of z is multiplied by 4 to 200. The algorithm of line 5 adds 25% of the value of z which is 50 to the original value of z which is 200 making the value new z is 250. In line 6, the value of z is unchanged at 250. While in line 7, all values are cleared because the algorithm has finished. Algorithms accumulate and change the value of a variable. Therefore, the value of the variable is not constant. Each line of the algorithm may make changes to certain variables. A variable table is used to track variable values at each level of the algorithm. Examples are as follows: Example 18 *4 250 – 4. z = z – 5. z = z – – Analysis of Algorithms Mind Test goo.gl/ukdHpQ – 2. Input z = 100 * 0.25 + z 50 3. z = z/2 – 200 – CHAPTER 1 PROGRAMMING 6. DISPLAY z 1. Start 7. End Each Level in the Algorithm The following algorithm accumulates the variable z with a value of 100, then divides by 2, multiplies by 4 and increases by 25%. What is the value of z in each line of the following algorithm? c. Identify the variable and set up a special column of the variable z. Z b. Identify and prepare the input and output columns of the program. This column is required to identify user input and program generated output. No a. Draw a numbered table for each line of code above. I/O Solution: 1.2.4 Detection of Variable Values on 51 7 100 17, give the value of z if the variable z is accumulated with a value of 75, then divided by 5, multiplied by 9 and added by 30%. 250 100 1 4 Based on Example 2 5 250 3 6 Machine Translated by Google


The value of the variable changes as the algorithm changes 2. INPUT x 6. End Computer Science Form 4 goo.gl/mTFyW3 5. DISPLAY total 1. Start 4. total = x + y Mind Test 3. INPUT y 1.2.5 Identifying Outputs Test your skills by browsing the website below. Example 19 1. Form a group with four members. 8. After that, build a representation of the algorithm based on the variables and all the numbers as well 4. The second member has to choose a number between numbers 11-20. Do this activity according to the following instructions. Determine whether the above algorithm is correct. 7. Combine all the numbers and arithmetic operations you choose. 3. The first member has to choose a number from 1 to 10. 9. Build a table to find out the value of y in each line of the algorithm you have built. 6. The fourth member also needs to choose an arithmetic operation either "+", "-" and "x". The following algorithm accepts two numbers and displays the sum as follows: 2. Each group is given a variable which is y which is accumulated with a value of 60. arithmetic operation of your choice. 5. Then, the third member has to choose an arithmetic operation either "+", "-" and "x". 10 52 If the output of the algorithm is correct, the output of the algorithm should be Comparing the output is expected to be the only way to determine the validity of the algorithm output. Output is expected to be determined manually, i.e. manual calculation. The correct output depends on the value of the variable when the display algorithm is called. In Example 18, the display is made on the sixth line. Therefore, only the z value in the sixth row is used, which is 250. equivalent to the expected output. Is the output determined using the correct algorithm? Group activity which is Correct from the Algorithm Based on the Input Given Machine Translated by Google


Y Mind Test No y Amount I/O CHAPTER 1 PROGRAMMING 53 88 – – 12 6 – 100 2 – – 12 Based on Example 19, try replacing the value of x with the integer 5 and y with the integer 31. 5 – – 1 12 + 88 = 100 – Total = 100 12 4 88 – – 88 12 – – – 3 – 5 Compare the output of the algorithm with the expected output. 1 Define the variables: x, y, sum So, the algorithm has achieved the accuracy of the value in the test above. Algorithm output, total is 100. (a) The user enters the integer 12 when the program asks for input for 2 Use appropriate test data: 4 Draw a table. Algorithm output, total is 100. To check the answer for certainty, use different input values and determine the expected output. 100. This amount is equal to the expected output. Solution: variable y. Answer: To double-check the answer for certainty, use different input values and determine the expected output. 3 Expected result: Calculate x + y = 12 + 88. So, the expected output is For input x = 12 and y = 88, the expected output is 100 (sum). This amount is equal to the expected output. variable x. (a) The effect of variable values on each line of the algorithm. So, the algorithm has achieved the accuracy of the value in the test above. (b) The user enters the integer 88 when the program asks for input for (b) Identify the output of the algorithm based on the input. Machine Translated by Google


Each line of the designed algorithm can be converted to computer code. The algorithm is universal. Therefore, the symbols and words used do not need to rely on any programming language. Many more programming languages are often used including Visual Basic (VB), Java, C# and others. 1.2.6 Algorithm Translation into Programming Language Example 20 11 Pair Activity Chew An and Jamilah want to borrow a Form 4 Computer Science reference book at her school. Solution: You and your friend are given two situations. Translate the given situation into algorithmic form and Java computer code. Good luck! Situation 2 Translate each line of the algorithm into perfect computer code. Ramesh invited his mother and father to go on vacation in Perak during the school holidays. He made plans to visit the Taiping Zoo during the holiday. His parents have agreed to Ramesh's plan. To avoid congestion when queuing to buy tickets to enter the zoo, Ramesh decided to buy tickets online. Help Ramesh buy tickets online by using algorithms and translate them into computer code. Help Chew An and Jamilah to borrow the book by using the algorithm and translate it into computer code. Situation 1 Did you know? you ? Computer Science Form 4 public static void main(String[] args){ System.out.println("Hello " System.out.print("Enter username: "); DISPLAY "How are you", name, "?" + name); Algorithm Finished Computer code (Java) nextLine(); Translating algorithms into programming languages INPUT name Apart from Java, there are many other programming languages that have been developed by programmers. Among the popular programming languages are Python, Forth, Perl, Lua, Smalltalk, Logo and Ruby. Start } String name = new java.util.Scanner(System.in). SHOW "Username:" 54 Machine Translated by Google


) (c) Draw a flowchart for the solution algorithm. 1 Write an algorithm that can determine the wall area of a room after taking into account (a) Algorithm testing is done after the Java code is written. (b) Logical errors are caused by algorithmic errors (c) Syntax errors are caused by algorithmic errors. (d) One of the causes of algorithm errors is failure to meet criteria. using a repeating control structure. Next, the application produces an average output of the five numbers. 2 Based on question 1, modify the algorithm to determine the cost of painting a room after the cost per square foot is entered. window dimensions. ( ( ( ( Write an algorithm to solve this problem. (a) Construct an IPO analysis. (b) Define pseudocode for Obtained Output. 5 Draw a flowchart for a program that accepts two numbers and then displays the average. 8 An application receives and sums five integer numbers from the user (c) If there is an error, suggest a fix for the error. 6 Determine whether the following statements are "True" or "False": 4 Write pseudocode for a program that accepts the radius of a circle and determines the circumference and area ) 9 Generate an algorithm for a program to calculate the circumference of a circle with a given radius in meters. It is known that the formula for calculating circumference is 2 x PI x radius. (PI = 3.142) the circle. 7 Let's say you live in Kemaman and need to commute to Kuantan. You want to know whether driving a car or taking a bus is more economical. You also know the bus ticket price from Kemaman to Kuantan and the travel distance and petrol cost per kilometer. (a) Do an analysis to determine the Expected Output. 3 Write pseudocode for a program that has received two numbers and displays the sum ) (b) Generate the appropriate pseudocode. as output. ) 55 CHAPTER 1 PROGRAMMING Formative Training 1.2 Machine Translated by Google


1.3.1 Explain the relationship between data type, data size and computer memory capacity 1.3.2 Choose and use appropriate data types: Integer ( int), real number (float, double), character (char), string and Boolean. 1.3.4 Declaring, initializing and assigning values to variables and constants 1.3.5 Using stacking statements and arithmetic statements Computer Science Form 4 1.3.6 Write a program to enter input from the keyboard and display the output 1.3.3 Differentiate global and local variables In the programming process, a programmer needs to declare the type of data required in a program to be executed. The value of the variable is always changing during the execution of the processing and will not hold any value after the program ends. The programmer needs to give a name to each variable that is used to solve a problem in the developed program. Programmers use variable names as reference names for specific values of that variable. Variables or constants in Java, need to be declared before being used. The concept and procedure is the same as wanting to travel abroad, that is, an individual needs to declare the items in the luggage at the Customs office. Another example is in the situation of the cost of a pair of shoes. This input item needs to be given a variable name because the cost of a pair of shoes may change depending on the type of shoe. The variable name should be consistent with the variable value. In this case, the variable name is costShoes because this name refers to the cost of a pair of shoes. If the cost of a pair of shoes changes, the value of the variable will change but the name of the variable will not. Variables are temporary storage spaces for numbers, text and objects. A variable is an element in programming and its value can change at any time during the programming process. For example, The computer will use the name of the variable as a reference to find the value of the variable in its memory. kosShoes kosShoes The name remains the same RM56.00 RM34.00 Values change 1.3 Variables, Constants and Data Types } public static void main(String[] args) { float length, width, width; public class countArea { CONTENTS STANDARD LEARNING STANDARDS Variables 56 Machine Translated by Google


? https://goo.gl/tXAp65 Types, values and variables (ii) /* Variable declaration*/ You will find more comment notation hereafter. (iii) /** Variable declaration*/ final double Singapore_Dolar_to_Malaysia_Ringgit = 3.03; Take a look at the example constant declaration shown below. (i) //Variable declaration Table 1.6 Data types and examples of permitted value usage CHAPTER 1 PROGRAMMING The text in green is known as a comment. Comments are markers created by programmers for each program that is built. In Java, there is a predefined syntax for comments. Among the three comment notation styles that can be used are, For more information on comments, please refer to subtopic 1.5. Sample value Maximum 3.4e38 4 stanzas One character only Integer Ranging from 0 to no limit false _ Data types Maximum 3.4e38 char String Minimum -1.7e308 Boolean 2 stanzas >10 bytes 1 bit Minimum -2147483648 double Minimum -3.4e38 Maximum 2147483647 8 bytes True _ Computer Memory Capacity float 4 stanzas final int NUMBER_DAYS_IN_WEEK = 7; //Variable declaration //Declaration of constants //Declaration of constants //Declaration of constants final int NUMBER_OF_HOURS_IN_A_DAY = 24; final double pi = 3.142; A data type in a programming language refers to a set of data that has predetermined values and characteristics. The types of data and examples of the use of allowed values are as in Table 1.6. will be processed to produce output for an existing problem. Data types can be categorized into two classes, namely primitive data and non-primitive data. During the programming process, the value of the constant is fixed and will not change. Constants are usually used when the programmer wants to declare a value that does not change. For example, values Data is an element that plays an important role in programming. Data entered in programming The declared data type must match the value. For example, a constant of type integer must assign an integer value. Pi (ÿ), the number of days in a week, the number of hours in a day, the exchange rate of Malaysian currency and so on. If you want to use a value like this, the programmer needs to declare it as a constant. For example, final double pi = 3.142; //Declaration of constants Data Types Constant 57 Did you know? You Machine Translated by Google


12 http://goo.gl/qba9Qr Integer Primitive data can also be known as unstructured data. long double Data type category Primitive data Character Data consists of two types namely primitive data and non-primitive data. Figure 1.20 Data types in programming languages Array bytes Malaysian ICT Volunteers or 'Malaysia ICT Volunteer' (MIV) is an ICT volunteer program that aims to provide volunteer services to help communities in areas that have been identified in terms of the use of ICT equipment and ICT development in the community. Computer Science Form 4 bytes Non-primitive data is data whose values consist of some combination of elementary values. Not primitive Data is not primitive Primitive Real numbers float Integral Primitive data is data whose value is in its most basic form and cannot be simplified further. Figures short int Data types Boolean char Non-primitive data can also be known as structured data. String My Malaysia Teamwork 1.3.1 Relationship between Data Type, Data Size and Computer Memory Capacity Did you know? you ? 58 2 Give three other examples of situations. Based on the previous example A programmer wants to develop a student information system. 3 Present the results of your group discussion. given, repeat steps in 1(a) and (b). (b) categories of data types Based on the statement above, discuss with the group members about, 1 (a) the type of data required Each data type and data size will be stored in the computer's memory. Variable names play an important role in determining the size of data in memory. Based on the type of data used in the variable, the operating system will determine what can be stored in the computer's memory. The variety of use of data types on variables can save space on computer memory. Therefore, the use of appropriate data types Machine Translated by Google


You are required to be in a small group and open an Examination Analysis System (SAPS) account. Based on the exam slip displayed, list how many types of data and and the computer memory capacity used for each data that has been listed. Teamwork Appropriate Data Types 13 you get job opportunities in the ICT field http://goo.gl/c2AD4e Daily Application the first and largest in Malaysia. Let's learn simple Java code ! http://goo.gl/nDmQr9 Dagang Net is a GLC company that provides services to conduct business through e-commerce which is a strategic tool for business. Dagang Net is an e-commerce service provider Science Innovation CHAPTER 1 PROGRAMMING Data types and computer memory capacity http://goo.gl/9JuhTe Open source knowledge makes it easy Computer 1.3.2 Selection and Use required for long values in order to save computer memory space. Table 1.6 on page 57 shows the amount of memory used to store data types for variables in computer memory. This memory is stored in units of bytes (bytes). The selection and use of appropriate data is very important in a program so that the program can be developed without syntax errors. The data types of variables and constants determine the type of information to be stored in the allocated memory space. The use of the appropriate data type also serves as a benchmark to a variable whether the variable stores constant data, countable data, letters, decimal numbers or data that has a true or false option. Data Types Computer Memory Capacity 59 Machine Translated by Google


Example Example "//" is used when you want to describe the command code that is in one line. 60 Computer Science Form 4 int first_number, second_number, answer; float height1, base1;//Variable declaration first_number = 10; answer = first_number + second_number; double wide;//Variable declaration second_number = 20; Real numbers double Integers include all numbers that have no fractions or decimals. An integer is a native number larger than a byte. Integers can have values between –2147483648 to 2147483648. float, Integer What to do to declare a variable? What is an integer? The programmer needs to use the integer keyword. What to do to declare a variable that can store large decimal numbers? DATA TYPES A real number is a number that consists of all numbers that have a decimal point or a fractional part. Real numbers have values between: 1.79769313486231e308 to 4.94065645841247e-324, if the number is negative, and 1.79769313486231E308 to 4.94065645841247E-324, if the number is positive. int Programmers need to use the Double keyword. What are real numbers? Machine Translated by Google


Example Example CHAPTER 1 PROGRAMMING 61 boolean forLeft = false; boolean forStraight = true; char ampersand = '@'; String email_address = "[email protected]"; boolean forRight = false; What is Boolean? char/ What are characters/strings? String Boolean The programmer needs to use the String data type. (False). What to do to declare a variable? Character/string What to do to declare a string variable? Boolean is data in the form of an option, that is choosing one of something "true" (True) or "false" The programmer needs to use the "true" or "false" keyword. Characters and strings are data in the form of spaces , text, words or values that contain a sequence of characters or symbols. Machine Translated by Google


Computer Data types Computer Science Form 4 Career Science https://goo.gl/bM8nG6 https://goo.gl/8zj0zW Computer http://goo.gl/rdGKvh How to install and use Java programming on Windows, Mac and Linux Supercomputer Science Innovation Famous programmer: Steve Wozniak NetBeans for Java– Divide the class into four groups. Each group has to list as many examples of data as possible based on the six types of data given. Each variable and constant may exist and be used for the entire program or only for a single function. The existence of a variable or a constant is known as an area where both can be validly used. Variables and constants for programmers consist of two scopes namely: a Universal variable (Global ) •Local variables only work in subroutines declared. end of the procedure. program only. When the procedure has finished, the memory space allocated to variables and constants will also finish. b Local variables (Local ) start 'from where' the variable is declared and when it ends •The use of global variables is current in functions •Used in functions 'where' variables are declared, •Global variables only work within programs. 14 Teamwork 62 1.3.3 Differences between Global and Local Variables float char boolean integers String double Machine Translated by Google


Table 1.7 Differences in characteristics between global variables and local variables What is a static variable? Figure 1.21 An example of a program that uses global variables and local variables Global variables and local variables Global variables are also known as static variables in Java. https://goo.gl/giIoIb CHAPTER 1 PROGRAMMING See the characteristics of global variables and local variables in Table 1.7. 15 63 Teamwork you ? Did you know? static int l = 5; } public static void main(string[] arg) { public class Info { int m = 7; } int n=90;//local variable public class A{ public static void main(String[] args) {; } }//end of class int data = 50; static int m = 100;//global variable Based on the program below, label the global variable and the local variable. Not accessible outside of that function. Characteristics Can only be used for filled functions. A variable declared in a function in a program. If two functions use the same local variable, no problem will occur. Can be used until the end of the program. Universal variable Local variables If a local variable has the same name as a global variable, the reference is only made to the nearest variable, which is the local variable. (Global variables) (local variables) Declaration A declaration made outside of any function. Function Access Local variables Universal variable Accessible in any function. Machine Translated by Google


Variables are known as places to store data. Each variable in Java has a specific type, which determines the size and layout of memory and the set of operations that can be applied to the variable. You must declare all variables before they can be used. Before developing a program, variables and constants need to go through the process of declaration, initialization and value assignment. A variable declaration needs to be implemented by giving the data type and name of the variable. An example of a variable declaration is as follows: you ? Did you know? } } public static void main(String[] args) { } public class Variable { int x; public static void main(String[] args) { } public class Variable { double s, t, u; } } boolean v; public static void main(String[] args) { } public class Variable { } public static void main(String[] args) { public class Variable { String name; Declaration of Variable Values 1.3.4 Declaration, Initialization and Assignment of Values to Variables and Constants64 Computer Science Form 4 Identifiers are names used to represent the names of objects, variables, constants, procedures and functions. • Boolean is a data type •Int is a data type •s, t,u are enabler names •x is the enabler name change Double Declaration • Double is a data type Declaration of Integer •a name is a name •v is the enabler name change variables change Boolean declaration • String is a data type String declaration Machine Translated by Google


Declaration & Declaration of Float • Float is a data type •y is a variable name Value setting Value setting Char Declaration • Char is a data type •w is a variable name Declaration & Value setting Value setting String Integer CHAPTER 1 PROGRAMMING Data Type VariableName = value; Initialization and Assignment of Values to Variables After declaring the data type and name of the variable, the value to the variable can be assigned or assigned. The syntax for setting a variable value is as follows. } String name = "hardeep"; int x = 10; } public class Variable { } } } } } } public class Variable { public class Variable { public class Variable { public static void main(String[] args) { float y; public class Variable { public static void main(String[] args) { public static void main(String[] args) { String name; name = "hardeep"; } public static void main(String[] args) { char w; } public class Variable { public static void main(String[] args) { int x; x = 10; public static void main(String[] args) { } } 65 Machine Translated by Google


v = true; } public class Variable { double s = 0.123, t = 1.1, u = s+t; } public class Variable { char w = 'y'; public class Variable { } } public static void main(String[] args) { boolean v = true; w = 'y'; public class Variable { public static void main(String[] args) { } } public static void main(String[] args) { public static void main(String[] args) { double s, t, u; s = 0.123; t = 1.1; u = s+t; } } public static void main(String[] args) { } public class Variable { char w; } public class Variable { } public static void main(String[] args) { boolean v; } Computer Science Form 4 66 Value setting Declaration & Value setting Value setting Declaration & Value setting Declaration & Value setting Value setting Boolean Double Char Machine Translated by Google


Value setting Declaration & Value setting Declaration and Setting of Constant Values Variable declaration and variable definition CHAPTER 1 PROGRAMMING public static void main(String[] args) { float y; } float y = 342.234f; public class Variable { } public static void main(String[] args) { } } public class Variable { y = 342.234f; 16 Float In the real world, there are some values that will not change such as a square has 4 sides, a day has 24 hours and the value of Pi has three decimal places which is 3.142. as well as the value of the currency for Malaysia. These values will be permanent and will not change. In Java programming, these values are still the same when used as variables. These variables are known as constants. The value of the constant will not change during the execution of the program. The syntax for declaring constants in Java is as follows: 67 Individual Work 1 Visitors to Malaysia Based on the given value, please make a variable declaration according to the appropriate data type and enter the value to the variable. 2 199 You are required to create a program that has the following values: 3L final int NUMBER_DAYS_IN_WEEK = 7 ; final double Pi = 3.14 ; static final double = 4.14; Machine Translated by Google


Accumulation and Arithmetic Statements Arithmetic Figure 1.22(b) Summarize for more than one expression Figure 1.22(a) Summarize for an expression http://goo.gl/YbsnEi Create a Game Figure 1.23 Examples of arithmetic statements Computer Science Form 4 1.3.5 Use of Statements When writing a program, there are several types of statements that can be used. Among them are Accumulation Statements and Arithmetic Statements. This statement refers to arithmetic operations namely addition, subtraction, multiplication and division. The main processing unit can read arithmetic operations from left to right only. If the programmer wants to perform the multiplication operation first, the use of parenthesis symbols should be preferred. Example: An assignment statement will assign a value to a variable. An arithmetic statement can consist of one or more arithmetic operations. For example int x = y. y is the value assigned to variable x. Examples of stacking statements are: A Summons statement can consist of one or more other expressions. Statements refer to "equal to" or the "=" symbol. double p; p = q = r = 255; x = "Hello"; int r; String x; float w; int q; p = 0.123; w = 561.123f; int p; 30 – 5 + 2* 3 / 3 Concentrate on one expression Focus on more than one expression * Parenthetical notation is placed on 2 (30 – 5 + ((2* 3) / 3)) 3 68 Machine Translated by Google


CHAPTER 1 PROGRAMMING Table 1.8 Arithmetic statements and program examples 69 See table 1.8 which shows arithmetic statements and example programs. * Division operation public class OperiTolak { + Description System.out.println("Result of Addition is: " + i); } x i = i - j; System.out.println("Result of Subtraction is: " + i); int j = 20; } Notation } Multiplication Result Programming int j = 20; i = i / j; – public class operationAdd { public static void main(String[] args) { / ÷ } public static void main(String[] args) { int i = 30; Example Program Example Output } Multiplication operation public class Multiplication operation { public static void main(String[] args) { Subtract operation } } The Additional Result is: 30 i = i + j; Mathematics is: 600 * int i = 10; int j = 20; System.out.println("Product of Multiplication is: " + i); System.out.println("Division is: " + i); Notation public static void main(String[] args) { int i = 30; i = ij; } – public class operationReject { int i = 30; int j = 2; Add operation The result of Subtraction is: 10 The Dividend is: 15 + Machine Translated by Google


17 Input from Keyboard and Display Output Some programs have accumulated values or inputs for calculation operations or statements in the program. There are also programs that allow values or inputs to be entered after the program has been built, that is, when the program is executed using the keyboard. The program needs to be added with coding as on the side. See the two program differences below. Summarize values and arithmetic statements Computer Science Form 4 A program that allows input to be entered using a keyboard System.out.println("The area of the triangle is : Scanner input = new Scanner(System.in); } import java.util.Scanner; The area of the triangle is : 12.0 public class wideTriangle { int height = input.nextInt(); " Please enter a high value: double area = (1.0/2)* base * height; 4 int site = input.nextInt(); System.out.println("Please enter site value "); int site = input.nextInt(); } System.out.println("Please enter high value "); Please enter the site value: 6 public static void main(String[] args) { import java.util.Scanner; + wide); System.out.println("Please enter site value : "); Scanner input = new Scanner(System.in); (c) Percentage of overall marks (a) Total marks Based on the situation above, accumulate values and construct arithmetical statements to obtain items (a) to (c) according to the subjects offered in your school. (b) Overall average score Every time an exam is held at school, all students will be able to know: Output The text in green is the input which is entered with a key board 1.3.6 Writing Programs to Insert 70 Individual Work Example 21 Machine Translated by Google


Output The text in green is the input entered with the keyboard. Output Input does not need to be entered because the program calculates the answer based on the value that has been entered in the program. Example 22 A program that has accumulated values or inputs. A program that allows input to be entered using a keyboard. public static void main(String[] args) { " public class wideTriangle2 { age = age; What is your name? : Haziq How old are you? : System.out.println("The area of the triangle is : public static void main(String[] args) { int site = 6; int height = 4; double area = (1.0/2)* base * height; hobby = hobby; System.out.println("What is your hobby? : "); String hobby = input.next(); } What is your hobby? : Playing Name : Haziq Age : 7 name = name; } The area of the triangle is : 12.0 } Scanner input = new Scanner(System.in); System.out.println("What is your name? : "); String name = input.next(); + name); + age); + hobbies); " } System.out.println("How old are you? : "); int age = input.nextInt(); " Hobbies: Playing " import java.util.Scanner; System.out.println("Name : System.out.println("Age : System.out.println("Hobbies : 7 + wide); public class infoAnda { CHAPTER 1 PROGRAMMING 71 Machine Translated by Google


18 Enters input from the keyboard and displays the output Computer Science Form 4 " Hobbies: Playing public class infoAnda2 { + name); Age: 7 String name; public static void main(String[] args) { + age); } hobby = "Playing"; Name: Haziq System.out.println("Name : System.out.println("Age : System.out.println("Hobbies : name = "Haziq"; " age = 7; } int age; + hobbies); String hobbies; " Choose one of the solutions to a calculation problem in mathematics, build a program that allows input to be entered using the keyboard and displays the output. 2 Calculate the average of five numbers. programmers have to take into account the type of data and the capacity of the computer's memory? (Note: Use your own variable names) 5 Calculate the area of the wall excluding a door and two windows. 1 Calculate the area of a room. 2 The programmer wants to develop a program on the calculation of wages. Why? 4 Calculate the wall area including windows and doors. Suggested problems: 1 Name three examples of variables that are often used to build Student Registers. 3 Find the selling price of an item when a voucher discount of RM3.00 is given. The following is a suggested problem that has been given. Output Input does not need to be entered because the program displays the output based on the value or input that has been entered in the program Formative Training 1.3 Individual Work A program that has accumulated values or inputs. 72 Machine Translated by Google


Students name Data Total marks Data types Gender Average score Score } double data = 50; int t = 190; static int number = 10; int n = 90; public class A { } public static void main(String[] args) { 8 As a programmer, you are required to develop a program for arithmetic calculations, namely the division of two numbers. When developing the program, specify the appropriate data type to use for the program to divide two numbers. 5 Based on the following declaration, build a program that can display the output of the addition of two numbers without any errors. student scores. wide without any error. 3 Determine the data type that will be used to represent the data for the enumeration program 4 Why do constants and variables need to be declared? local variables. 7 Based on the following process, build a calculation program that can display the output 6 Based on the diagram shown below, identify and label the universal variables and int first_number, second_number, answer; //variable declaration area = 0.5 * height1 * base1; CHAPTER 1 PROGRAMMING 73 Machine Translated by Google


public static void main(String[] args) { Scanner input = new (System.in); System.out.println("Please enter weight 1 : "); int weight1 = input.nextInt(); System.out.println("The average weight is : } import java.util.Scanner public class averageWeight { } char average = (weight1 + weight2 + weight3) * 3; + average); System.out.println(Please enter weight 3 : ); int weight3 = input.nextInt(); " System.out.println("Please enter weight 2 : "); int weight2 = input.nextInt(); 74 9 Based on the following program, identify the mistakes that have been made. 10 You are required to develop a program that has String, int, double/float and boolean data types. The program must be about you such as your name, age, favorite number and favorite. Look at the following suggestions: (a) What is your name? (b) How old are you? (c) What is your favorite number? (d) Do you like reading or not? Build error-free programs. Computer Science Form 4 Machine Translated by Google


CONTENTS LEARNING STANDARDS STANDARD As has been learned in the algorithms subtopic, the steps found in computer algorithms are not only linear but branching and even iterative. In a branched structure, the steps allow decisions to be made immediately. A repetitive structure allows the same step to be repeated many times. In programming languages, there are elemental similarities between control structures and algorithmic structures, i.e. choice control and repetition control. Some variation exists in the structure of choice control and repeat control but not for sequence control. For sequence control, programs are executed in sequence. For example, a teacher teaches his students according to the chapter that has been arranged for him. For choice control and repeat control, each variation has a specific structure with its own advantages and disadvantages. Therefore, students need to adjust the problem with the appropriate control structurInstructions in linear order are usually used to obtain user input, display results or output or declare and accumulate values for variables. Control Structure 1.4 While (iii) Do-while Optional Controls (iii) Boolean Computer (i) For If-else-if CHAPTER 1 PROGRAMMING (ii) Switch-case (++) and decrement 1.4.4 Write programs using repeating control structures that involve Not varied. Technical writers are responsible for writing descriptions of how computer programs work. 1.4.1 Describe the flow of optional control structures Control Structure Repeat Control Do-while Sequence Control For (ii) While 1.4.3 Explain the flow of repeat control structures (ii) Math Class (random method) Career Science 1.4.2 Write programs using optional control structures by combining relational operators and logical operators (ÿÿ) Switch-case (i) Increment operator Just in order Figure 1.24 Types of control structures in programming (i) If-else 75 Machine Translated by Google


Enter the amount you want to withdraw Show balance How to use Boolean expressions in Java? BBC Bitesize Selection in programming http://goo.gl/DNtv8Z Nope User selects 'view balance'? Finished Yes User select 'withdraw money'? Computer Science Form 4 Start Yes Daily Application http://goo.gl/91MKkt Figure 1.25 Boolean condition statement There are lesser known applications that use control structures such as control applications in cars, refrigerator temperature applications, microwave ovens, printers and air conditioners. Nope 1.4.1 Optional Control Structure For example, automatic teller machines (ATMs) now have many functions such as checking balances, withdrawing money, transferring money and paying bills. Based on the options entered, the software inside the ATM will decide what display to show the user and how to process the entered input. A boolean condition statement, such as "has the user chosen to view the balance?" is used to test the entered input value and this in turn will determine the set or block of instructions that will be executed (Figure 1.25). The decision or choice was recorded in the program. Choice control is a mechanism that allows decisions or choices to be made automatically. Statements about the computer making decisions are called boolean conditional statements. The boolean condition allows comparison of variables, object properties or values done through relational operators or logical operators. This comparison returns the result in the form of boolean data type. Based on certain inputs, a computer program can make decisions. 76 Machine Translated by Google


• if-else Boolean conditional statements are written using optional control structures. There are three forms of optional control structures as follows: Optional Control This control structure is called if (Figure 1.26). The if control structure will only execute certain statements such as processing data through expressions if the condition is true. • if Syntax • switch-case Flow chart • if-else-if Example 23 you ? Did you know? 77 if (<Boolean condition>) { } Example: <Instructions if True> System.out.println("You are eligible to vote."); } if (age > 20) { Answer: We already know the value of Pi (ÿ) in mathematics is 3.142. Evaluate the following expressions: (c) True (e) Pi >5 (b) True (d) Pi !=5 (b) Pi > 0 (c) Pi < 10 (a) False (e) False (a) Pi == 3 (d) True Figure 1.26 Flow chart and if syntax true condition? Do CHAPTER 1 PROGRAMMING this statement if true Do it • Zero/one Finished Source: www.kerryr.net • True/false Start • Open/close Boolean was developed by mathematician and computer researcher George Boole (1815-1864). The boolean system is built based on a binary approach that involves only two objects, namely: True • Yes No If Value Apart from data types such as integer, double or String, there is another data type that is commonly used mainly in control structures, which is the boolean data type. Boolean type data has only two possible values, namely Yes/True or No/False. Boolean Machine Translated by Google


Syntax (a) Is the input 10 greater than 0? The if-else statement is used to make decisions in a program. The result of the comparison indicates a boolean result, ie Yes (True) or No (False). The follow-up statement depends on the result of that Boolean. Flow chart (d) Is the applicant over 16 years old? Examples of Boolean conditions used in option controls are as follows: (e) Is the input score 40 or above? (c) Is the temperature of the egg incubation box in the range of 37 to 39°C? (b) Is the room temperature higher than 27°C? public static void main(String[] args){ True Start } Computer Science Form 4 Do int age=25; Finished http://goo.gl/kkyqN9 Figure 1.27 Flow chart and if-else syntax public class Example24{ } Execute this statement if false } else { Execute this statement if true If-else statement in Java System.out.println("Sorry, you are not old enough."); False if (age > 20) { true condition? System.out.println("You are eligible to vote."); Optional Controls If-Else Computers can ask for a user's age to determine voting eligibility. The boolean condition for voting is 21 years. So, the if-else option control program used is as follows: } <Instructions if False> <Instructions if True> Example 24 } else { if (<Boolean condition>) { 78 Machine Translated by Google


Flow chart Syntax Computers can also be programmed to make more complex decisions, i.e. by using the if-else-if control structure. As such, the computer can try a new boolean condition if the previous condition produces a false result. If the boolean condition produces a true result, only the statement linked to the boolean condition will be executed. Other boolean conditions will not be tested. } statement04 statement01 }else if (boolean condition3_ }else { True) { statement 03 if (boolean condition1_True) { statement02 }else if (boolean condition2_ True) { Optional Controls If-Else-If 79 statement 1 true? Yes Do statement 4 Finished Yes Nope Yes Nope CHAPTER 1 PROGRAMMING condition 2 Do it Start condition 1 true? Do Do it Do it statement 2 statement 3 condition 3 true? Do it Do Figure 1.28 Flow chart and if-else-if syntax Nope Machine Translated by Google


Example 25 An application receives student scores and determines the appropriate grade. The following table shows the grade determination based on the score range. Here is a program to represent grade selection based on a table that uses an if-else-if control structure. Optional Controls Switch-Case B+ C 60–64 50–59 70–74 A 65–69 B A+ 80–89 0–39 D 75–79 A+ E G 45–49 C+ 90–100 40–44 }else if (score >=45) { } if (score >= 90) { Grade Computer Science Form 4 Score }else if (score >=50) { System.out.println(“Marks="+marks+“and Grade is"+Grade); double score=73; public static void main(String[] args){ Grade = "B"; }else if (score >=0) { }else if (score >=75) { Grade = "B+"; }else if (score >=40) { }else if (score >=80) { Grade = "A+"; Grade = "C"; } Figure 1.29 Several counters for different services at the post office String Grade; } }else if (score >=70) { Grade = "C+"; }else if (score >=60) { Grade = "G"; public class Example25{ Grade = "A-"; }else if (score >=65) { Grade = "E"; Grade = "A"; Grade = "D"; said, a switch-case control structure can be used. Figure 1.29 shows customers queuing up to get a specific service requirement. The requirements are matched with the counter that offers the service. Input is matched with existing candidates. To overcome the shortcomings of using if-else-if This structure is easier to understand because the test values in 'Select Case' are matched with several candidate 'Cases'. The use of if-else-if to make a number of decisions is complicated because the if-else-if statement needs to be repeated many times and the repetition can cause confusion for the user. 80 Machine Translated by Google


Syntax The test for 'Switch' is a number, alphabet or string expression. 'Case' contains the respective values that will be matched by the test. If the test equals the value after 'Case', then the group of statements after 'Case' will be executed. The 'Break' expression is used as a command to exit the 'Switch' block. If the 'Break' expression is not included, the group of statements after 'Break' will also be executed. 'Default' is sometimes included in the 'Switch' block as an extra step. If the test does not match any of the 'Case' values, the 'Default' statement group will be executed. This step guarantees that at least one statement has been executed. case: value1 { Group of statements 3 } case: value2 { switch (test){ } case: value3 { breaks; }} } default: { breaks; Group of statements 1 breaks; Group of statements 2 Group of statements 4 Flow chart Case statement 3 CHAPTER 1 PROGRAMMING Group of statements 1 Start Nope Case Nope value3 Figure 1.30 Flow chart and switch-case syntax value1 Yes Group Yes Nope Yes statement 2 Group of statements 4 Finished Case Group value2 81 Machine Translated by Google


Example 26 An application will display the date in the format 'dd-month-name-yy' (example: 28-April-16) Use the switchcase form to write a program that will display the name of the month based on the given month in the form of a number. Solution 82 System.out.println(day+“-November-”+year); breaks; } case 12: { System.out.println(day+“-December-”+year); breaks; } default: { System.out.println(day+“-June-”+year); breaks; } case 7: { Computer Science Form 4 import java.util.Scanner; public class Example26 { public static void main (String [] args) { int day = 23, year = 2016; Scanner input = new Scanner (System.in); System.out.println(day+“-July-”+year); breaks; } case 8: { } System.out.println(day+“-April-”+year); breaks; } case 5: { } System.out.println(day+“-May-”+year); breaks; } case 6: { System.out.println(day+“-February-”+year); breaks; } case 3: { System.out.println("The entered number is not between 1 to 12"); System.out.println(day+“-March-”+year-”+year); breaks; } case 4: { }} int month = input.nextInt(); switch (month){ case 1: { System.out.println(day+“- January-”+year); breaks; } case 2: { System.out.println(day+“-August-”+year); breaks; } case 9: { System.out.println (“Enter a number between 1 and 12”); System.out.println(day+“-September-”+year); breaks; } case 10: { System.out.println(day+“-October-”+year); breaks; } case 11: { Machine Translated by Google


19 Control Options Switch case You are tasked with converting the program below into a switch case control structure. Here is a program to represent grade selection based on the table shown below. The following program uses the W control structure. Individual Activities Grade = "C+"; System.out.println(“Marks="+marks+”and Grade is"+Grade); double score=73; Grade = "A"; http://goo.gl/B7rW7h }else if (score >=65) { }else if (score >=40) { Grade = "A+"; public class ExampleW{ }else if (score >=60) { Grade = "C"; Grade = "E"; Grade = "A-"; In 2013, Syed Muhammad, who was still a high school student at the time, successfully created five applications for the world's leading telecommunications company, Apple. Among the applications are Surfing Fast, Who Created, Simple exCode and Digital Harimau Malaya as well as the game Crazy Ball. } if (score >= 90) { String Grade; }else if (score >=75) { }else if (score >=50) { } CHAPTER 1 PROGRAMMING }else if (score >=80) { public static void main(String[] args){ Grade = "G"; Switch statements in Java Grade = "B+"; Grade = "D"; }else if (score >=45) { }else if (score >=0) { Grade }else if (score >=70) { Source: www. utusan.com.my Grade = "B"; My Malaysia Score } 0–39 90–100 65–69 B+ 60–64 80–89 40–44 A 50–59 E G 75–79 A+ C 45–49 70–74 D A+ B C+ 83 Machine Translated by Google


Relation Operator 84 Conditional value Table 1.9 Relational operators Variables Figure 1.31 Expressions with relational operator "=" Computer Science Form 4 Relational operators are also known as comparison operators. This is because relational operators are used to test the relationship between larger and smaller variables and condition values. Comparison operator 1.4.2 Relational Operators and Logical Operators in Optional Control Structures score == 100 Relation Operator Description Two categories of operators that are often used in conditional expressions are relational operators and logical operators. The relational operator is used to compare two values to produce a boolean result. In Figure 1.31, "score" is a variable. A variable contains a specific value that has been assigned to the variable during or after the declaration of the variable is made. "score is equal to 100" is not true. What if the variable is stacked with a value of 100? The result for the Boolean conditional statement "score is equal to 100" is true. Table 1.9 shows the relational operator operators commonly used in optional control structures. A Boolean conditional statement uses an expression that is intended to make a comparison. User input will be stored in a variable. The variables will be compared through the values in the Boolean condition. Comparison operators make comparisons as in the previous examples. Logical operators are used to generate several boolean expressions to generate more complex conditions. Suppose the score variable has been initialized with the value 90. So, the result of the boolean condition statement Did you know? you ? == Less than or equal to Greater than Equal to Less than > Not the same as <= >= != < Greater than or equal to Machine Translated by Google


Example 27 Example 30 Example 28 Example 29 Suppose the number variable accepts an integer input of ÿ5. What is the result of the following comparative expression? Suppose the number variable receives an integer input of 0. What is the result of the following comparison expression? Suppose the number variable receives an integer input 24. What is the result of the following comparison expression? Suppose the number variable receives an integer input of 0. What is the result of the following comparison expression? Number == 7 Results (correct?) Number != -5 Numbers < -2 Number > 8 Expression Numbers < 12 Yes Numbers > –5 Number != 0 Yes Nope Number == 10 Yes Number != 0 Nope Nope Number > 0 Number == 0 Nope Number < 0 Number > 0 Nope Yes Number != 0 Number == 0 Yes Nope Number < 0 Number > 0 Yes Yes Number < 0 Number != 0 Based on example 27, what is the result of the following comparative expression? Number == 0 Nope Nope Nope Operators Expression Expression goo.gl/HevGUJ Expression Expression Results (correct?) Results (correct?) Results (correct?) CHAPTER 1 PROGRAMMING Results (correct?) Mind Test 85 Machine Translated by Google


System.out.println ("This number is a negative integer."); The Reasoning Chapter in Mathematics uses the same concept of AND, OR and NOT! Figure 1.32 Logical operators } System.out.println("This number is a positive integer."); public class Example31a{ } else if (number == 0) int number=-7; OR Computer Science Form 4 otherwise if (number > 0) NOT System.out.println("This number is not a positive integer"); if (number > 0) public class Example31b{ otherwise } System.out.println("This number is a positive integer"); public static void main(String[] args){ } Logical Operators AND public static void main(String[] args){ System.out.println ("This number is zero."); int number=15; Mind Test Logical Operators Example 31 Did you know? you ? Based on example 31, test a number to identify negative integers. Test a number to identify positive integers. Example output: Example output: To test a boolean condition, place the expression in the learned options control structure. See the following example. 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. 86 Machine Translated by Google


For example, exam marks should be in the range 0 to 100 and can be written as a combination of marks >= 0 and also marks <=100. The appropriate operator in this case is the AND operator. Based on Example 32, it is clear that all boolean conditions must be met. If one of the boolean conditions is not true, then the result is false. See Table 1.10. Score >=0 && Score <= 100 The AND operator is written using the '&&' symbol. Therefore, the boolean conditions can be written as an expression as follows: The AND logical operator is used when two or more boolean conditions must be combined and all conditions must be true. 87 Example 32 Did you know? you ? score<=100 Make sure the input score is in the valid range, which is 0 to 100. score>=0 score>=0 && score<=100 Example output: } Operation a && b logic NOT Boolean System.out.println("The score entered is invalid."); a if (score >=0 && score <=100) True/ False AND a|b OR public static void main(String[] args){ Meaning a |b a& b Boolean public class Example32{ logic } goo.gl/xEPKUd AND logic otherwise OR logic System.out.println("Entered marks are valid."); int score=55; Table 1.10 Examples of using the AND operator CHAPTER 1 PROGRAMMING logic False True True True False True False False False False True False Logical Operator AND Machine Translated by Google


88 Example 33 Logical Operator OR Logical Operator NOT The logical operator NOT converts a boolean value to its opposite. True True FALSE TRUE False False False True True FALSE True False False TRUE True True Suppose the variable x is of boolean type. The value of x is False. Therefore, NOT x is True. What if the original value of x is True? This means NOT x is False. See the truth table in Table 1.12 that summarizes the use of the NOT operator. When NOT is added (!score >=40), the meaning of the statement changes and will indicate that the student failed. The logical operator NOT is placed before the boolean condition to change the status to its opposite. The NOT operator is written using the '!' symbol. For example, a score >= 40 indicates that the student passed. 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. The logical operator OR is written using the symbol '||'. Let's compare this operator with the logical operator AND. Example output: Clothes that have been dried need to be removed when it's night or it's going to rain. Write a program for the given situation. boolean night=true; boolean rain=false; public static void main(String[] args){ } x OR: When you only want one to be right. remember AND logic and OR logic. NOT x permission of the NOT operator } public class Example33{ if (night || rain) score<=100 score>=0 || score<=100 System.out.println("Pick up the shirt."); Computer Science Form 4 score>=0 Table 1.12 Table An easy way to remember AND logic and OR logic. Try this method to AND : When you want everything to be right Table 1.11 Examples of using the OR operator It is clear here that only one of the boolean conditions is required and not necessarily that both boolean conditions need to be met. See Table 1.11. you ? Did you know? Machine Translated by Google


Check if the student passed? Check if the student failed? Example 34 if(score>=40) } False OUTPUT boolean pass; OUTPUT otherwise NOT INPUT marks public class Example34{ if(!passed) Start score >= 40 Finished goo.gl/gBi4iM "Fail" Logical operations and Truth otherwise True False "Passed" pass=true; Figure 1.33 The NOT operator gives the meaning of its opposite int score=83; System.out.println(“You pass”); OUTPUT True "Passed" goo.gl/nVNLCz System.out.println(“You need to repeat the test”); Logic Operators in Java goo.gl/xVySzQ INPUT marks OUTPUT Finished public static void main(String[] args){ CHAPTER 1 PROGRAMMING "Fail Tables pass=false; Start (score >= 40) ? Logical operators } Example output: The passing score is 40 and above. If the student's passing status is incorrect, the student has to repeat the test. 89 Machine Translated by Google


Relational operators and logical operators can be combined in optional control structures. In the example above, the relational operators <= and >= have been combined with the logical operator AND in the boolean conditional expression: Score >=0 && Score <= 100 Another example of a combination involving the relational operator and the OR logical operator is as follows: Example 35 What is the relationship between DeMorgan's Law and logical operators? Combining Relational Operators and Logical Operators in Optional Control Structures Mind Test double celsius=39, fahrenheit=97; public static void main(String[] args){ } System.out.println("You may have a fever."); public class Example35{ } if (celsius>37 || fahrenheit>98.6) Computer Science Form 4 90 Example output: If the body temperature is higher than 37 °C or 98.6 °F, then a person may have high fever. Write a program for the situation described. Machine Translated by Google


20 Operator Combinations Some statements are placed in blocks that need to be repeated. This happens because repetition is made for a certain number of times or until a certain boolean condition is no longer true. See Figure 1.34. In daily life, you can observe repetitive actions of electronic devices. An example of a repeat control structure is an air conditioner. The air conditioner will operate when the room temperature rises and stop when the room temperature cools. The temperature of the room is decisive, whether the cooling process needs to be repeated or not. CHAPTER 1 PROGRAMMING Figure 1.34 Types of repetition control structures Repetition statements goo.gl/vC6jWD Conditional repetition Repeat Control Counter-based repetition Meters You were given an assignment by your teacher to convert the units of meters (m) to kilometers (km) and kilograms (kg) to grams (g). The formula for each specified unit exchange is as follows: ÷ 1000 ÷ 1000 Based on the given formula, write a program for the exchange result for the following values: x 1000 x 1000 Kilograms Kilometers (a) 500 g to kg (b) 0.8 km to m (c) 1.7 kg to g (d) 400 m to km Grams 91 1.4.3 Repetition Control Structure Individual Activities Machine Translated by Google


Click to View FlipBook Version