0% found this document useful (0 votes)
3 views43 pages

76b33010-6fdb-4e4f-9426-94403f16f741

The document outlines effective problem-solving strategies, emphasizing cost, time, and resource management. It details the steps of problem-solving, the use of algorithms, pseudocode, and flowcharts for expressing solutions, as well as the importance of variable declaration and data types in programming. Additionally, it covers error types in algorithms and the significance of selecting appropriate data types to optimize memory usage.

Uploaded by

69rjqm6jjr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views43 pages

76b33010-6fdb-4e4f-9426-94403f16f741

The document outlines effective problem-solving strategies, emphasizing cost, time, and resource management. It details the steps of problem-solving, the use of algorithms, pseudocode, and flowcharts for expressing solutions, as well as the importance of variable declaration and data types in programming. Additionally, it covers error types in algorithms and the significance of selecting appropriate data types to optimize memory usage.

Uploaded by

69rjqm6jjr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

Created by Turbolearn AI

1.0 Pengaturcaraan

1.1 Strategi Penyelesaian Masalah

1.1.2 Menjelaskan Ciri-Ciri Penyelesaian Masalah Berkesan


Effective problem-solving involves considering cost, time, and resources.

Cost: The price to acquire, produce, and maintain. This often involves money,
time, energy, and expenses.
Normal Project: Completed within allocated time and cost.
Crashing Cost: Maximum effort to complete a project in the shortest time,
which increases costs.
Time: Refers to completing projects within the set timeframe. Delays increase
costs, and needing to complete a project quickly also increases costs.
Resources: Stocks, money, raw materials, staff, and other assets used by an
organization to function effectively and generate results.
Resource Planning: Management's responsibility to optimize decisions.
Careful planning avoids waste.
Resource Scheduling: Prevents project delays. Resource shortages slow
down project completion and increase costs.

Problem-solving steps:

1. Collect and analyze data.


2. Define the problem.
3. Generate ideas.
4. Generate solutions.
5. Determine actions.
6. Implement solutions.
7. Evaluate.
8. Make improvements.

1.2 Algoritma
1. A set of instructions for solving a problem.
2. Detailed instructions that can be followed.
3. Can be refined by adding details.

Page 1
Created by Turbolearn AI

Characteristics of an algorithm:

Clear details
Executable
Has limitations

1.2.1 Menggunakan Algoritma untuk Menyatakan


Penyelesaian Kepada Masalah
Analysis of Input, Process, Output (IPO):

Identify input data, processes to change data values into information, and
output displays.

The Input-Process-Output (IPO) chart can be used to analyze problems.

Input: Identifying data that needs to be read from the user or


environment.
Process: Steps or formulas to process input data into output.
Output: Identifying the required output, what needs to be displayed on
the screen at the end of the program.

Example of IPO:

Input: Year of birth


Process:
1. Read input year of birth.
2. Get the current year from the computer system (current year).
3. Age = Current year – Year of birth
Output: Age

1.2.1 Menggunakan Algoritma untuk Menyatakan


Penyelesaian Kepada Masalah
Algorithms can be represented using:

Pseudocode
Flowcharts

Page 2
Created by Turbolearn AI

1.2 Pseudocode
1. Not a computer programming language.
2. Instructions written in everyday language.
3. Each instruction is a mathematical expression, logical expression, control
structure, or use of computer functions.
4. Each instruction is placed in a new line with a serial number.

Steps to write pseudocode:

Write the START statement.


Read INPUT.
Process data using logical or mathematical expressions.
Display OUTPUT.
Write the END statement.

1.2 Flowchart

The image above shows a flowchart illustrating the steps to calculate the area of a
circle, beginning with "Start", reading in the radius, setting pi to 3.142, calculating the
area, displaying the area, and concluding with "End".

Page 3
Created by Turbolearn AI

Symbol Name Function

Terminal Start Beginning of the algorithm in the flowchart.


Terminal End End of the algorithm in the flowchart.
Input/Output Reads input or displays output to the screen
Instruction to process input in the form of expressions,
Process
processing files, etc.
Connector Connection point to connect separate flowcharts.
Condition Tests the condition in the requirement.
Activity
Connects nodes to show the process flow.
flow

Steps to build a flowchart:

Draw the START terminal node.


Draw connecting lines.
Draw an input node, entering details such as data assignment.
Draw connecting lines.
Draw a process node, entering details such as mathematical expressions.
Draw connecting lines.
If necessary, draw other process nodes or input nodes as needed.
If not, draw the END terminal node.

1.2.3 Menguji dan Mebaiki Ralat dalam Algoritma


Types of algorithm errors:

Syntax Error
Logic Error
Runtime Error
Error Description

Syntax Does not exist in the algorithm. Occurs due to carelessness when using
Error the programming language. Usually found automatically by the compiler.
Occurs because the software does not perform its intended function, is
Logic Error
incomplete, or produces inaccurate output.
Runtime Errors that arise when the program is run, for example, the program
Error cannot be started, is very slow, or is unresponsive.

Page 4
Created by Turbolearn AI

1.2.4 Mengesan Nilai Pemboleh Ubah Pada Setiap Tahap


Dalam Algoritma
Algorithms assign and change the value of a variable.
The value of a variable is not fixed.
Each line of the algorithm may make changes to a specific variable.
A variable table is used to track the value of variables at each stage of the
algorithm.
No. z I/O

1 - -
2 100 100
3 50 -
4 200 -
5 250 -
6 250 250
7 - -

1. Start
2. Input z = 100
3. z = z / 2
4. z = z * 4
5. z = z * 0.25 + z
6. Display z
7. End

1.2.5 Mengenal Pasti Output yang Betul dari Algoritma


