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

SC025 REVISION NOTES & WORKSHEET 2023-2024

Discover the best professional documents and content resources in AnyFlip Document Base.
Search
Published by bm-1944, 2024-02-24 19:28:03

SC025 REVISION NOTES & WORKSHEET 2023_2024

SC025 REVISION NOTES & WORKSHEET 2023-2024

Keywords: SC025,SUMMARY,REVISION,WORKSHEET

SC025 COMPUTER SCIENCE 2 MATRICULATION PROGRAMME SESSION 2023/2024 Prepared by: PN. MARZITA ISMAIL PENSYARAH UNIT SAINS KOMPUTER KOLEJ MATRIKULASI KEDAH


mieta_ismail@KMK_Januari2024 TERMS DEFINITION/ DESCRIPTION 2.0 Approach in Problem Solving 2.1 Problem solving o the process of formulating a problem, finding a solution and expressing a solution. 2.2 Steps in Problem Solving i. Problem Analysis ** Tips to handle complex problem statement: KENAL PASTI IPO REVERSELY (MENGUNDUR)… you can ask yourself…. o An analysis of a problem statement to identify input, process and output (IPO): o Use I P O Chart (general format) to write your answer: Input : required data to the problem (usually data entered by user using keyboard or retrieved from the database (for big program/system) Process: relevant action (verb)/condition (if any) involved to produce output from input. Output: expected result after processed (to be printed/displayed on the monitor) o Example: Problem Statement: Calculate area of a rectangle. I - length, width (if more than 1 input, separate with comma (,) P - Calculate area of a rectangle (must have verb that shows data manipulation occurs such as Calculate/Convert) O – Area of a rectangle (usually mesti relate dgn Process(es) OUTPUT : Apa program ini perlu produce/display kepada user? PROCESS : APA process(s) yang perlu dilaksanakan untuk menghasilkan@produce the output(s)? INPUT : Apakah data@value(s) yang bergantung kepada user (berubah-ubah) dan tidak diberi dalam soalan, but we need it from user@database untuk pastikan process dilaksanakan ** JAWAPAN IPO PERLU MENEPATI PERSOALAN2 DI ATAS ii. Design a Solution o involves creating an algorithm • Algorithm o a sequence of well-defined steps to solve a problem o can be represented using pseudocodes or flowcharts iii. Implementation o the process of implementing an algorithm by writing a computer program using a programming language (such as Java language). iv. Testing o main objective is to convince that the program will do what it is expected to do • Program verification o the process of ensuring that a program meets user-requirement (verify output with different inputs) • Program testing o the process of executing a program to demonstrate its correctness • Errors o 3 types of error: Syntax Errors Run-time Errors Logic Errors • Debugging o A process of removing errors from a program v. Documentation (definition/purpose) • can be done in Two (2) ways: o contains description of the program that helps other programmers in editing or maintaining the program later i. Writing comments between your lines of codes (use ‘/’ or ‘/*’) ii. Creating a separate text file to explain the program


mieta_ismail@KMK_Januari2024 3.0 Design a Solution Terms Definition/ Description 3.1 ALGORITHMS ➔ A sequence of well-defined steps to solve a problem • Pseudocode o A written statement of an algorithm using a semiformal language with limited vocabulary • intended for human reading rather than machine reading • description is verbal • Flowchart o A graphical representation consisting of geometricalshapes that are connected by flow lines to represent an algorithm o graphical in nature. Terminal Symbol: (Shape:Capsule or Terminator in MS Word) o indicates the beginning and end points of an algorithm Process Symbol: (Shape:Rectangle) o Represents a set of operations that changes value of data Input-Output Symbol: (Shape:Parallelogram) o shows an input or an output operation Disk Storage I/O Symbol: (Shape: Cylinder) o indicates input from or output to disk storage Decision Symbol: (Shape:Diamond) o shows a decision process. o it checks a condition written inside the symbol and returns True or False o it stands for the keyword if or while in pseudocode Flow Lines: (Shape: Arrow head) o indicates the logical sequence of execution steps in the algorithm Off-Page Connector: o provides continuation of a logical path on another page On-Page Connector: (Shape:Circle) o provides continuation of a logical path on the same page 3.2 CONTROL STRUCTURE ➔ showsthe logical order of program instructions o SEQUENCE o performs actions one after another in sequence Pseudocode General Format Example Flowchart General Format Example Start action1 action2 action3 … … action n Stop action1 action2 Java General Syntax Example of Full Java Code { action1; action2; …………..; }


mieta_ismail@KMK_Januari2024 o SELECTION: o performs action(s) based on a certain condition o Single (if) o Checks a condition to perform action(s) ** action can be input, process or output wpun flowchart umum guna simbol rectangle…itu hanya contoh yaaaa… o If condition is true, perform action(s) o If condition is false perform nothing Pseudocode General Format Example Flowchart General Format Example Start …… if <condition> <action1> …… Stop Start input mark if (mark > 40) print “PASS” end if End Java General Syntax # if True, 1 action Example of Full Java Code Java General Syntax # if True, more than 1 action Example of Full Java Code { …….. …….. if (condition) { action1; } } { …….. …….. if (condition) { action1; action2; …………..; …………..; } } o Dual (if-else) o Checks one condition to choose between two actions o If condition is true, perform action1 (s) o If condition is false, perform action2(s) Pseudocode General Format Example Flowchart General Format Example Start …… if <condition> <action1> else <action2> end if …… Stop Start input mark if (mark > 40) print “PASS” else print “FAIL” end if End


mieta_ismail@KMK_Januari2024 Java General Syntax # if True , 1 action Example of Full Java Code Java General Syntax # if True, more than 1 action Example of Full Java Code { …….. …….. if (condition) { action1; } else { action2; } …….. } { …….. …….. if (condition) { action1; action2; } else { action3; action4; } …….. } o Multiple Selection (if-else-if ) o Checks many conditions to choose between many actions o Condition will be checked one by one o When a condition istrue, perform the action(s) and stop checking the rest Pseudocode General Format Example Start …… if <condition1> <action1> else if <condition2> <action2> else <last action> …… end if Stop Start Stop input number if (number > 0) print “positive” else if (number < 0) print “negative” else print “zero” end if Flowchart General Format Example


mieta_ismail@KMK_Januari2024 Java General Syntax # if True, 1 action Example of Full Java Code { …….. …….. if (condition1) {action1;} else if (condition2) {action2;} else if (condition3) {action3;} else {action4;} } …………. Java General Syntax # if True , more than 1 action Example of Full Java Code { …….. …….. if (condition1) { action1; action2; } else if (condition2) { action3; action4; } else if (condition3) { action5; action6; } else { action7; action8; } …….. }


CONTROL STRUCTURE : SELECTION → EXAMPLES OF PROBLEMS : ONLY DISPLAY MESSAGE BASED ON CONDITION TYPES → SINGLE (if …. ) DUAL (if …..else ……) MULTIPLE (if …… else if …. else) PROBLEM STATEMENTS If a student is in Modul 2 group, display the message “The student is taking Computer Science subject”. If a student is in Modul 2 group, display the message “The student is taking Computer Science subject”. Otherwise, display the message “The student is taking Biology subject”. If a student is in Modul 2 group, display the message “The student is taking Computer Science subject”. If he/she in Modul 1 or 3, display message “The student is taking Biology subject”. Otherwise, an error message “Your input is not in the list” will be displayed. STEP 1: PROBLEM ANALYSIS IPO I: modul P: Determine message “The student is taking Computer Science subject” based on modul O: message “The student is taking Computer Science subject” or null I : modul P: Determine message “The student is taking Computer Science subject” OR “The student is taking Biology subject” based on modul O: message “The student is taking Computer Science subject” or “The student is taking Biology subject” I : modul P: Determine message “The student is taking Computer Science subject” OR “The student is taking Biology subject” OR “Your input is not in the list” based on modul O: message “The student is taking Computer Science subject” or “The student is taking Biology subject” or “Your input is not in the list” STEP 2: DESIGN SOLUTION (ALGORITHM) PSEUDOCODE Begin Read modul if (modul ==2) then Display “The student is taking Computer Science subject” end if End Begin Read modul if (modul ==2) then Display “The student is taking Computer Science subject” else Display “The student is taking Biology subject” end if End Begin Read modul if (modul ==2) then Display “The student is taking Computer Science subject” else if (modul ==1 OR modul==3) then Display “The student is taking Biology subject” else Display “Your input is not in the list” end if End


CONTROL STRUCTURE : SELECTION → EXAMPLES OF PROBLEMS : ONLY DISPLAY MESSAGE BASED ON CONDITION FLOWCHART Begin Read modul modul == 2 T Display “The student is taking …” End F Display “The student is taking…” Read modul modul == 2 T Display “The student is taking …” F Begin End Display “The student is taking…” Read modul modul == 2 Display “The student is taking …” F Begin End Display “Your input is not in the list” modul == 1 || modul ==3 T T F


CONTROL STRUCTURE : SELECTION → EXAMPLES OF PROBLEMS : ONLY DISPLAY MESSAGE BASED ON CONDITION STEP 3 : IMPLEMENTATION CODING JAVA import java.util.Scanner; public class SelectionSingle1{ public static void main(String[] args) { Scanner sc = new Scanner (System.in); int modul; System.out.print ( "Enter modul: "); modul =sc.nextInt (); if (modul == 2) { System.out.print ("The student is taking Computer Science subject."); } } } import java.util.Scanner; public class SelectionDual1 { public static void main(String[] args) { Scanner sc = new Scanner (System.in); int modul; System.out.print ( "Enter modul: "); modul =sc.nextInt (); if (modul == 2) { System.out.print ("The student is taking Computer Science subject."); } else { System.out.print ("The student is taking Biology subject"); } } } import java.util.Scanner; public class SelectionMulti1 { public static void main(String[] args) { Scanner sc = new Scanner (System.in); int modul; System.out.print ( "Enter modul: "); modul =sc.nextInt (); if (modul == 2) { System.out.print ("The student is taking Computer Science subject."); } else if (modul ==1 || modul ==3) { System.out.print ("The student is taking Biology subject"); } else { System.out.print ("Your input is not in the list"); } } }


CONTROL STRUCTURE : SELECTION → EXAMPLES OF PROBLEMS : PERFORM CALCULATION BASED ON CONDITION TYPES → SINGLE (if-then statements) DUAL (if-then-else statements) MULTIPLE (if-then-else if statements) PROBLEM STATEMENTS Perform addition of variable p and q if user enter positive number for both variables. Perform addition of variable p and q if user enter positive number for both variables. Otherwise, perform multiplication. Perform subtraction of 2 numbers entered by user, p and q. If p is larger than q, deduct q from p, else if q is larger than p, deduct p from q. Otherwise, display a message “Both numbers are equal”. STEP 1: PROBLEM ANALYSIS IPO I: p,q P: Determine whether to calculate addition based on numbers O: Either addition or null I : p,q P: Determine whether to calculate addition based on numbers O: Either addition of p and q or multiplication of p and q I : p,q P: Determine whether to calculate subtraction based on numbers O: Either subtraction of p or subtraction of q or message “Both numbers are equal”. STEP 2: DESIGN SOLUTION (ALGORITHM) PSEUDOCODE Begin Read p,q if (p >0 && q>0 ) then add = p + q Display add end if End Begin Read p,q if (p >0 && q>0) then add = p + q Display add else mltply = p * q Display mltply end if End Begin Read p,q if (p>q) then subtract = p – q Display subtract else if (q>p) subtract = q – p Display subtract else Display “Both numbers are equal” end if End


CONTROL STRUCTURE : SELECTION → EXAMPLES OF PROBLEMS : PERFORM CALCULATION BASED ON CONDITION FLOWCHART Begin Read p, q p>0 && q>0 T End F Display mltply Read p, q p>0 && q>0 T Display add F Begin End Read p, q p>q F Begin End T T F add = p + q Display add add = p + q mltply = p x q q>p subtract = p - q subtract = q - p Display “Both numbers are equal” Display subtract


CONTROL STRUCTURE : SELECTION → EXAMPLES OF PROBLEMS : PERFORM CALCULATION BASED ON CONDITION STEP 3 : IMPLEMENTATION JAVA CODE import java.util.Scanner; public class SelectionSingle1 { public static void main(String[] args) { Scanner sc = new Scanner (System.in); int p,q, add, mltply; System.out.print ( "Enter value for variable p: and q : "); p=sc.nextInt (); q = sc.nextInt (); if (p >0 && q>0) { add= p+q; System.out.print ("Addition= " + add); } } } import java.util.Scanner; public class SelectionDual2 { public static void main(String[] args) { Scanner sc = new Scanner (System.in); int p,q, add, mltply; System.out.print ( "Enter value for variable p: and q : "); p=sc.nextInt (); q = sc.nextInt (); if (p >0 && q>0) { add= p+q; System.out.print ("Addition= " + add); } else { mltply = p*q; System.out.print ("Multiplication = " + mltply); } } } import java.util.Scanner; public class SelectionSime { public static void main(String[] args) { Scanner sc = new Scanner (System.in); int p,q, subtract; System.out.print ( "Enter value for variable p: and q : "); p=sc.nextInt (); q = sc.nextInt (); if (p >q) { subtract = p-q; System.out.print ("Subtraction = " + subtract); } else if (q>p ) { subtract = q-p; System.out.print ("Subtraction = " + subtract); } else { System.out.print ("Both numbers are equal"); } } }


CONTROL STRUCTURE : SELECTION → DETERMINE@PERFORM ACTION/S BASED ON CONDITION TYPES → SINGLE (if-then statements) DUAL (if-then-else statements) MULTIPLE (if-then-else if statements) PROBLEM STATEMENTS Calculate electric bill based on electricity usage in watt (charge is 20 cents per watt). Display the electric bill, if electric bill is RM100.00 and less, display message “Congratulation! You have saved a lot!” Calculate electric bill based on the electricity usage in watt as given below. • Usage up to 1000 watt – charge 20 cents per watt • Additional usage after 1000 watt – charge is 30 cents per watt. Display the electric bill Calculate electric bill based on the electricity usage in watt as given below. • Usage up to 1000 watt – charge 20 cents per watt • First 300 additional usage after 1000 watt – charge is 30 cents per watt. • Additional usage after 1300 watt – charge is 40 cents per watt. Display the electric bill STEP 1: PROBLEM ANALYSIS IPO I: electricity usage P: Calculate total charge Determine whether to display message “Congratulation! You have saved a lot!” based on electric bill O: electric bill, message “Congratulation! You have saved a lot!” or null I : electricity usage P: Determine electric bill based on electricity usage O: electric bill I : electricity usage P: Determine electric bill based on electricity usage O: electric bill STEP 2: DESIGN SOLUTION (ALGORITHM) PSEUDOCODE Begin Read e_usage e_bill = e_usage * 0.2 Display e_bill if (e_bill <=100 ) then Display “Congratulation! You have saved a lot!” end if End Begin Read e_usage if (e_usage <1000) then e_bill = e_usage * 0.2 else e_bill = 200.0 + ((e_usage-1000) * 0.3) end if Display e_bill End Begin Read e_usage if (e_usage <1000) then e_bill = e_usage * 0.2 else if (e_usage <=1300) e_bill = 200.0 + (e_usage-1000) * 0.3) else e_bill = 290.0 + (e_usage-1300) * 0.4) end if Display e_bill End


CONTROL STRUCTURE : SELECTION → DETERMINE@PERFORM ACTION/S BASED ON CONDITION FLOWCHART Begin Read e_usage e_bill <=100 T End F Read e_usage e_usage <=1000 Display e_bill Begin End Read e_usage e_usage <=1000 F Begin End T T F Display “Congratulation! You have saved a lot!” e_bill = e_usage * 0.2 e_usage <=1300 e_bill = e_usage * 0.2 Display e_bill e_bill = 200.0 + ((e_usage-1000) * 0.3) T F e_bill = e_usage * 0.2 Display e_bill e_bill = 200.0 + ((e_usage-1000) * 0.3) e_bill = 290.0 + ((e_usage-1300) * 0.4)


CONTROL STRUCTURE : SELECTION → DETERMINE@PERFORM ACTION/S BASED ON CONDITION STEP 3 : IMPLEMENTATION JAVA CODE import java.util.Scanner; public class SelectionSingle3 { public static void main(String[] args) { Scanner sc = new Scanner (System.in); double e_usage, e_bill; System.out.print ("Enter electric usage : "); e_usage=sc.nextDouble (); e_bill=e_usage * 0.2; System.out.println ("Electric bill = RM" + e_bill); if (e_bill<=100) { System.out.print ("Congratulation, you have saved a lot."); } } } import java.util.Scanner; public class SelectionDual3 { public static void main(String[] args) { Scanner sc = new Scanner (System.in); double e_usage, e_bill; System.out.print ( "Enter electric usage : "); e_usage=sc.nextDouble (); if (e_usage<=1000) { e_bill=e_usage * 0.2; } else { e_bill=20 +((e_usage-1000) * 0.3); } System.out.println ("Electric bill = RM" + e_bill); } } import java.util.Scanner; public class SelectionMulti3 { public static void main(String[] args) { Scanner sc = new Scanner (System.in); double e_usage, e_bill; System.out.print ( "Enter electric usage : "); e_usage=sc.nextDouble (); if (e_usage<=1000) { e_bill=e_usage * 0.2; } else if (e_usage <=1300) { e_bill=200 +((e_usage-1000) * 0.3); } else { e_bill = 290 + ((e_usage -1300)* 0.4); } System.out.println ("Electric bill = RM" + e_bill); } }


mieta_ismail@KMK_Januari2024 o REPETITION: performs one or more actionsrepeatedly while a certain condition is true o The keyword used is while (selagi syarat dipenuhi (True), ulangi action2 di antara while & end while sehinga syarat False, keluar dari looping (ke baris selepas end while)) o Format: initialize (starting value) while (condition) loop-body (statement/s that need to be repeated, put in here, between while & end while) update (next value) end while next action(s) (if any, it’s for any statement/s that need to be performed only one time such as: Display average) 2 types of Repetition: (i) (ii) Pseudocode Format (i) Counter-controlled (ii) Sentinel-controlled **Evaluation – the value to be repeat **Evaluation - the value to repeat is not known, is known, so programmer will it depend on user input set the value during coding


mieta_ismail@KMK_Januari2024 start counter < 10 Print “Welcome to KMK” end Flowchart Examples (i) Counter-controlled (ii) Sentinel-controlled True counter = counter + 1 counter = 0 False


mieta_ismail@KMK_Januari2024 Examples 1: Flowchart & Java Code Counter-controlled Sentinel-controlled


mieta_ismail@KMK_Januari2024 Examples 2: Flowchart & Java Code Counter-controlled Sentinel-controlled


mieta_ismail@KMK_Januari2024 Examples 3: Flowchart & Java code Counter-controlled Sentinel-controlled import java.util.Scanner; class AvgTest { public static void main (String [] args){ Scanner sc=new Scanner (System.in); int student = 1; while (student<=5) { System.out.print ("Enter mark for Test1: "); double test1=sc.nextDouble(); System.out.print ("Enter mark for Test2: "); double test2=sc.nextDouble(); double avg = (test1+test2)/2; System.out.println("Average mark :" + avg); student = student +1; } } }


mieta_ismail@KMK_Januari2024 4.0 Java Language 4.1 Introduction to JAVA ObjectOriented Programming (OOP) a programming technique that uses objects to design the applications and computer programs OOP Description: • Class a description of the properties and the behaviors of one or more objects. • Object an entity that has both state and behavior. The state consists of any data that the object might be keeping track of. The behavior consists of actions that the object can perform. • Method a block of code which only runs when it is called. Basic Components ofJava Programs: ** Refer Handout: STEPS TO CODE IN JAVA for examples OF THESE COMPONENTS • Comments contains information about the program, but that has no effect when the program runs Eg: //Author : Faizal Tahir • import statement will import classes in a package (a collection of pre-defined library, classes and interfaces) Eg: import java.util.Scanner; • Class a keyword used for developing user defined data type Eg: class JavaProgram { • main Method A program driver which starts the execution of Java program Eg: public static void main (String[ ] args) { • Body • Represents a set of executable statements which may include: – creating instance of a class (object) – variables declaration (details @4.2) – output initialization – input statement(s) Details refer below: – processing statement(s) – outputstatement(s) Input statement(s) used to accept data entered by user into the computer • Step 1. Import class Scanner from package java.util. o import java.util.Scanner; • Step 2. Create an instance of class Scanner (object) o Scanner sc = new Scanner(System.in); • Step 3. Assign input statement to a variable o variable = sc.nextInt(); Processing statement(s) Used to manipulate inputsto produce the output. It involves the use of arithmetic operators, relational operators & logical operators Eg: i. result = p * q; -➔ arithmetic ii. if (p == 10 && q != 10) ➔ logical iii. while (c <= 10) ➔ relational Output Statement(s) used to display output on the screen o System.out.print();


mieta_ismail@KMK_Januari2024 4.2 Data Types, Operators, and Expressions: 4.2.1 Identifiers A series of characters consisting of letters, digits and underscore (_) • Used for variable names or function names • Should be unique and meaningful • Case-sensitive – uppercase and lowercase letter is considered different. (ex: NUM, num and Num are considered as different identifiers) Rules to write valid identifiers (variable/function names): • First character must be a letter or an underscore or a dollar sign, $ (i.e must not begin with a digit) • Must not use any othersymbols other than letters, digits, dollar sign $, and underscore (_) • Must not use reserved words, such as if, while, int, do, float 4.2.2 Variables • a location in the computer’s memory to store a value • must be declared with a name and a data type before it can be used syntax: <datatype> <variable name>; eg: double marks; 4.2.3 Constants an identifier that is similar to a variable except that it holds fixed value while the program is active Syntax : final <datatype>< CONSTANT_NAME>= <value>; eg: final double pi = 3.142; 4.2.4 Reserved Word keywords that are reserved by Java functions. Eg: class, public, static void, main, return, int, double, boolean, true, false, final, if, else, while, for Primitive Data Types: Refer to the type of data that can be stored in a variable • int – integer Used to declare variables that will store integer numbers, such as 7, - 11, 0, 31914 • double – double floating-point Used to declare variables that will store larger decimal numbers, such as 3.4, 0.01, -11.9. • boolean – true/false value A Boolean value represents a true or false condition • char – character Used to declare variables that will store alphanumeric data, such as ‘A’, ‘a’, ‘9’, ‘*’ Escape Characters • begins with a backslash, \ followed by a character. • Used in print statement to format output Eg: \n – a new line (to display output at a new line) \t – a tab (to indent around 5 spaces) Operators: generate some computations when applied to operands in expression. Types of operators: • Arithmetic (for Mathematical Operations) includes using five arithmetic operators to perform addition, subtraction, multiplication, division and taking the modulus. (+, - , *, /, %) ** Mathematical Operations ➔ the manipulation of variables using arithmetic operators resulted to one single value. • Relational (for Conditional Operations) refers to the comparison of values. (==, <, >, <=, >=, !=)


mieta_ismail@KMK_Januari2024 • Logical: • applied to one or more relational expression. • used to: • negate (inverse) a relational expression • connect two or more relational expressions i. AND - && • is TRUE if both are true, and false otherwise ii. OR - || • is TRUE if a or b or both are true, and false otherwise iii. NOT - ! • if some Boolean condition a is true, then !a is false; if a is false, then !a is true • Assignment (=) Used to assign (give) a value or results of an expression on the rightside to a variable on the left-side of an equation, (=). Precedence of Operators: HIGHEST OPERATOR Description ASSOCIATIVITIY ( ) Grouping Evaluate from inside out ! Logical NOT Right to left * / % multiplication, division, modulus Left to right + - addition, subtraction Left to right < <= > >= == != relational Left to right LOWEST && Logical AND Left to right || Logical OR Left to right = Assignment Right to left Expressions A combination of one or more operands and their operators Eg: i) 3.142 x r x r ii) Math.sqrt(a) Statements An instruction given to computers that allow the computer to take a specific action such as display on the screen or read input 4.3 Use of Control Structure CODING : • Refer 3.2 for general format of Java syntax for each control structure • Refer Handout: Steps to Code in Java for a complete program code (eg. given, Sequence) Sequence Selection Repetition Programming Errors: • Syntax Error Occurs when the syntax of the programming language is violated. • statement cannot be translated and program cannot be executed • Common examples are: – Misspelled variable and function names – Missing semicolons – Improperly matches parentheses, square brackets [ ], and curly braces { } – Incorrect format in selection and loop statements • Run-time Error Occurs when a program with no syntax errors asks the computer to do something that the computer is unable to reliably do. • Common examples are: - Trying to divide by a variable that contains a value of zero - Trying to open a file that doesn't exist • Logic Error Occurs when there is a design flaw in your program. • Common examples are: • Very difficult to detect, the only sign is incorrect output. – Multiplying when you should be dividing – Adding when you should be subtracting – Opening and using data from the wrong file – Displaying the wrong message


1 - Comment 2 - Header 3 – Declare Data Type 4 - Input 5 - Process 6 - Output 1 2 1 2


1


(a) (b) (i). Addition is the class name@file name… (ii). sc is the object name for class Scanner **Both can be change…up to programmer Open curly bracket, { is compulsory (wajib) after each of these 2 statements 2 (i) (ii) What is (i) and (ii)?


Data Type When to use these data type? String For data that consist more than 1 character or symbol such as variable Name (eg data : Ali, Abu, Nani etc.) int For data that consist integer such as variable Age (eg data: 1,7,14 etc.) double For data that consist value with decimal point such as variable Weight (eg data: 20.5, 40.3 etc. ) float Boolean For data that consist only two (2) states, true or false such as variable Married (True, False) char For data that consist only 1 character or symbol such as Gender (eg data : M, F) 3


4 Prompt user input (beri msg pd user, data apa yg kena masukkan to make it more User Friendly – not shown in pseudocode/flowchart. Instruct comp. to receive input from user one by one…


5 Just write statement/instruction using appropriate formula


6 To display message or caption ( User Friendly) with value of any variable beside it, use symbol (+). (Message/caption put in between “…….. “ + variable)


PSEUDO CODE Start Read num1, num2 total = num1 + num2 Display total End FULL JAVA CODE 1 - Comment 2 - Header 3 – Declare Data Type 4 - Input 5 - Process 6 - Output Example of coding based on pseudo code:


mieta_ismail@KMK_Januari2024 4.4 Array : ▪ Consist of: is an ordered sequence of data of the same type. o Data type – refer to the type of data that can be stored in an array o Size – refer to the length or number of elements in an array o Index – the address for the array elements starting from 0 to n where n is the size of the array o Value – the actual data stored in the array elements Important Statements in array: i. Declare array: (data type) eg: double [ ] marks; ii. Create array: (size) If value will be input by user: Choose: Declare & Create array separately OR together in 1 statement eg: marks = new double [5]; iii. Declare & create array (together in 1 statement): eg: double [ ] marks = new double [5]; iv. Entering data into array input by user : eg: for (int i =1; i< marks.length;i++){ marks[i]=sc.nextDouble();} iv. Declare & Create & Assign data/value a) Do it in 3 steps of statements OR together in 1 statement b) Do it separately (examplesfor each data type) i)3 steps of statements: if data is set by programmer //declare & create array in 1 int []days; //declare data type of array days days =new int [4]; //create array days, 4 in size days[]={25,14,23,17}; //assign data into array days OR ii)1 statement ONLY //declare,create & assign value of an int type array name days int [ ] days = {25,14,23,17}; Other examples: double [ ] marks = {50.5, 50, 70.5, 90,40.5}; char [ ] grade = {‘A’, ‘B’, ‘C’, ‘D’}; String [ ] names={“Ali”, “Abu”,“Siti”,”Tim”}; **size of array is depend on the number of value assigned statement double [ ] marks = new double [5]; //assign data one by one statement marks[0]=50.5; marks[1]=50; marks[2]=70.5; marks[3]=90; marks[4]=40.5; If data/value set by programmer, refer below :


mieta_ismail@KMK_Januari2024 vi. Accessing/Display elements in array (2 options): eg: // to access array that have many data, we need to use repetition in order to go to each index for (int i =1; i< marks.length;i++) { total = total + marks[i]; //to total up all the data in array marks System.out.print (marks[i]); //display ALL values in an array System.out.print (“The index is “+ i ); //display the index of an array } OR //to access array without using repetition double [ ] marks = {50.5, 50, 70.5, 90, 40.5}; //to display the value 90 of index 3 in the array System.out.print (“The value in index 3 is “+ marks[3] ); //to display sum of marks at index 1, 50 and 3, 90. The output is 140 System.out.print ( marks[1] + marks[3] ); Skills to cover in Array Solution Example i. Find Sum ii. Find Average iii. Find Largest/Smallest @ Min/Max @ Fastest/Slowest @ Highest/Lowest& etc. Find Frequency


mieta_ismail@KMK_Januari2024 4.5 Method: a collection of statements that are grouped together to perform a particular task. ** Adv: - Code reusability – define once, use it multiple times - allow to break a complex program into smaller chunks of code - readability is enhanced as it reduces the complexity of the main() method. - allow different people to work on different methods simultaneously. Types: 1. Predefined methods @ Standard Library Methods Built-in methods in Java that are readily available for use by programmers. Eg: 1. sqrt() ➔ method defined in Math class. It returns the square root of a number ➔ Syntax : sqrt(int 9) or sqrt (double n) 2. pow(base,exp) ➔ method defined in Math class used to calculate The value of a number raised to the power of other number. ➔ Syntax : pow (double p, double q) 2. Static User– defined Methods A method that belongs to the class and not the instance (or object) that is defined by the programmer. 1. Defining a Method @ Method Definition: - Consist of a method header and a method body General Format: <modifier><returnType><nameofMethod>(parameter list) { //method body } Eg: public static double calcAreaRect (double l, double w) { return l * w; method body } Method definition Components: a) Modifier → defines the access type of the method (OPTIONAL) b) returnType ➔ if HAVE value to return, use int or Boolean or double or char ➔ if NO value to return, use void Eg: void calcAreaRect (double l, double w) { } c) methodName ➔ is an identifier, usually the name represents the task performed by the method. d) Parameter List➔ refers to the type, order, and number of parameters of a method anda placeholder to hold value of the passed arguments. e) Method-body ➔ collection of statements that define – what the method does, – how the parameters are manipulated with programming statements and – what value is returned. 2. Calling a Method @ Method Call: General Format: <methodName>(Actual Parameter/s@Argument/s) Eg: calcAreaRect(length, width); method-header ** 1. Method Call : - bina dalam Main Method 2.Method Definition: - bina di luar Main Method samada sebelum or selepas tiada masalah, asalkan in the same Class.


mieta_ismail@KMK_Januari2024 Steps to apply Method: Eg: class CalcArea { { (use import statement & initialize variables involve as usual) + 2. Invoke @ Call Method (3 cara@pilihan) ➔ 1. methodName (argument/s); Eg : calcAreaRect (length, width) ; 2. variable = methodName (argument/s); Eg: area = calcAreaRect (length, width); System.out.print (area); 3. methodName (argument/s)); Eg: System.out.print (calcAreaRect (length, width)); } + 1. Define method (ada 4 CARA – guna mana2 cara yang sesuai as asked in the question) i., RETURN VALUE, ACCEPT PARAMETER(S) (have parameters, use suitable data type for returnType) { return l * w; @ double area = l * w; return area; } ** ada 2 cara utk return value: 1. Directly return the calculation 2. Return via variable ii.NOT RETURN VALUE , ACCEPT PARAMETER(S) (have parameters to hold arguments, use void for returnType because this type of method did not return any value to main method coz it will display the output here) { double area = l * w; System.out.print (“Area of rectangle = “ + area); } newMethod newMethod ** cara (3) ini you guna jika you nak display output kat main method juga. Cuma ianya lebih ringkas sbb tak perlu guna variable mcm Cara2… caranya you just letakkan arahan method call terus kpd output statement…cara nie perlukan return value dari method baru… ** cara (2) ini you assignkan method call kpd 1 variable… guna cara ini bila you nak display output dlm main method menggunakan variable...perlukan return value dari method baru. ** guna cara (1) ini bila u you kena display output dlm method baru. Selesaikan semua task termasuk output di method baru..jadi tiada return value ke main method dah. Main Method ** kalau ada parameters … wajib ada data type public static void CalcAreaRect (double l, double w) public static void CalcAreaRect (double l, double w)


iii. RETURN VALUE, NOT ACCEPT PARAMETER(S) (bracket ( ) left blank , use suitable data type for returnType ) { double l = 5.0, w=4.0; return l * w; @ double area = l * w; return area; } iv. NOT RETURN VALUE, NOT ACCEPT PARAMETER(S) (bracket ( ) left blank, use void for returnType because this type of method did not return any value to main method. This method will perform process with fix data and also display output within the method itself. ) { double area = 5 * 4; System.out.print (area); } @ { double l = 5.0, w=4.0; double area = l * w; System.out.print (area) ; } RevisionNotes&Worksheet_SC025 mietaIsmail@kmk_Mac2023 Credit to: En. Mohd Amran b Md Ali & Pn. Maziah Mohd Zin ~Reference Book Writer~ and all KMK’s Computer Science Lecturer newMethod newMethod public static double CalcAreaRect ( ) public static void CalcAreaRect ( ) public static void CalcAreaRect ( )


Click to View FlipBook Version