Tips for SC025 2018/2019
Kolej Matrikulasi Perak
PROBLEM SOLVING, ALGORITHM, CONTROL STRUCTURE
Problem solving 5 steps in Problem Solving
- is the process of transforming the Step 1 : Problem analysis
description of a problem into a solution. Step 2 : Design a Solution
Step 3 : Implementation
Step 4 : Testing
Step 5 : Documentation
1. Problem Analysis 2. Design a solution
An analysis of a problem statement to identify input, Design an algorithm, a sequence of well-defined
process and output steps to solve a problem.
Sequence Algorithm
is a step-by-step instruction that will transform the
I : INPUT
input into the output. The algorithm is the abstract
P : to calculate OUTPUT based on INPUT
idea of solving a problem.
O : OUTPUT
Algorithm Technique
Selection Pseudocode
I : INPUT - A written statement of an algorithm using a
P : to determine OUTPUTA OR OUTPUTB based on semiformal language with limited vocabulary
INPUT - Intended for human reading rather than
O : OUTPUTA OR OUTPUTB machine reading
Main purpose : to define the procedural logical of an
Repetition algorithm in simple and easy to understand for its
reader
I : INPUT for ____ times
P : to calculate OUTPUT based on INPUT for _____ Flowchart
times - Flowchart is a graphical representation of an
O : OUTPUT for ____ times algorithm in relation to its sequence of
functions
3. Implementation OR
is the process of implementing an algorithm by - A set of standard shaped boxes that are
writing a computer program using a programming connected by flow lines to represent an
language (for example, using Java language). algorithm
OR
Writing algorithm in the form of computer program
through programming language.
4. Testing 5. Documentation
is the process of executing a program to demonstrate Make description that helps editing or maintaining the
its correctness (i.e. run the program). program later.
OR - Writing Comments
Verify the program is correctly designed and ensures - Create a separate Text File.
the program meet user requirements.
Important to test and debug the program Importance of documentation
Finding syntax error and correcting program code Documentation enable programmer to
mistake. - understand the flow of program.
for future reference.
- to guide user to use the program
- Explain the purpose of code statement
Prepared by :
Nooraini Binti Dilah
~ Mdm Abu Bakar & Zuraidah Binti Ismail
1
Tips for SC025 2018/2019
Kolej Matrikulasi Perak
3 types of error. How to write report: Use comment in the coding.
Syntax error :
Program error that occurs when the code violates the
syntax or grammar of the programming language.
e.g : misspelling a command, leaving out require
command. Types of control structure
- Improper matched parentheses, square Sequence
- Performs actions one after another in
brackets and curly braces.
sequence
- Misspelled variable and Method names.
Selection
- Missing Semicolons (;) - Performs action(s) based on a certain
- Incorrect Format of Looping Statements. condition
- Statement unable to translate (compile). Repetition
* The Program will not run. - Performs one or more actions repeatedly
while a certain condition is true.
Logic error :
Types of selection
- Flow in program design that causes
- Single Selection (single if)
inaccurate results. - Dual Selection (if else)
- Calculation Error (Based on programmer) - Multiple Selection (nested if)
- Producing wrong result.
- Hard to Identify Types of looping
* The program may still run. - Counter control
- Sentinel Control (Sentinel Value is value will
e.g : sum = no1- no2 end the looping)
Runtime error :
- Program error or event that causes the
program to stop running.
- Infinite Loop - Program Unable to terminate
by itself.
e.g :
- Dividing a number by zero (6/0).
- The compiler will issue a run-time error if you
try to change the value of a constant during
execution
INTRODUCTION TO JAVA
Define OOP Characteristic of OOP
Object oriented programming (OOP) is a - Abstraction (shows only essential things to
programming technique that uses “objects” to design the user)
the applications and computer programs. - Encapsulation (information hiding)
- Inheritance (one object acquires all
properties and behaviors of a parent object)
- Polymorphism (Perform single activity
through different ways)
Describe characteristic of OOP Abstraction Vs Encapsulation
Abstraction is a process of hiding the
Abstraction Encapsulation
implementation details and showing only functionality
to the user.
is a process of is a process of making
Prepared by :
Nooraini Binti Dilah
~ Mdm Abu Bakar & Zuraidah Binti Ismail
2
Tips for SC025 2018/2019
Kolej Matrikulasi Perak
Encapsulation in Java is a process of wrapping
collecting important a complex system
code and data together into a single unit.
information which will easier to handle for an
create a base for end user, without
Inheritance in Java is a mechanism in which one
building up a complex worrying about its
object acquires all the properties and behaviors of a
system. internal complexities.
parent object.
focuses on “identifying focuses on “hiding the
Polymorphism in Java is a concept by which we can
the necessary internal complexities of
perform a single action in different ways.
components for building a system”.
a system”
Why Java? Class
- Defines behaviors of Object.
Platform Independent - Collection of objects of similar types.
- Write Once, Run Anywhere. - Generic. Create objects from each class.
Object-Oriented Object
- Complex Problem is divided into smaller sets - Entity that has both state and behavior.
by creating objects. - Does things depends on its properties.
- Code reusable, design benefits, easier to - Characteristic : State, behaviour, identity
maintain.
Elements of Object
Fast - Identity (Independent)
- Faster than Python, PHP. - State/attribute (define characteristics)
- Behavior (perform actions)
Secure
- Automatic Memory Management, reduces
memory corruption. Components of Java Program
- Protect integrity and privacy of data
transmitted. - Comments
- Import Statements
Large Standard Library - Class Declaration
- Have hundreds of classes, methods under - Method main()
different packages. - Blocks of Statements
Program Comments Import Statement
- Do not affect program code, used for - Import Class in a package.
Documentation. - Package is a collection of predefined library,
classes and interfaces.
// comment text, on one line
Top level / sub Package : java.util
Or Class : Scanner
nextInt () Accept input as an int
/* comment text; may
span multiple lines */
nextDouble () Accept input as n double
nextBoolean Accept input as a boolean
nextchar().charAt(0) Accept input as a character
nextLine () Accept input as a String
Prepared by :
Nooraini Binti Dilah
~ Mdm Abu Bakar & Zuraidah Binti Ismail
3
Tips for SC025 2018/2019
Kolej Matrikulasi Perak
Method main() Blocks of Statements
- Execution starts from main() method, known - Creating instance of a class
as program driver. - Declaring Variable
- Input statements
public – Accessible by every java programmer. - Process statements
static – Executes only once. - Output statements
void – No returning of value.
String[] – Takes array of objects.
Output Statement Input Statement
System.out.println(...); import java.util.Scanner;
System.out.print(....); Scanner sc = new Scanner(System.in);
public static void main…..... {
Message only
System.out.print(“ Enter length :”) ; Scanner sc = new Scanner(System.in);
char answer;
Value only double weight;
System.out.print(area) ; int age;
String name;
Combination of message and value
System.out.print(“ Area is : ” + area) ;
answer = sc.next().charAt(0);
weight = sc.nextDouble();
age = sc.nextInt();
name = sc.nextLine();
Identifier Variables
Identifier refers to memory locations which can hold Value can be changed during program execution.
values.
It can be class_name or variable_name or Constant
method_name. Fixed values those are not changed during the
Execution of program
Rules of Identifier
- Rule 1 : Consist of letters A to Z, a to z, digits General form :
0 to 9, the underscore character “_” and the final dataType CONSTANTNAME = value;
dollar sign ($) Eg :
- Rule 2 : The first character must be a letter final double PI = 3.142;
or an “_” or $ sign (i.e. must not begin with
digit) Reserved Words
- Rule 3 : Blank space are not allowed are keywords that are reserved by Java functions
- Rule 4 : Reserved word cannot be used as Eg : if, while, for
identifiers
- Rule 5 : Identifiers are case-sensitive.
Therefore, marks and Marks, both valid
example of identifiers, are distinct
Escape Characters Data Type
- character preceded by a backslash (\)
- has a special meaning to the compiler Primitive data type
Prepared by :
Nooraini Binti Dilah
~ Mdm Abu Bakar & Zuraidah Binti Ismail
4
Tips for SC025 2018/2019
Kolej Matrikulasi Perak
- Integer (int)
Tab (\n) - Double floating point (double)
System.out.println("She said \tHello!\t to me."); - Character (char)
Output : - Boolean - true/false value
She said Hello! to me.
Primitive Rules
Data Type
New Line (\n)
int integer number (whole numbers)
System.out.println("She said \nHello! \nto me.");
Output :
She said double decimal numbers
Hello!
to me. char a single character delimited by single
quote.
Single Quote Character (\’)
System.out.println("She said \’Hello! \’ to me."); boolean a logical value (true or false) *all
She said ‘Hello!’ to me. words true ,false written in small
letter. it cannot be 0,1 in Java.
Comment
// Save as "Hello.java"
String is NOT a data type in Java. String is a Class
/* Name : and begin in uppercase.
Matric No : MS12345 */
Type of Operator Precedence and Associativity of Operators
Arithmetic Operator Operators Associativity
- + - * / %
Highest () Evaluate from inside out
Remember
! Right to left
int/ int → int 50/100 = 0
* / % Left to right
double / int → double 50.0/100=0.5
+ - Left to right
int/double → double 50/100.0=0.5
< <= > Left to right
int/int → int 10%5=0 >= == !=
double%int → double 10.0%5=0.0 && Left to right
double%int → double 10.5%5=0.5 || Left to right
Lowest
int%int → int 7%4=3 = Right to left
Relational Operator
- == != > < >= <=
Logical Operator
- && || !
ARRAY
Define array Advantage Array
Prepared by :
Nooraini Binti Dilah
~ Mdm Abu Bakar & Zuraidah Binti Ismail
5
Tips for SC025 2018/2019
Kolej Matrikulasi Perak
- Code Optimization: It makes the code
An array is an ordered sequence (index) of data of optimized, we can retrieve or sort the data
the same type. efficiently.
- Random access: We can get any data
- Array is a fixed sized collection of located at an index position.
consecutive memory location.
- Each memory location in an array is Disadvantages Array
accessed by a relative address called index - Size Limit: We can store only the fixed size
of elements in the array. It doesn't grow its
Variable Loop Vs Variable Array size at runtime. (To solve this problem,
collection framework is used in Java which grows
automatically.)
Variable Loop Variable Array
Can hold 1 Can hold many value at a
value at a time time
int m=sc.nextInt(); int i;
int [ ]m=new int [3];
for (i=0;index<m.length;i++) {
m[i]=sc.nextInt();
}
Declare Array Example Pseudocode for Array
Method 1: Start
int ArrayName[ ]; //declaring array Declare, create and, initialize num[10]
ArrayName = new int[20]; // Creating array by Sum = 0.0, i = 0
specifying its size Repeat while i < num.length
Read num [i]
Method 2 : Sum = sum + num[i]
int [ ] ArrayName = new int[20]; i=i+1
End repeat
Average = sum / num.length
Display average
End
Operation in Array (Matriculation Syllabus) Example Coding for Array
- Linear search class Average {
- Total elements public static void main(String[] args) {
- Average double [] num = new double [10];
- Finding max / min double sum = 0.0, average;
- Frequency for (int i = 0; i < n
um.length; i++) {
um[i] = sc.nextDouble();
n
Refer Code Note
sum = sum + n um[i];
}
average = sum / num.length;
System.out.format(average);
}}
METHOD
Define method Consist of :
Prepared by :
Nooraini Binti Dilah
~ Mdm Abu Bakar & Zuraidah Binti Ismail
6
Tips for SC025 2018/2019
Kolej Matrikulasi Perak
A Java method is a collection of statements that are - Method data type to return
grouped together to perform an operation. - Method name (Start with lowercase)
- Method parameters (DataType
Function : variableName)
This helps in reuse of the code and also it helps to - Method body : a sequence of statements in
organize and simplify coding. a block
Advantage Argument Vs Parameter
1. Time saver : Methods are time savers and What is passed to a method is referred to as an
help us to reuse the code without retyping "argument" / Actual parameter.
the code. The "type" of data that a method can receive is
2. Code reusability : You can write a method referred to as a "parameter" / Formal parameter.
once, and use it multiple times. You do not
have to rewrite the entire code each time. - Argument is a value that is passed (from
Think of it as, "write once, reuse multiple method main) to a method (user defined
times." method)
3. Make code more readable and easier to - Parameter is a variable defined by a method
debug : For example, findSum() method is so that receives a value when the method is
readable, that we can know what this method called
will be doing than actually reading the lines
of code that make this method.
Method Type Static Vs Non Static
- Standard Library Methods - built-in
methods in Java are readily available for
Instance (non-static) Static Method
use.
Method
- User-defined Methods - method that is
defined by the programmer
Instance method is not Static method is
with static keyword declared with static
keyword.
In a program, it has to In a program, it can be
be called by using called directly by using
object of the class method name
Belong to the object of Belong to the class.
the class. You have to You can access it
create an instance of without creating an
the class to access it instance of the class
Standard Library Method User Defined Method
built-in methods in Java that are readily available for is a method that is created by the programmer.
use.
Eg : The three (3) parts :
print(....) - Return type
println(....) - Method name
sqrt() - Parameter
pow()
Static : Return Value
Example : static int total (int a, int b) {
import java.util.Scanner; return a*b;
……... }
int a, b, c; Static : No Return Value
a = sc.nextInt(); void static int total (int a, int b) {
Prepared by :
Nooraini Binti Dilah
~ Mdm Abu Bakar & Zuraidah Binti Ismail
7
Tips for SC025 2018/2019
Kolej Matrikulasi Perak
b = sc.nextInt(); System.out.println(a*b);
c = sc.nextInt(); }
int x = Math.pow(a,b);
double y = Math.sqrt(c); Non Static : Return Value
System.out.println(x); int total (int a, int b) {
System.out.print(y); return a*b;
}
Non Static : No Return Value
void int total (int a, int b) {
System.out.println(a*b);
}
Method Call Method Call : Return Value
2 ways : Static Method
- Returns a value, or int c = 0;
- No returns value (declared as void) c = methodName;
System.out.print(c);
A method must be called based on exactly how the
method was defined OR
- Method name
- Method type System.out.print(methodName)
- Number of parameters
- Sequence of data type for each parameter Non Static Method
int c = 0;
MyJavaProgram obj= new MyJavaProgram();
c = obj.methodName;
System.out.print(c)
OR
System.out.print(obj.methodName);
Prepared by :
Nooraini Binti Dilah
~ Mdm Abu Bakar & Zuraidah Binti Ismail
8