SC025
COMPUTER SCIENCE 2
MATRICULATION PROGRAMME
SESSION 2020/2021
Prepared by:
PN. MARZITA ISMAIL
PENSYARAH
UNIT SAINS KOMPUTER
KOLEJ MATRIKULASI KEDAH
Terms Definition/ Description
1.0 Approach in Problem Solving
o the process of formulating a problem, finding a solution and
1.1 Problem solving expressing a solution.
1.2 Steps in Problem Solving o An analysis of a problem statement to identify input, process and
i. Problem Analysis output (IPO):
o Use IPO 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)
ii. Design a Solution ** Tips to handle complex problem statements,
• Algorithm
KENAL PASTI IPO REVERSELY (MENGUNDUR)… you can ask
iii. Implementation
yourself:
iv. Testing
✓ Apa program ini perlu produce/display kepada user? (OUTPUT)
• Program verification
✓ APA process(s) yang perlu dilaksanakan untuk
• Program testing
menghasilkan@produce the output(s)? (PROCESS)
• Errors
✓ Apakah data@value(s) yang bergantung kepada user (berubah-
• Debugging
v. Documentation ubah) dan tidak diberi dalam soalan, but we need it from
(definition/purpose)
user@database untuk pastikan process dilaksanakan (INPUT)
• can be done in
Two (2) ways: ** JAWAPAN IPO PERLU MENEPATI PERSOALAN-PERSOALAN DI ATAS
o involves creating an algorithm
o a sequence of well-defined steps to solve a problem
o can be represented using pseudocodes or flowcharts
o the process of implementing an algorithm by writing a computer
program using a programming language (such as Java language).
o main objective is to convince that the program will do what it is
expected to do
o the process of ensuring that a program meets user-requirement
(verify output with different inputs)
o the process of executing a program to demonstrate its
correctness
o 3 types of error: Syntax Errors
Run-time Errors
Logic Errors
o A process of removing errors from a program
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_April2021
2.0 Design a Solution Definition/ Description
Terms o A sequence of well-defined steps to solve a problem
o A written statement of an algorithm using a semiformal language
2.1 Algorithms:
• Pseudocode with limited vocabulary
• Flowchart • intended for human reading rather than machine reading
• description is verbal
o A graphical representation consisting of geometrical shapes 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
3.3 Control Structure: On-Page Connector: (Shape:Circle)
o SEQUENCE o provides continuation of a logical path on the same page
o Shows the logical order of program instructions
o performs actions one after another in sequence
Pseudocode Example Flowchart General Example
General Format Format
Start
action1
action1 action2
action2
action3
…
…
action n
Stop
Java General Syntax Example of Full Java Code
{
action1;
action2;
…………..;
}
mieta_ismail@KMK_April2021
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 Example Flowchart General Example
General Format Format
Start
Start input mark
…… if (mark > 40)
if <condition> print “PASS”
<action1> end if
……
End
Stop
Java General Syntax Example of Full Java Java General Syntax Example of Full Java
# if True, 1 action Code # if True, more than 1 Code
{ action
……..
…….. {
if (condition) ……..
……..
action1; if (condition)
…….. { action1;
……..
} action2; }
else
{ …………..;
…………..; }
}
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 Example Flowchart General Example
General Format Format
Start Start
…… input mark
if <condition> if (mark > 40)
<action1> print
else “PASS”
<action2> else
end if print “FAIL”
…… end if
Stop End
mieta_ismail@KMK_April2021
Java General Example of Full Java Code Java General Example of Full Java Code
Syntax Syntax
# if True, more
# if True , 1 action than 1 action
{ {
…….. ……..
…….. ……..
if (condition) if (condition)
{ action1;
action1;
else action2; }
else
action2; { action3;
……..
} action4; }
……..
}
o Multiple o Checks many conditions to choose between many actions
Selection o Condition will be checked one by one
(if-else-if ) o When a condition is true, perform the action(s) and stop
checking the rest
Pseudocode General Format Example
Start Start
…… input number
if <condition1> if (number > 0)
print “positive”
<action1> else if (number < 0)
else if <condition2> print “negative”
else
<action2> print “zero”
else end if
<last action> Stop
……
end if
Stop
Flowchart General Format Example
mieta_ismail@KMK_April2021
Java General Syntax Example of Full Java Code
# if True, 1 action
{
……..
……..
if (condition1)
action1;
else if (condition2)
action2;
else if (condition3)
action3;
else
action4;
……..
}
Java General Syntax Example of Full Java Code
# if True , more than 1 action
{
……..
……..
if (condition1)
{ action1;
action2; }
else if (condition2)
{ action3;
action4; }
else if (condition3)
{ action5;
action6; }
else
{ action7;
action8; }
……..
}
mieta_ismail@KMK_April2021
o REPETITION: performs one or more actions repeatedly 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)
Types:
Pseudocode Format
Counter-controlled 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_April2021
Counter-controlled Flowchart Example Sentinel-controlled Flowchart Example
start
counter = 0
False
counter < 10
True end
Print “Welcome
to KMK”
counter = counter + 1
mieta_ismail@KMK_April2021
Examples based on problem statement:
Examples of full Java code
Counter-controlled Flowchart Example Sentinel-controlled Flowchart Example
mieta_ismail@KMK_April2021
Examples of full Java code
Counter-controlled Flowchart Example Sentinel-controlled Flowchart Example
mieta_ismail@KMK_April2021
Examples of full Java code
Counter-controlled Flowchart Example Sentinel-controlled Flowchart Example
mieta_ismail@KMK_April2021
3.0 Java Language Object oriented programming (OOP) is a programming technique
3.1 Intro to JAVA that uses “objects” to design the applications and computer
Object Oriented Programming programs
(OOP)
a process of hiding the implementation details and showing only
OOP Characteristics: functionality to the user
• Abstraction a process of wrapping code and data together into a single unit
a mechanism in which one object acquires all the properties and
• Encapsulation behaviors of a parent object.
• Inheritance a concept by which we can perform a single action in different ways.
• Polymorphism
Class a description of the properties and the behaviors of one or more
objects, but NOT their particular values
Object an entity that has both state and behavior
Basic Components of Java ** Refer PDF/PPT file STEPS TO CODE IN JAVA for examples OF THESE
Programs: COMPONENTS
contains information about the program, but that has no effect when
• Program Comments the program runs
• import statement Eg: //Author : Faizal Tahir
will import classes in a package (a collection of pre-defined library,
classes and interfaces)
Eg: import java.util.Scanner;
• Class declaration a keyword used for developing user defined data type
Eg: class JavaProgram {
• Method main () A program driver which starts the execution of Java program
Eg: public static void main (String[ ] args) {
• Block of Statements • Represents a set of executable statements which may include:
– creating instance of a class (object)
– declaring variables, (details @4.2)
– input statement(s)
– processing statement(s) Details refer below:
– output statement(s)
Input statement(s) used to accept data entered by user into the computer
Processing statement(s) • 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();
Used to manipulate inputs to produce the output.
It involves the use of arithmetic operators, relational operators &
logical operators
Eg: i. result = p * q; -→ arithmetic
ii. if (true && true) → logical
iii. while (c <= 10) → relational
Output Statement(s) used to display output on the screen
o System.out.print();
mieta_ismail@KMK_April2021
3.2 Data Types, Operators, and Expressions:
3.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:
• 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 other symbols other than letters, digits,
dollar sign $, and underscore (_)
• Must not use reserved words, such as if, while, int, do, float
3.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
3.2.3 Constants
used
3.2.4 Reserved Word syntax: <datatype> <variable name>;
Primitive Data Types: eg: double marks;
• int – integer an identifier that is similar to a variable except that it holds fixed value
• double – double while the program is active
floating-point Syntax : final <datatype>< CONSTANT_NAME>= <value>;
• boolean – true/false
value eg: final double pi = 3.142;
• char – character keywords that are reserved by Java functions.
Escape Characters Eg: class, public, static void, main, return, int, double, boolean,
true, false, final, if, else, while, for
Operators: Refer to the type of data that can be stored in a variable
Types of operators: Used to declare variables that will store integer numbers, such as 7, -
11, 0, 31914
• Arithmetic Used to declare variables that will store larger decimal numbers, such
(for Mathematical as 3.4, 0.01, -11.9.
Operations) A Boolean value represents a true or false condition
Used to declare variables that will store alphanumeric data, such as
‘A’, ‘a’, ‘9’, ‘*’
• 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)
generate some computations when applied to operands in
expression.
includes using five arithmetic operators to perform addition,
subtraction, multiplication, division and taking the modulus.
(+, - , *, /, %)
• Relational ** Mathematical Operations → the manipulation of variables using
(for Conditional arithmetic operators resulted to one single value.
Operations) refers to the comparison of values. (==, <, >, <=, >=, !=)
mieta_ismail@KMK_April2021
• Logical: • applied to one or more relational expression.
i. AND - && • used to:
ii. OR - || • negate (inverse) a relational expression
iii. NOT - ! • connect two or more relational expressions
• Assignment (=)
Precedence of Operators: • is TRUE if both are true, and false otherwise
• is TRUE if a or b or both are true, and false otherwise
• if some Boolean condition a is true, then !a is false; if a is false,
then !a is true
Used to assign (give) a value or results of an expression on the right-
side to a variable on the left-side of an equation, (=).
HIGHEST OPERATOR Description ASSOCIATIVITIY
() Grouping Evaluate from inside out
! Logical NOT Right to left
* /% multiplication, Left to right
division, modulus
+- addition, Left to right
subtraction
< <= > >= == != relational Left to right
LOWEST && Left to right
Logical AND
|| 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
3.3 Use of Control Structure CODING : • Refer 2.2 for general format of Java syntax for
Sequence each control structure
Selection
Repetition • Refer Handouts Steps to Code in Java for a
complete program code (eg. given, Sequence)
3.3. Programming Errors: Occurs when the syntax of the programming language is violated.
• Syntax Error • statement cannot be translated and program cannot be executed
• Common examples are:
• Run-time Error
• Logic Error – Misspelled variable and function names
– Missing semicolons
– Improperly matches parentheses, square brackets [ ], and
curly braces { }
– Incorrect format in selection and loop statements
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
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
mieta_ismail@KMK_April2021
3.4 Array : is an ordered sequence of data of the same type.
▪ Consist of:
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: If value will be input by user:
i. Declare array: (data type) Choose: Declare & Create array separately
eg: double [ ] marks; OR
together in 1 statement
ii. Create array: (size)
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();}
If data/value set by programmer, refer below :
iv. Declare & Create & Assign data/value
a) Do it in 3 steps of statements OR together in 1 statement b) Done it seperately
(examples for each data type) If data/value set by programmer, refer below :
i)3 steps of statements: //declare & create array in 1
int []days; //declare data type of array days statement
days =new int [4]; //create array days, 4 in size double [ ] marks = new
double [5];
days[]={25,14,23,17}; //assign data into array days
//assign data one by one
OR statement
marks[0]=50.5;
ii)1 statement ONLY
marks[1]=50;
//declare,create & assign value of an int type array name days marks[2]=70.5;
int [ ] days = {25,14,23,17}; marks[3]=90;
marks[4]=40.5;
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
mieta_ismail@KMK_April2021
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 ( mark [1] + marks[3] );
Skills to cover in Solution Example
Array
i. Find Sum
ii. Find Average
iii. Find
Largest/Smallest @
Min/Max @
Fastest/Slowest @
Highest/Lowest & etc.
Find Frequency
mieta_ismail@KMK_April2021
3.5 Method: a collection of statements that are grouped together to perform an
Types: operation.
1. Standard Library Method ** Adv: - Code reusability – write once, use it multiple times
2. User – defined Method - More readable & easier to debug
Built-in methods in Java that are readily available for use.
Eg: 1. sqrt() → method defined in Math class. It returns square root
of a number → Syntax : Math.sqrt(9) or Math.sqrt (n)
2. pow(base,exp) → method defined in Math class. It returns
a base number that had been raised to the
power of exponent number
→ Syntax : Math.pow (p,20)
A method that is defined by the programmer.
1. Method definition:
General Format:
<returnType><methodName>(parameter/s) {
//method-body
}
Eg: double calcAreaRect (double l, double w) {
return l * w;
} ** Parameters mesti bersama data type masing2
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) {
}
methodName → is an identifier, usually the name represents the
task performed by the method.
Parameters → a placeholder to hold value of the passed arguments.
Method-body → it define:
– what the method actually does,
– how the parameters are manipulated with programming
statements and
– what value is returned.
2. Create object (to use the method/s)
General Format:
ClassName obj = new ClassName () //obj can be replace with any
Name
Eg: CalcArea obj = new CalcArea ()
3. Method call:
General Format:
<objectName>.<methodName>(argument/s)
Eg: obj.calcAreaRect(length, width);
mieta_ismail@KMK_April2021
Steps to apply Method:
Eg: class CalcArea {
Main Method
{
(use import statement & initialize variables involve as usual)
+ 2. Create object → className objectName = new className ( );
Eg : CalcArea obj = new CalcArea ( ); ** guna cara 1 ini bila output
dilaksana dlm method baru ,
+ 3. Call Method (3 cara) → 1. objectName.methodName (argument/s); selesaikan semua task termasuk
Eg : obj.calcAreaRect (length, width) ; output di method baru..jadi,
tiada return value
2. variable = objectName.methodName (argument/s);
Eg: area = obj.calcAreaRect (length, width); ** cara 2 ini kita assignkan
System.out.print (area); method call kpd 1 variable…
guna cara ini bila nak display
** cara 3 ini kita letakkan arahan output dlm method main
method call terus kpd output mnggunakan variable..perlukan
statement…tanpa gunakan return value dari method baru..
variable…juga perlukan return
value dari method baru… 3. System.out.print (objectName.methodName (argument/s));
Eg: System.out.print (obj.calcAreaRect (length, width));
}
+ 1. Define method (ada 4 jenis – guna cara yang sepatutnya as asked in the question)
i., RETURN VALUE, ACCEPT PARAMETER(S) (have parameters, use suitable data type for
returnType)
newMethod
** parameters kalau ada… wajib ada data type
double calcAreaRect (double l, double w) {
return l * w;
@ ** ada 2 cara utk return value:
double area = l * w; 1. Directly return the calculation
return area; 2. Return menggunakan variable
}
ii.NOT RETURN VALUE , ACCEPT PARAMETER(S) (have parameters to hold arguments, use void
for returnType because this type of method did not
newMethod return any value to main )
void calcAreaRect (double l, double w ) {
double area = l * w;
System.out.print (“Area of rectangle = “ + area);
}
mieta_ismail@KMK_April2021
iii. RETURN VALUE, NOT ACCEPT PARAMETER(S) (bracket ( ) left blank , use suitable data type
for returnType )
newMethod
double calcAreaRect ( ) {
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 )
newMethod void calcAreaRect ( ) {
@ double l = 5.0, w=4.0;
void calcAreaRect ( ) {
double area = 5 * 4; double area = l * w;
System.out.print (area); System.out.print (area) ; }
}
RevisionNotes+Worksheet_SC025
mietaIsmail@kmk_April2021
mieta_ismail@KMK_April2021
“WE LOVE
PROGRAMMING.
WE LOVE JAVA”
Credit to:
En. Mohd Amran b Md Ali & Pn. Maziah Mohd Zin
~Reference Book Writer~
mieta_ismail@KMK_April2021