Berdasarkan Input yang Diberi
Correct output depends on the variable when the algorithm display is called.
Comparing the expected output is the only way to determine the validity of the
algorithm's output.
The expected output is determined by manual calculation.
If the algorithm's output is correct, it should be the same as the expected
output.

Page 5
Created by Turbolearn AI

No. x y Jumlah I/O

1 - - - -
2 12 - - -
3 12 88 - -
4 12 88 100 12 + 88 = 100
5 12 88 100 Jumlah = 100
6 - - - -

1.2.6 Terjemahan Algoritma ke Dalam Bahasa


Pengaturcaraan
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 be based on any
programming language.
Examples of programming languages are Visual Basic (VB), Java, C#, etc.
Algorithm Computer Code (Java)

Start public static void main (String[] args) {


Display "User Name" System.out.print (“Enter user name: “);
String nama new java.util. Scanner (System.in)
Input Name
nextLine();
Display "Hello". Name ,
System.out.println (“ Hello “ + nama);
"?"
End ;

1.3 Pemboleh Ubah, Pemalar dan Jenis Data

Page 6
Created by Turbolearn AI

Variables or constants in Java need to be declared before use.

In the programming process, a programmer needs to declare the type of data


needed in a program to be executed.

Temporary storage space for numbers, text, and objects.

The value of a variable always changes during data processing and will not
hold any value after the program ends.

Programmers need to name each variable used to solve a problem in the


developed program.

Programmers use variable names as reference names for specific variable


values.

The computer uses the variable name as a reference to find the variable's value
in its memory.

The value of a constant is fixed and will not change during the programming
process.

Used when programmers want to declare a value that will not change.

The type of data declared must match the value.

A set of data that has defined values and characteristics.

Data will be processed to produce output.

Data types can be categorized into 2 classes: primitive data and non-primitive
data.

Page 7
Created by Turbolearn AI

Data Computer Memory


Example Value
Type Capacity

Minimum -2147483648 Maximum


Integer 4 bytes
2147483647
Minimum -3.4e38 Maximum
Float 4 bytes
3.4e38
Minimum -1.7e308 Maximum
Double 8 bytes
3.4e38
Single character
Char 2 bytes
only
String Starting from 0 to unlimited > 10 bytes
Boolean True (true) False (false) 1 byte

1.3.1 Menjelaskan Hubungan Antara Jenis Data, Saiz Data


dan Kapasiti Ingatan Komputer
Each type of data will be stored in computer memory.
The variable name plays an important role in determining the size of data in
memory.
The operating system determines what can be stored in the computer's
memory based on the data type used by the variable.
The variety of data types used on variables can save space in computer
memory.

1.3.2 Memilih dan Menggunakan Jenis Data yang


Bersesuaian
The selection and use of appropriate data is very important so that programs
can be developed without syntax errors.
The data type for variables and constants determines the type of information
that will be stored in the allocated memory space.
The use of appropriate data types functions as a benchmark for whether a
variable stores fixed data, calculable data, letters, decimal numbers, or data
with true or false values.

Page 8
Created by Turbolearn AI

Data Type

Integer Includes all numbers that do not have fraction or decimal values.
Real
Consists of all numbers that have a decimal point or fractional part.
Number
Data in the form of spaces, text, words, or values containing a sequence
Character
of characters or symbols.
Boolean Data in the form of a choice, i.e., choosing one of something true or false.

1.3.3 Membezakan Pemboleh Ubah Sejagat (Global) dan


Setempat (Local)
Each variable and constant may exist and will be used for the entire program or
only for one function.
The existence of variables or constants is known as the area where both can be
used legally.
Scope of
Variables

Only works in the program. When the procedure ends, the


Global Variable memory space also ends. Can be used until the end of the
program.
Only works in the subprogram that is declared. Used in functions
Local Variable where variables are declared starting from where the variable is
declared and when the procedure ends.
Declaration of
Outside any function.
Global Variable
Declaration of
In a function within the program.
Local Variable
Can be accessed from any function. If a local variable has the same
Access to Global
name as a global variable, reference is only made to the nearest
Variable
variable (local).
Access to Local Cannot be accessed outside that function. There is no problem if
Variable two functions use the same local variable.

Page 9
Created by Turbolearn AI

1.3.4 Mengisytiharkan, Memulakan dan Menetapkan Nilai


Pada Pemboleh Ubah dan Pemalar
Variables are known as places to store data.
Each variable in Java has a specific type that determines the size and layout of
memory and the set of operations that can be used.
All variables need to be declared before they can be used.
Variable declaration needs to be implemented by providing the data type and
variable name.
Data Variable
Example
Type Name

java public class pembolehUbah { public static void


Integer X
main(String[] args { int x ; } }
java public class pembolehUbah { public static void
String Name
main(String[] args { String nama ; } }
java public class pembolehUbah { public static void
Double s, t, u
main(String[] args { double s,t,u ; } }
java public class pembolehUbah { public static void
Boolean v
main(String[] args { boolean v ; } }
java public class pembolehUbah { public static void
Char w
main(String[] args { char w ; } }
java public class pembolehUbah { public static void
Float y
main(String[] args { float y ; } }
After declaring the type and name of the variable, a value can be set or
assigned to the variable.

Page 10
Created by Turbolearn AI

Data
Value Example
Type

java public class pembolehUbah { public static void


Integer 10
main(String[] args { int x = 10 ; } }
java public class pembolehUbah { public static void
String hardeep
main(String[] args { String nama = “hardeep” ; } }
java public class pembolehUbah { public static void
s=
Double main(String[] args { double s = 0.123, ,t = 1.1 ,u = s + u ;
0.123
} }
java public class pembolehUbah { public static void
Boolean true
main(String[] args { boolean v = true ; } }
java public class pembolehUbah { public static void
Char y
main(String[] args { char w = ‘y’ ; } }
java public class pembolehUbah { public static void
Float 342.234f
main(String[] args { float y = 342.234f ; } }
Constants are variables that have a value that does not change while the
program is running.

final int NUMBER_OF_DAYS_IN_A_WEEK = 7


final double Pi = 3.14
Static final double = 4.14

1.3.5 Menggunakan Pernyataan Umpukan dan Pernyataan


Aritmetik

Type of
Statement

Can consist of one or more other expressions. Refers to "equal to" or


Assignment the symbol " = ". An assignment statement will give a value to a
variable.
Can consist of one or more arithmetic expressions. Refers to
Arithmetic arithmetic operations (+, -, *, /). The main processing unit can only
read arithmetic operations from left to right.

Examples:

Page 11
Created by Turbolearn AI

String x;
x = “ Hello ”;
double p;
p = 0.123;
float w;
w = 561.123f;
int p;
int q;
int r;
p = q =r = 255;
(30 – 5 + ((2*3) / 3)

Example
Notation Program Example
Output

java public class operasiTambah { public static


Hasil
void main(String[] args { int i = 10; int j = 20;
ADDITION Tambah
i = i + j; System.out.println (“ Hasil Tambah
ialah : 30
ialah : “ + i ) ; } }
java public class operasiTolak { public static
void main(String[] args { int i = 30; int j = 20; Hasil Tolak
SUBTRACTION
i = i - j; System.out.println (“ Hasil Tolak ialah ialah : 10
: “ + i ) ; } }
java public class operasiDarab { public static
void main(String[] args { int i = 30; int j = 20; Hasil Darab
MULTIPLICATION
i = i * j; System.out.println (“ Hasil Darab ialah ialah : 600
: “ + i ) ; } }
java public class operasiBahagi { public static
void main(String[] args { int i = 30; int j = 2; i Hasil Bahagi
DIVISION
= i / j; System.out.println (“ Hasil Bahagi ialah ialah : 15
: “ + i ) ; } }

import java.util.Scanner;
Scanner input = new Scanner (System.in);

Page 12
Created by Turbolearn AI

import java.util.Scanner ;
public class luasSegiTiga {
public static void main (String [] args) {
Scanner input = new Scanner (System.in);
System.out.println (“Please enter the base value: ” );
int tapak = input.nextInt();
System.out.println (“Please enter the height value: ” );
int tinggi = input.nextInt();
double luas = (1.0/2) * tapak * tinggi ;
System.out.println (“Area
```## Struktur Kawalan (Control Structures)

This section covers control structures in programming, focusing on how dec

![STRUKTUR KAWALAN](https://api-turbo.ai/76b33010-6fdb-4e4f-9426-94403f16f

This image illustrates the three main types of control structures: sequent

### Struktur Kawalan Pilihan (Selection Control Structure)

* Allows decisions or selections to be made automatically.


* Uses **Boolean conditions** to test input values, determining which se
* Boolean conditions compare variables, object properties, or values usi

The forms of selection control structures include:

* `if`
* `if-else`
* `if-else-if`
* `switch-case`

![KAWALAN PILIHAN](https://api-turbo.ai/76b33010-6fdb-4e4f-9426-94403f16f7

The image breaks down Boolean values (`TRUE` or `FALSE`) and shows the dif

#### `if` Statement

* Executes specific statements only if the condition is `true`.

if () { }

*Example:*

if (age > 20) { System.out.println(“You are eligible to vote.”); }

Page 13
Created by Turbolearn AI

#### `if-else` Statement

* Used for decision-making in a program.


* Shows a Boolean result: `Yes` (`True`) or `No` (`False`).
* Subsequent statements depend on this Boolean result.

if () { } else { }

*Example:*

if (age > 20) { System.out.println(“You are eligible to vote.”); } else {


System.out.println(“You are not eligible to vote.”); }

Page 14
Created by Turbolearn AI

#### `if-else-if` Statement

* Used for more complex decision-making.


* Tests a new Boolean condition if the previous condition is `false`.
* If a Boolean condition is `true`, the corresponding statement is executed,

![CARTA ALIR](https://api-turbo.ai/76b33010-6fdb-4e4f-9426-94403f16f741/6cf179

This image shows a flowchart and syntax diagram of the if-else-if statement.

#### `switch-case` Statement

* Overcomes the shortcomings of using multiple `if-else-if` statements, whic


* Easier to understand.
* Switch Test: Numeric expression, alphabet, or string.
* Case: Contains a value to be matched with the switch test.
* Break: Exits the switch block. If omitted, the next statement will be exec
* Default: An optional step. If the switch test doesn't match any case value

![CARTA ALIR](https://api-turbo.ai/76b33010-6fdb-4e4f-9426-94403f16f741/af8003

This image illustrates a flowchart and syntax diagram for the `switch-case` st

### Combining Relational and Logical Operators in Selection Control Structure

* **Relational operators** compare two values to produce a Boolean result.


* **Logical operators** combine Boolean expressions to produce more complex

Here's a breakdown of relational and logical operators:

| Relational Operators | Description |


| :------------------- | :------------------------------ |
| `==` | Equal to |
| `!=` | Not equal to |
| `>` | Greater than |
| `>=` | Greater than or equal to |
| `<` | Less than |
| `<=` | Less than or equal to |

![OPERATOR LOGIKAL](https://api-turbo.ai/76b33010-6fdb-4e4f-9426-94403f16f741/

The image provides a visual reference for the AND, OR, and NOT logical operato

| Logical Operators | Description


| :---------------- | :-------------------------------------------------------
| AND | Combines two or more Boolean conditions; all conditions
| OR | Combines two or more Boolean conditions; only one condit
| NOT | Converts a Boolean value to its opposite.

*NOT Example:*

| x | NOT x |
| :---- | :------ |
| TRUE | FALSE |
| FALSE | TRUE |

Page 15
Created by Turbolearn AI

*Example Programs:*

*Positive Integer Check:*

```java
public class contoh31a {
public static void main(String[] args) {
int number = 15;
if (number > 0)
System.out.println(“This number is a positive integer”);
else
System.out.println(“This number is not a positive integer”);
}
}

Output:

This number is a positive integer

Integer Type Check:

public class contoh31b {


public static void main(String[] args) {
int number = -7;
if (number > 0)
System.out.println(“This number is a positive integer”);
else if (number == 0)
System.out.println(“This number is zero”);
else
System.out.println(“This number is a negative integer”);
}
}

Output:

This number is a negative integer

Valid Score Check:

Page 16
Created by Turbolearn AI

public class contoh32 {


public static void main(String[] args) {
int score = 55;
if (score >= 0 && score <= 100)
System.out.println(“The entered score is valid.”);
else
System.out.println(“The entered score is invalid”);
}
}

Output:

The entered score is valid.

Taking in Laundry example:

public class contoh33 {


public static void main(String[] args) {
boolean night = true;
boolean rain = false;
if (night || rain)
System.out.println(“Take in the laundry”);
}
}

Output:

Take in the laundry

Check if you passed the exam:

Page 17
Created by Turbolearn AI

public class contoh34 {


public static void main(String[] args) {
boolean pass;
int score = 83;
if (score >= 40)
pass = true;
else
pass = false;
if (!pass)
System.out.println(“You need to repeat the test”);
else
System.out.println(“You passed”);
}
}

Output:

You passed

Fever Warning Example:

public class contoh35 {


public static void main(String[] args) {
double celcius = 39 , Fahrenheit = 97 ;
if (celcius > 39 || Fahrenheit > 98.6)
System.out.println(“You may have a fever.”);
}
}

Output:

You may have a fever.

Kawalan Ulangan (Repetition Control)


This section covers repetition control structures, which include for, while, and do-
while loops.

Page 18
Created by Turbolearn AI

for Loop

public class contoh36 {


public static void main(String[] args) {
int i ;
for ( i = 1 ; i <=100 ; i+=1) {
System.out.print (“i” ) ;
}
}
}

Output:

12345678910.

public class contoh37 {


public static void main(String[] args) {
int total = 0 ;
for ( i = 2 ; i <=100 ; i+=1) {
total = total + i ;
}
System.out.println (“Total : ” + total ) ;
}
}

Output:

5049

public class contoh38 {


public static void main(String[] args) {
for ( i = 0 ; i <= 30 ; i+=1) {
if ((i % 2) == 2)
System.out.print ( i + “, ” ) ;
}
}
}

Output:

Page 19
Created by Turbolearn AI

1,3,5,7,9,11,15,17,19,23,25,27,29

public class contoh39 {


public static void main(String[] args) {
double balance = 500.0;
for ( i = 0 ; i <= 5 ; i+=1) {
balance = balance + (0.1 * balance);
}
System.out.printn ( “ Balance after 5 years : “ + balance) ;
}
}

Output:

Balance after 5 years : 805.255

while Loop

public class contoh40 {


public static void main(String[] args) {
int n = 5 ;
while ( n > 0 ) {
System.out.println (n + “ , ” ) ;
n = n-1;
}
}
}

Output:

5,4,3,2,1

Page 20
Created by Turbolearn AI

import java.util.Scanner;

public class Module1 {


public static void main(String[] args) {
Scanner scanner = new Scanner (System.in);
int nom = scanner.nextInt ();
while (nom > 0 ) {
nom - = 1;
System.out.println ( nom + “ ” ) ;
}
}
}

import java.util.Scanner;

public class contoh42 {


public static void main(String[] args) {
String strPassword = new String ();
Scanner scanner = new Scanner (System.in);
final String RekodLaluanRahsia = “Pisang” ;
while (!strPassword.equals (RekodLaluanRahsia) ) {
System.out.print ( “ Please enter password : ” ) ;
strPassword = scanner.next();
System.out.print ( )
}
}
}

Sample Interaction:

Please enter password : Pisang

do-while Loop

Page 21
Created by Turbolearn AI

public class contoh43 {


public static void main(String[] args) {
int no = 1 ;
do {
System.out.println (no + “ X 3 = ” + no * 3) ;
no = no + 1;
} while ( n <= 12)
}
}

Output:

1 X 3 = 3
2 X 3 = 6
3 X 3 = 9
4 X 3 = 12
5 X 3 = 15
6 X 3 = 18
7 X 3 = 21
8 X 3 = 24
9 X 3 = 27
10 X 3 = 30
11 X 3 = 33
12 X 3 = 36

import java.util.Scanner;

public class contoh44 {


public static void main(String[] args) {
double no ;
double sum;
int counter = 1;
Scanner scanner = new scanner (System.in);
do {
no = scanner.nextDouble();
sum += no ;
counter = counter + 1;
} while ( counter <= 5)
System.out.println (“ The total is ” + sum) ;
}
}

Sample Interaction:

Page 22
Created by Turbolearn AI

6
7
9
3
6
The total is 31.0

import java.util.Scanner;

public class contoh45 {


public static void main(String[] args) {
string input ;
Scanner scanner = new scanner (System.in);
int no1;
int no2;
do {
no1 = scanner.nextInt();
no2 = scanner.nextInt();
System.out.println (“ Beza = ” + Math.abs (no1 –no2)) ;
System.out.println (“Type YA to continue”) ;
input = scanner.next();
} while ( input.equals(“YA”)) ;
}
}

Sample Interaction:

5
7
Beza = 2
Type YA to continue
YA
5
9
Type YA to continue
t

Increment and Decrement Operators


Commonly used as counters.
Increment Operator (++): Increases the value of a variable by a certain number.
Decrement Operator (--): Decreases the value of a variable by a certain
number.

Page 23
Created by Turbolearn AI

Expression Meaning Example

i += 1 i = i + 1
i += 2 i = i + 2
i += 3 i = i + 3

while (<Boolean condition>) {


<Repeating block of statements>
<Update value in condition>
}

Expression Meaning Example

i -= 1 i = i – 1
i -= 2 i = i – 2
i -= 3 i = i - 3

while (<Boolean condition>) {


<Repeating block of statements>
<Update value in condition>
}

Random Numbers and Boolean Control


Math.random() is a Java subprogram for generating random numbers.
It uses the system time as a seed to initiate the random number generation.
Example: (int) (Math.random()*10) + 1 (random number from 1 to 10)

Example Program: Generating 20 Random Dice Numbers

Page 24
Created by Turbolearn AI

import java.util.Scanner;

public class contoh46 {


public static void main(String[] args) {
int i ;
Scanner scanner = new Scanner (System.in);
Boolean flag = true;
do {
for (i = 1; i <=20 ; i++ ) {
System.out.println ((int) (Math.random() * 6) + 1) + “ ” )
}
System.out.println () ;
System.out.println (“ ---------------------------------”);
System.out.println (“ Type ya to continue, tidak to stop”);
if (Scanner.next().equals(“ya”)) {
flag = true;
else {
flag = false;
}
} while ( flag)
}
}

In the previous example:

A Boolean variable controls the repetition.


The user is asked whether to continue the program or not.

Example Program: Dice Number Frequency in 100 Throws

Page 25
Created by Turbolearn AI

import java.util.Scanner;

public class contoh47 {


public static void main(String[] args) {
int i ;
int diceNo;
int count1 =0, count2 =0, count3 =0, count4 =0, count5 =0, count6
Scanner scanner = new Scanner (System.in);
Boolean flag = true;
do {
for (i = 1; i <=20 ; i++ ) {
diceNo = (int) (Math.random() * 6 + 1) ;
System.out.println ( diceNo + “ ” ) ;
Switch (diceNo) {
case 1 : count1++ ; break;
case 2 : count2++ ; break;
case 3 : count3++ ; break;
case 4 : count4++ ; break;
case 5 : count5++ ; break;
case 6 : count6++ ; break;
}
System.out.println () ;
System.out.println (“ * Dice Number 1 = ” + count1 + “ % ”
System.out.println (“ * Dice Number 2 = ” + count2 + “ % ”
System.out.println (“ * Dice Number 3 = ” + count3 + “ % ”
System.out.println (“ * Dice Number 4 = ” + count4 + “ % ”
System.out.println (“ * Dice Number 5 = ” + count5 + “ % ”
System.out.println (“ * Dice Number 6 = ” + count6 + “ % ”
System.out.println () ;
System.out.println (“ ---------------------------------”);
System.out.println (“ Type ya to continue, tidak to stop”)
if (Scanner.next().equals(“ya”)) {
flag = true;
else {
flag = false;
}
} while ( flag)
}

Example Program: Dice Number Frequency Calculation

Page 26
Created by Turbolearn AI

import java.util.Scanner;
public class dadurambang {
public static void main (String [] args) {
int i ;
int diceNo;
int Kira1 =0, Kira2 =0, Kira3 =0, Kira4 =0, Kira5 =0, Kira6 =0;
double percen1 = 0 , percen2 = 0 , percen3 = 0 , percen4 = 0 , per
int jumlahKiraan = 0;
Scanner scanner = new Scanner (System.in);
Boolean flag = true;
do {
for (i = 1; i <=20 ; i++ ) {
diceNo = (int) (Math.random() * 6 + 1) ;
switch (diceNo) {
case 1 : Kira1++ ; break;
case 2 : Kira2++ ; break;
case 3 : Kira3++ ; break;
case 4 : Kira4++ ; break;
case 5 : Kira5++ ; break;
case 6 : Kira6++ ;
}
}
jumlahKiraan = Kira1 + Kira2 + Kira3 + Kira4 + Kira5 + Kira6;
percen1 = (double) Kira1/jumlahKiraan * 100;
percen2 = (double) Kira2/jumlahKiraan * 100;
percen3 = (double) Kira3/jumlahKiraan * 100;
percen4 = (double) Kira4/jumlahKiraan * 100;
percen5 = (double) Kira5/jumlahKiraan * 100;
percen6 = (double) Kira6/jumlahKiraan * 100;
System.out.println () ;
System.out.println (“ Dice Number 1 = ” + percen1 + “ % ”);
System.out.println (“ Dice Number 2 = ” + percen2 + “ % ”);
System.out.println (“ Dice Number 3 = ” + percen3 + “ % ”);
System.out.println (“ Dice Number 4 = ” + percen4 + “ % ”);
System.out.println (“ Dice Number 5 = ” + percen5 + “ % ”);
System.out.println (“ Dice Number 6 = ” + percen6 + “ % ”);
System.out.println () ;
System.out.println (“ ---------------------------------”);
System.out.println (“ Type ya to continue”);
if (!scanner.next().equals(“ya”)) {
flag = true;
}
} while ( flag)
}
}

‍Amalan Terbaik (Best Practices)


A technique or methodology proven through reliable experience or study
to achieve the desired results.

Page 27
Created by Turbolearn AI

Commitment to using all available knowledge and technology to ensure good


outcomes.
Good programming practices involve following common practices to produce
high-quality programs.

Inden Yang Konsisten (Consistent Indentation)


Consistent indentation makes the program code easy to read and understand.
Write indentation consistently from start to finish.

Jenis Data (Data Types)


Choose appropriate data types so the variable size is neither too small nor too
large, and conserve resources.

Pemboleh Ubah Yang Bermakna (Meaningful Variables)


Should not start with a number.
Example: 1cara (incorrect)
No spaces between words. Use underscores or concatenate words.
Example: cara_1 / cara1 (correct)
Should not be the same as keywords.
Example: integer, double (incorrect)
Case-sensitive.
Example: caraPertama is not the same as CaraPertama.
Meaningful and easy to understand. Avoid abbreviations.
Do not use reserved words.
Example: print, value (incorrect)

Komen (Comments)
Clearly written in two to three short lines to describe the function of the code
and fit the coding column space.

Jenis Ralat Dalam Atur Cara (Types of Errors in a Program)

Page 28
Created by Turbolearn AI

Ralat Algoritma (Algorithm Errors)


Ralat Sintaks (Syntax Errors)
Ralat Logik (Logic Errors)
Ralat Masa Larian (Runtime Errors)

Ralat Sintaks (Syntax Errors)


Grammar mistakes such as misspellings or incorrect punctuation. The use
of unrecognized objects or characters.

Ralat Logik (Logic Errors)


Occur when the program does not function as intended. Rarely or not
detected by the compiler. Only the programmer can detect them through
the output produced. The programmer needs to check all aspects of the
project output.

Ralat Masa Larian (Runtime Errors)


Errors encountered when a running program is interrupted due to certain
factors. Occurs if the programmer tries to perform impossible arithmetic
operations.

Mengesan, Mengenalpasti, Menterjemah Mesej Ralat Dan


Membaiki Ralat (Detecting, Identifying, Translating Error
Messages, and Fixing Errors)
Fix the identified errors.
Ensure the declared variable names are the same as the names to be recalled in
the program (check spelling & case).
Ensure all punctuations are typed completely.
Review the program in the declaration section.

Mengenalpasti Nilai Bagi Pemboleh Ubah Pada Bahagian


Tertentu Atur Cara (Identifying Variable Values in Specific

Page 29
Created by Turbolearn AI

Program Sections)

INPUT OUTPUT

Item | Variable | Value (Variable Data)

Menghasilkan Atur Cara Yang Mudah Dibaca Dengan


Menggunakan Gaya Yang Baik (Producing Easy-to-Read
Programs Using Good Style)
Use good programming style.

Gaya Atur Cara Yang Baik (Good Programming Style)


Comment on each function.
Use meaningful variable names.
Use comfortable indentation for reading.

Markers created by the programmer for each program built.


KOMEN (Comments) In Java, comment codes need to follow the set syntax to
avoid syntax errors.
PEMBOLEH UBAH
YANG BERMAKNA Variable names that have simple and meaningful spellings.
(Meaningful Variables)
Refers to how the program is written to facilitate reading.
Program reading will start with indentation, which means
INDEN (Indentation)
the text line is a few character positions into, from the left
or right margin of the page.
Comment
Description
Type

The compiler ignores all text starting with // until the last text of the
//
same line.
/* */ The compiler ignores all text within /* to */ even on different lines.
Documentation comments. The compiler ignores these comments just
/** */
like /* comments.

Page 30
Created by Turbolearn AI

This image provides a code sample calculating the area of a triangle.

Struktur Data (Data Structures)


A specific method for storing data in memory in an organized manner so
that it is easily accessed for processing into information according to user
needs.

Page 31
Created by Turbolearn AI

Data can be arranged in arrays and vectors, linked lists, stacks, and queues.
Use a systematic structure for variables and instructions when developing a
program.
Variables can be broken down into "small groups" called ARRAYS.
Computer instructions can also be broken down into small groups called
FUNCTIONS.
Related groups are called only when needed.

This diagram shows visual representations of Vectors, Matrices, Arrays, Data Frames,
and Lists.

Menerangkan Struktur Tatasusunan (Array) Satu Dimensi


(Describing a One-Dimensional Array Structure)
An array is a variable that allows a collection of several data values (elements)
at a time by storing each element in an indexed memory space.
A variable is a memory slot reserved for storing data.
Usually, simple variables only store one data value at a time.

dataType [ ] arrayName;
arrayName = new dataType [ arraySize];

Example:

int [ ] scoreList ;
scoreList = new int [ 6 ];

Page 32
Created by Turbolearn AI

Array declarations provide empty memory space.


Values need to be assigned through the assignment process.
After declaration, values are assigned by calling the array elements one by one.

scoreList [ 0 ] = 34 ;
scoreList [ 1 ] = 56 ;
scoreList [ 2 ] = 78 ;
scoreList [ 3 ] = 89 ;
scoreList [ 4 ] = 56 ;
scoreList [ 5 ] = 95 ;

Elements

34 56 78 89 56 95
Index
0 1 2 3 4 5

scoreList is the name of the array.

Alternate Declaration:

int scoreList [ ] = { 34,56,78,89,56,95};

Assignment is made during declaration.


Size in the array does not need to be included in the [ ] brackets.
The array size is determined automatically based on the number of data in the {
} brackets.
All data to be stored must be of the same type.

int score1 = 56, score2 = 78, score3 = 34;


int score [ ] = { 56,78,34};

Example Program:

Page 33
Created by Turbolearn AI

package perisianSaya;

public class MyClass {


public static void main (String [] args) {
String [] nameList = new String[4];
nameList [0] = “Adam”;
nameList [1] = “Alia”;
nameList [2] = “Wong”;
nameList [3] = “Devi”;
int [ ] ageList = {16,17,16,17};
double [] heightList = {182.1,172.5,173.2,175.0}
System.out.println (“ NAME\\tAge\\tHeight(cm)”);
for (int i = 0; i<4;i++) {
System.out.print (nameList [i] + “\\t”);
System.out.print (ageList [i] + “\\t”);
System.out.print (heightList [i] + “\\t”);
System.out.println () ;
}
}
}

Menggunakan Subatur Cara Dan Memahami Konsep


Menghantar Parameter Ke Subatur Cara Dan
Mengembalikan Data (Using Subprograms and
Understanding the Concept of Passing Parameters to
Subprograms and Returning Data)
Long computer code files are difficult to write, read, review, or update.
Therefore, related lines of computer code can be assembled into a module.
Thus, long computer code can be divided into modules.
Each module is shorter and specializes in a specific purpose.
These modules are called subprograms, structures for assembling computer
code.

Kelebihan Menggunakan Subatur Cara (Advantages of Using


Subprograms)

Page 34
Created by Turbolearn AI

Easy to reuse
Easy to test, debug, and repair
Allows tasks to be divided among different group members
Easier to handle computer projects
Complex projects become simple

static void subProgram01 ( )

Keyword Description

The static keyword is placed in front of the subprogram name.


Kata Kunci Khas Without this keyword, the subprogram cannot be used directly.
(Special Keyword) Without static, the subprogram requires object generation before
data is used.
Subprograms usually return results after the subprogram body
Jenis Data finishes processing data. The return data type in the header
Pulangan (Return depends on the type of data to be returned by the body. This
Data Type) includes int, double, string, and char. If there is no need to return
data, use the void keyword.
Nama Subatur
Given by the programmer. Must start with a letter (usually
Cara (Subprogram
lowercase). Can contain numbers but not symbols.
Name)
Bekas Parameter () symbols are used if the parameter is empty. The parameter
(Parameter name will be enclosed if the container accepts parameters.
Container) Example: (int quantity)
Subprograms are mandatory with the name main().
Can exist without other subprograms.
Contains the first line of statements that must be executed by the computer.
Contains the last line of statements that must be executed by the computer.
The subprogram header is rarely changed.
Statements in the main() subprogram will determine the nature of the program.
These statements should be written based on a tested algorithm.

Subprocedures and Modularity

Subprocedures

Page 35
Created by Turbolearn AI

A programmer can write other subprocedures.


Other subprocedures are similar to main(), but simpler.
Subprocedures can use other subprocedures to execute code in other
subprocedures.

The relationship between two subprocedures is that of a caller and a callee. The
caller invokes the callee's name within its body.

Typically, main() uses other subprocedures. When main() requires another


subprocedure for a specific process, control is transferred to that subprocedure, and
once completed, control returns to main().

Parameters and Arguments


Parameters (or arguments) are variables that allow a subprocedure to receive values
from the caller. This enables subprocedures to share variable values through
parameters.

Formal parameter: Refers to the parameter in the subprocedure.


Actual parameter: Refers to the variable in the calling subprocedure.

Parameters must be declared during the subprocedure definition and declared within
the parentheses of the parameter container. The declaration of parameters is similar
to that of variables. There is no limit to the number of parameters, and their sequence
depends on the programmer.

Here are some examples that demonstrate including and excluding parameters:

NO PARAMETERS CONTAINS PARAMETERS

static void subAtur01 () { } static void subAtur01 (int x ) { }


static void subAtur02 () { } static void subAtur02 ( int x ; double y) { }
static void subAtur03 () { } static void subAtur03 (int [ ] x ; string z) { }

Returning Control and Data


All subprocedures return control to the caller. Some subprocedures return not only
control but also data.

Page 36
Created by Turbolearn AI

For those that only return control, the keyword void is used.

If a subprocedure returns data, the last line in the subprocedure body has a
return statement and the data to be returned to the caller.

The subprocedure name does not have void as the return data type. Instead, the
data type corresponding to the data being returned is declared in the syntax.

Data can be returned as the result of an expression, the value in a variable, a


constant value, or the data value itself.

Each subprocedure can only return one type of data.

The name of a subprocedure that returns data is usually prefixed with get.

Examples: getNama, getAlamat, getTelefon.

DEFINITION OF SUBPROCEDURE EXPLANATION

static void subAturcara ( ) { } Does not return data. Only control is returned.
static int subAturcara ( ) { } Returns data of integer type.
static double subAturcara ( ) { } Returns data of double type.
static string subAturcara ( ) { } Returns data of string type.

Functions vs. Procedures


Functions

Data that has been processed needs to be stored in the caller's


body. This data will be used again by the caller, potentially by
main() or other subprocedures. Functions are used to request input,
but they do not display or store results.

Procedures

Procedures are used for display purposes only, such as messages to


the user. The results of the process are used only once in the
subprocedure and are not needed again.

Page 37
Created by Turbolearn AI

ASPECT OF
FUNCTION PROCEDURE
COMPARISON

Similarity Returns control Returns control


Returns data. Body ends with
Does not return data. Body does
Difference a return statement followed
not end with a return statement.
by the data returned.
Return Data int, double, char, string, array,
void
Type or Java object.
static dataType namaFungsi static void namaProsedur
Syntax Definition
([dataType namaParameter]){} ([dataType namaParameter]){}
static int cariJumlah (int x, static void cariJumlah (int x,
Example
int y){ int jawapan = x + y; int y) { int jawapan = x + y;
Definition
return jawapan; } System.out.print (jawapan); }
dataType pembolehUbah;
namaProsedur ([dataType
Syntax Call pembolehUbah = namaFungsi
namaParameter ] );
([dataType namaParameter ]);
int jumlah = cariJumlah
Example Call cariJumlah (5,8);
(5,8);

Java Math Functions

SYNTAX EXPLANATION

Math.sqrt (double n) Returns the square root of the value n.


Returns the nearest integer that is less than or equal to
Math.floor(double n)
the value n.
Returns the number n after rounding to the nearest
Math.round (double n)
integer.
Math.max (double m , double
Returns the larger number between m and n.
n)
Math.min (double m , double
Returns the smaller number between m and n.
n)

Modular Programming

Page 38
Created by Turbolearn AI

The program for the example above is a console application. Variables (name, grade,
marks) are declared as global variables, accessible by all subprocedures. The
procedures main(), getNama(), getMarkah(), setGred(), and paparInfo() can read and
write to the same set of variables. The main() procedure does not contain many
algorithm statements because those statements have been placed into
subprocedures. Calling subprocedures should follow a logical sequence.

Arrays as Parameters
Arrays are used as parameters for large amounts of data. Ensure that the
subprocedure can accept array parameters. Declaration is done in the subprocedure
header, and a for loop is needed to assign or access values of elements in the array.
Elements in an array can be changed directly from any subprocedure; therefore, the
array variable does not need to be returned to the caller.

Here is an example of passing an array in Java:

public class contoh63 {


public static void main (String[] args){
int[] senaraiNombor = {1,2,3,4,5,6,7,8,9,10};
paparSenarai(senaraiNombor);
}

static void paparSenarai (int[] senaraiNombor){


System.out.print ("Senarai nonbor dalam subatur cara : ");
for (int i=0;i<10;i++) {
System.out.print (senaraiNombor [i] + " , ");
}
}
}

In this example, an empty number array is declared in the main() procedure, and a
call is made to the setSenaraiRawak procedure. In setSenaraiRawak, the empty array is
assigned with random values generated by math.random. The values of the elements
are displayed in both the subprocedure and the main() procedure.

Software Development Lifecycle (SDLC)

Page 39
Created by Turbolearn AI

Also known as the Application Development Lifecycle, it's a term used in


systems and software engineering, information systems, and application
development. It describes the process of planning, designing, testing, and
implementing an application or software. It consists of a cycle of
sequential phases, making it an effective action plan for project teams.
SDLC helps track the status of project completion.

SDLC Models:

Waterfall
RAD (Rapid Application Development)
Iterative
Spiral
Agile
Hybrid (Combination Model)

SDLC Phases
The SDLC phases are commonly used as a model for application development,
mirroring the processes in SDLC. It is one of the earliest models, easy to understand
and manage, containing 5 phases where one phase needs to be completed before
moving to the next.

Analysis
Identifying program requirements and the reasons for building a program. Systematic
steps must be followed to solve problems, and it is important to clearly understand
the problem statement.

Using IPO analysis/chart.


Determine the desired solution.
Identify the formula to produce the output.
Identify the input for the formula.

An example of the IPO model:

Page 40
Created by Turbolearn AI

INPUT PROCESS OUTPUT

Hourly Rate, 1. Get hourly rate. 2. Get hours worked. 3. Calculate Staff
Hours Worked Staff Salary = hourly rate X hours worked Salary

Design
Created after IPO analysis, this phase looks at potential solutions and determines the
most effective and efficient one, building the best solution.

Algorithm: Initial step in problem-solving.


Pseudocode: Steps written in conversational language.
Flowchart: Graphical representation showing the steps to solve a problem and
the relationships between them.
LOGICAL DESIGN PHYSICAL DESIGN

Abstract Specifications Actual Physical Specifications


Description of what the system will do Description of how the system functions
Input, Output, Process and Security Controls Hardware, design and procedure

Pseudocode Example:

1. Start
2. Read hourly rate (kadarsj)
3. Read hours worked (bilJam)
4. Calculate staff salary = kadarsj * bilJam
5. Display staff salary
6. End

Implementation
The goal is to transform the design into a program that can be installed on hardware
and is ready to execute the solution, building and producing a system that can solve
the problems faced. Application development activities involve coding.

Coding: Requires a programming language like Java, Javascript, etc., to


transform program specifications into source code.

Compilation: The process of converting programming code into


executable code.

Page 41
Created by Turbolearn AI

Here is a sample Java program:

public class contohpg172 {


public static void main (String [] args){
int bilJam = 20;
double gajistaf, kadarsj;
kadarsj = 25.00;
gajistaf = kadarsj * bilJam;
System.out.println (" Gaji anda ialah RM " +gajistaf);
}
}

Testing
Ensuring all requirements are met, all coding functions as required, and all modules
can function when combined. It involves feedback from system users for correction
and improvement, engaging users fully in the development stage.

Detecting omissions.
Helping the project team document by detecting user errors.
Storing test results as proof of system development completion.

Code Review: Conducted to detect errors. The programmer will refer to


the displayed log to correct and remove detected errors.

TYPE WHO? WHEN?

Syntax Self Author During coding.


After completing the
Peer
module.
Project team led by a programming language
After both stages above.
expert
STAGES IN
TEST TYPES
SDLC

Self Ensuring each unit in the built system functions.


System Testing the system as a whole after testing individual units.
Integration Ensuring the system can function with existing systems.
This test is performed during integration testing by system users to
Acceptance
ensure it meets user requirements.

Page 42
Created by Turbolearn AI

ITEM ACTIVITY MARK (/) OR (X)

Syntax Errors Spelling text of variable names


Spelling text of comments
Use of unrecognized objects or characters
Declaration of data type for hours worked
Declaration of data type for staff salary
Declaration of data type for hourly rate
Runtime Errors Input calculation for hours
Input calculation for hourly rate
Logic Errors Check staff salary output.

API (Application Programming Interface)


A set of routines, protocols, and tools for building applications. An API
specifies how software components should interact.

A good API simplifies application development by providing building blocks, which


programmers can then assemble. Examples include the Google Maps API and the
Twitter API.

Documentation
A process of collecting data, gathering information, and summarizing,
such as running test reports, flowcharts, program code, and IPO charts.

These documents are important for system user reference, IT officers, and new staff
in each phase. Complete documentation of the project phase from the beginning in
each phase will be used as a reference for the next phase.

Page 43

You might also like