PENERBIT ILMU
BAKTI SDN. BHD.
Contents
PENERBITTopic 1 Introduction to Programming
ILMU
BAKTI SDN. BHD.1.1 Programming Language 1
1.2 Types of Programming Languages 1
1.3 Programming Paradigm 4
1.4 Language Translator 5
Summative Practice 1 9
Topic 2 Approach in Problem Solving
2.1 Problem Solving 10
2.2 Steps in Problem Solving 11
Summative Practice 2 16
Topic 3 Design a Solution
3.1 Algorithms 17
3.2 Control Structures 23
3.3 Desk Checking Algorithms Using Trace Tables 43
Summative Practice 3 46
Topic 4 Java Language
4.1 Introduction to Java 48
4.2 Basic Components of a Java Program 50
4.3 Input-Output in Java with Examples 55
4.4 Construct a Simple Java Program 60
Summative Practice 4 67
Topic 5 Identifiers, Data Types, Operators and Expressions
5.1 Identifiers (or Names) 69
5.2 Variables: Name, Type and Value 70
5.3 Constants (Final Variables) 72
5.4 Java Reserved Words 72
5.5 Java Data Types 73
5.6 Java Statements 75
5.7 Java Operators 76
5.8 Examples of Java Programs Using Primitive Data Types, Operators and Expressions 86
Summative Practice 5 88
Topic 6 Use of Control Structures
6.1 Control Structures in Programming Languages 89
6.2 Sequence Control Structure 90
6.3 Selection Control Structure 93
PENERBIT
ILMU6.4 Repetition Control Structure 101
BAKTI SDN. BHD.
6.5 Programming Errors 112
Summative Practice 6 115
Topic 7 Arrays
7.1 Introduction 117
7.2 Components of an Array 118
7.3 Declaring and Creating Arrays 119
7.4 Accessing Elements in an Array 121
7.5 One-Dimensional Arrays in Java 125
7.6 Common Operations with One-Dimensional Arrays 127
Summative Practice 7 132
Topic 8 Java Methods
8.1 Introduction to Java Methods 133
8.2 Types of Methods 134
8.3 Defining a Method 136
8.4 General Structure of Static User-defined Methods 137
8.5 Calling a Method 142
8.6 Static User-defined Methods to Perform Simple Computations 145
Summative Practice 8 151
Topic 9 Java Programs
9.1 Case Study #1 155
9.2 Case Study #2 158
Summative Practice 9 164
Semester Examination 165
Answers 170
1TOPICPENERBIT
ILMU
Introduction to ProgrammingBAKTI SDN. BHD.
Learning Outcomes
● Define programming language, programming paradigm and language
translators.
● Differentiate paradigms of programming language: procedural, object-
oriented and logic.
● Differentiate types of language translators: compiler, interpreter and
assembler.
1.1 Programming Language
1 A computer program is simply a set of specific instructions for a computer
to execute. To create a computer program, software developers use a
programming language to write the instructions:
A programming language is a set of words, abbreviations and symbols
that enables software developers to use a program development tool to
create a program or app.
2 Several hundred programming languages exist today. Each language has its
own rules or syntax for writing the instructions. Examples of programming
languages include Cobol, Pascal, Fortran, C++ and of course, Java.
1.2 Types of Programming Languages
Low-level Languages
1 A low-level language is a type of programming language that contains basic
instructions that the computer can understand and execute.
1
Introduction to Programming
2 It communicates directly with hardware. So, low-level languages may be used
to program fundamental tasks or functions of operating systems or device
drivers which require direct hardware access.
3 The two types of low-level languages are the machine language and assembly
language.
BAKTI SDN. BHD.
Topic 1 4 Machine language
(a) It is made up of a set of instructions and data in the form of binary
numbers, consisting of strings of 0’s or 1’s.
(b) Creating a program in machine language is a very daunting task. It is not
easy for programmers to write code in machine instructions.
(c) A machine language is not portable as each computer has its machine
instructions. So, a program written in one computer will not work in
another computer.
Mid Semester Test 1 5 Assembly language
(a) Assembly language uses some abbreviated English words, such as MOV,
ADD and SUB.
(b) Assembly language instructions are therefore easier to write and
understand compared to machine language instructions that use binary
numbers.
(c) However, assembly code must be translated to machine language before
the computer can run the program. A tool called an assembler is used to
do this.
(c) However, assemblers are processor-dependent, and each type of computer
can be programmed in its own assembly language.
ILMU
6 Table 1.1 summarises the differences between machine language and assembly
lannguage.
Table 1.1 Comparing machine language and assembly language
Machine Language Assembly Language
AnswersPENERBIT Machine language is made up of Assembly language contains simple
binary digits, i.e. 0’s’ amd 1’s English commands.
It cannot be easily understood by The code is easier to read, write and
humans. maintain.
It can be directly executed by the
computer. Assembly code must be converted
into machine code before the
Machine language is at the computer can execute it.
lowest level in the hierarchy of
programming languages. It is Assembly language comes above
the only language which can be machine language. Its commands
understood by the computer. are less structurally similar to CPU
instructions.
It is a first-generation programming It is a second-generation
language. programming language.
2
Introduction to Programming
High-level Languages
1 High-level languages allow programmers to write computer programs that are
independent of a particular type of computer.
2 These programming languages are considered ‘high level’ because they are
much closer to human language and less complex than machine code.
PENERBIT
ILMU 3 Advantages of a high-level language Topic 1
BAKTI SDN. BHD. (a) A high-level language is easy to read, write, and maintain as it is written
using English-like words. It is more programmer-friendly than machine
code.
(b) High-level languages are portable and can run on different kinds of
computers with little or no modifications.
4 Table 1.2 highlights the differences between low-level languages and high-
level languages.
Table 1.2 Comparing machine language and assembly language
Low-level Language High-level Language
It is a machine-friendly language. It is a programmer-friendly language Mid Semester Test 1
The computer can easily understand as the code is human readable.
the instructions,
It it is a non-portable language. It is a portable language that can run
It is machine-dependent. on any platform.
It is complex to debug and maintain.
An assembler is needed to translate It is simpler to debug and maintain.
assembly code into machine code.
A compiler or interpreter is needed
It is memory efficient. to translate the instructions into
machine code.
It is less memory efficient.
5 Figure 1.1 summarises the different categories and levels of programming Answers
languages.
OO and Visual Language
FORTRAN C Pascal High-level
languages
Hight-Level Language
Assembly Language Low-level
(symbolic labels) languages
Machine Language (0's and 1's)
Hardware (switches and gates)
Figure 1.1 Categories and levels of programming languages
3
Topic 1 Introduction to Programming BAKTI SDN. BHD.
Mid Semester Test 1 1.3 Programming ParadigmILMU
AnswersPENERBIT 1 Each of the different programming languages can be classified into different
types or paradigms:
Programming paradigms are the different styles or ways by which a
computer language looks at the problem to be solved.
2 A programming paradigm can also be defined as a fundamental style of
building the structure and elements of a program. Three popular programming
paradigms are:
(a) Procedural programming
(b) Object-oriented programming
(c) Logic programming
Procedural Programming
1 A procedural language uses a linear or top-down approach. Its design focuses
on procedures and data. A procedure is simply a series of instructions to be
carried out by the computer step by step:
Procedural programming is a computer programming paradigm that
organises program code into procedures to perform computations.
2 The programmer identifies the major function of a program to be executed by
the main module, and the main module is then divided into smaller modules.
3 The program consists of a systematic sequence of statements, functions and
commands to complete a computational task. For example, the command ADD
stands for addition, or PRINT means to print. Many procedural languages also
use arithmetic operators, such as the asterisk (*) for multiplication and the plus
sign (+) for addition.
4 In short, a procedural program directly instructs a computer on how
to complete a task that you want it to do in logical steps. Examples of
programming languages that support this paradigm are C, COBOL, MATLAB
and Python.
Object-Oriented Programming
1 Object-oriented programming, also known as OOP, follows a bottom-up
approach. Its design focuses on objects and methods:
Object-Oriented Programming (OOP) is a programming language
paradigm that will implement the objects in a program.
2 An object is an item that can contain both data and the procedures that read
or manipulate that data. An object may represent a real person, place, event or
transaction.
3 The major benefit of OOP is that it allows programmers to reuse and modify
existing objects. For example, the system developer may have created an
Employee object, but the code can be structured as a resuable component
4
PENERBIT Introduction to Programming Topic 1
ILMU
BAKTI SDN. BHD. that is available for use by any other existing or future program. Thus, system Mid Semester Test 1
developers can reuse an existing object repeatedly. For instance, the Payroll
program and the Health Benefits program would both use an Employee Answers
object.
4 An OOPL (object-oriented programming language) is a programming language
that supports the OOP paradigm. Examples include Java, C++ and the latest
version of of Visual Basic.
Logic Programming
1 Logic programming does not follow an explicit algorithm. Its design focuses on
facts and rules:
Logic programming is a computer programming paradigm in which
program statements express facts and rules about problems within a
system of formal logic.
2 Rules are written in the form of logical clauses with a head and a body; for
instance, "H is true if B1, B2, and B3 are true". While “H is true” is called the
head of the rule, “if B1, B2, and B3 are true" is called the body.
3 Facts are expressed similar to rules, but without a body; for instance, "H is
true" is a fact.
4 Major logic programming language families include Prolog, answer set
programming (ASP) and Datalog.
1.4 Language Translator
1 A computer program written in any programming language that is human-
readable is called the source code.
2 However, the computer can only understand and execute machine language.
Therefore, source code has to to converted into a machine language code that
the central processing unit (CPU) understands:
A translator is a computer program that translates programming source
code into machine language.
3 Three main types of translators are used to convert different programming
languages into the equivalent machine code: assembler, compiler and
interpreter.
Assembler
1 Assembly language is a low-level programming language that uses symbolic
instructions code consisting of meaningful abbreviations. For example, A is
used for addition, C for compare, L for Load and M for multiply.
5
Introduction to Programming
2 Assembly code must be converted to machine language before the computer
can execute or run the program.
3 A tool called an assembler will be used to convert the assembly language
source program into machine language to create an executable program.
However, assemblers are processor-dependent and each kind of computer may
be programmed in its own assembly language.
Compiler
1 A compiler is a computer program that converts an entire high-level source
code into machine language. The machine language version that results from
compiling the procedural language is called the object program or object code.
2 The compiler stores the object program on storage media for execution later.
Figure 1.2 summarises how a compiler works.
Topic 1 BAKTI SDN. BHD.
Source Compiler Object Results
Program Program
Mid Semester Test 1 Program Data
Listing
Figure 1.2 A compiler converts the whole source program into a machine language object program.ILMU
AnswersPENERBIT 3 While it is compiling the source program into the object program, the compiler
checks the source program for errors. The compiler then generates a program
listing which contains information about the compilation. It helps the software
developer to make necessary changes to the source code to correct the errors
detected.
4 Examples of programming languages that use compilers are C, C++ and Java.
Interpreter
1 An interpreter translates high-level source code into machine code and
executes it line by line. The interpreter reads an instruction, converts it to
one or more machine language instructions, and then executes those machine
language instructions. It does all this before moving to the next instruction in
the program.
2 Each time the source program runs, the interpreter translates and executes it,
instruction by instruction. Unlike a compiler, an interpreter does not produce an
object program.
6
Summative Practice 1
1 Give the definition for each of the following terms:
(a) Programming language
(b) Programming paradigm
(c) Translator
PENERBIT
ILMU 2 Programmers can use high-level language to write a computer program. Topic 1
BAKTI SDN. BHD. (a) Explain what is meant by the term ‘high-level language’.
(b) Give one advantage of writing code in a high-level language.
(c) Give two differences between low-level language and high-level language.
3 Computer programming is a process of designing and building an executable computer program to
accomplish a specific computing result or to perform a specific task.
(a) Identify two types of programming paradigm based on the given statements.
Statement Paradigm
(i) Doctors use an information system to help them diagnose illnesses. This Mid Semester Test 1
system has been programmed with facts and rules about the symptoms of
illnesses.
(ii) This programming style is used to develop maps and identify a standardised
shortest route to travel, which is to simplify the traveling process. It contains
both data as well as functions.
(b) Explain what is a procedural paradigm.
(c) Give one example of a programming language that supports the procedural paradigm.
4 Give the name of the translator B that is used to translate code A to code C.
IMM R5, 0x1 B 10010011
STORE R0, R2 10101000
ADD R0, R0, 10011010
00011111
Answers
A C
5 Study the diagram below.
Statement 1 Machine Language Execute Statement 1 Machine Language Execute
Statement 2 Machine Language Execute Statement 2 Later
Statement 3 Machine Language Execute Statement 3
Statement 4 Machine Language Execute Statement 4
Translate into Save it in an
object file
Translate into Immediately
Translator X Translator Y
(a) Differentiate between two translators, X and Y, in the diagram.
(b) Give one example of a programming language that uses translator Y?
9
PENERBITJava Language 4TOPIC
ILMU
BAKTI SDN. BHD. Learning Outcomes
● Describe Object-oriented Programming: class, object, method.
● Describe the components of a Java program: comments, class, main
method, body.
● Use output and input statements including output string.
● Construct a simple program to perform simple computations.
4.1 Introduction to Java
1 Java is a popular general-purpose programming language. It is a high-level
language that makes writing, compiling and debugging programs very easy.
2 It is used to develop desktop, mobile and web applications, games, database
processing, and much, much more.
3 Java is a class-based, object-oriented language. That means programs are
organised as a collection of objects, with each object representing an instance
of a class. This allows programmers and developers to create modular programs
with reusable code.
Object-Oriented Programming (OOP) Recap
1 Object-Oriented programming (OOP) refers to a type of programming in which Remember, an object is
programmers define the data type of a data structure and the type of operations an item that contains both
that can be applied to the data structure. data and procedures that
read and manipulate that
2 An object-based application in Java is based on declaring classes, creating data.
objects from them and interacting between these objects.
48
PENERBIT 3 The four main concepts of object-oriented programming are: Java Language Topic 4
ILMU (a) Inheritance
BAKTI SDN. BHD. • When one object acquires all the properties and behaviours of a parent 49Mid Semester Test 1
object, this is known as inheritance. Answers
• In Java, the properties of one class (parent class) can be inherited by
another (subclass or child class). This provides code reusability. It is used
to achieve runtime polymorphism.
(b) Polymorphism
• If one task can be performed in different ways, that is known as
polymorphism. For example, the same person can have different roles as
a father, husband and an employee.
• In Java, we use method overloading and method overriding to achieve
polymorphism.
• Runtime polymorphism—A call to an overriden method is resolved at
runtime. In method overriding, a subclass (child class) has the same
method as the parent class.
• Static polymorphism—A call to an overloaded method is resolved at
compile time. In method overloading, two methods have the same name
but differ in parameters.
(c) Abstraction
• Hiding internal details and showing functionality is known as abstraction.
For example, we make phone calls all the time on our mobile phones, but
we do not know what happens internally inside the phone when we make
a call.
• In Java, we use abstract class and interface to achieve abstraction. An
abstract class is a restricted class that cannot be used to create objects, but
can only be inherited from another class.
(d) Encapsulation
• Binding (or wrapping) code and data together into a single unit is known
as encapsulation. For example, in medicine, encapsulation refers to the
technique of enclosing drugs inside a shell known as a capsule.
• In Java, data members and methods are enclosed in a similar way in a
class. All the data members are private.
4 Objects in Java
(a) Any entity that has state and behaviour is known as an object. For
example, a chair, pen, table, keyboard, bike, etc. It can be physical or
logical.
(b) In Java, an object can be defined as an instance of a class.
An object contains an address and takes up some space in memory.
(c) Objects can communicate without knowing the details of each other's data
or code. The only information needed is the type of message accepted and
the type of response returned by the objects.
5 Classes in Java
(a) A collection of objects is called a class. It is a logical entity.
(b) A class can also be defined as a blueprint from which you can create an
individual object.
(c) A class does not consume any space.
Java Language 6 Methods in Java
50 (a) A method refers to the sequence of instructions that performs some task or
computation.
(b) Every Java program must have a method named main.
(c) The program execution starts at the main method.
4.2 Basic Components of a Java ProgramBAKTI SDN. BHD.
1 Figure 4.1 shows the basic structure of a Java program. This is the way we
write a Java program, or its general format.
Topic 4 Java keyword class name main method
class Class HelloWorld
declaration
method public static void main(String[] args)
Mid Semester Test 1 body of // Prints “Hello, World” in the terminal window
method
System.out.print(“Hello, World”);
statement comment
ILMU
Figure 4.1 Basic structure of a Java program
AnswersPENERBIT
2 Basically, a Java program consists of four main components:
(a) Comments
(b) Class declaration
(c) Method
(d) Body of method
(1) Comments
1 Java comments are the statements in a program that are not executed by the
compiler and interpreter.
2 Why do we use comments in a code?
(a) Comments are used to make the program more readable by adding the
explanatory details of the code.
(b) It makes it easy to maintain the code and to detect errors.
(c) The comments can be used to provide information or explanation about
any variable, method, class, or statement.
(d) It can also be used to prevent the execution of program code while testing
the alternative code.
3 There are two types of comments in Java: Java Language
(a) Single line comment: The single-line comment consists of only one
51
line of code. It is the widely used and easiest way of commenting on the
statements.
Syntax:
Single line comments starts with two forward slashes (//).
Any text after // is not executed by Java.
// This is a single line comment
(b) Java multiline comment: A multiline comment consists of multiple lines
of code.
Syntax:
Multiline comments are placed between /* and */.
Any text between /* and */ is not executed by Java.
/* This
is a
multiline
comment
*/
Example: Comments in a Java program
/*
This program demonstrates
parts of a Java program
*/
class FirstProgram
{
public static void main(String[] args)
{
// Display message
System.out.println("Hello World!");
}
}
PENERBIT Topic 4
ILMU
BAKTI SDN. BHD. Mid Semester Test 1
(2) Class Declaration Answers
1 A class is created using the keyword class. In the above example, we declared
a class named FirstProgram:
class FirstProgram class declaration
{ body of class
...
}
• FirstProgram is the name of the Java class.
• Note that the file must be named to the class name with the .java extension.
That means that this program must be saved as FirstProgram.java.
• The second line of the program consists of the left brace ( { ), which is
matched with the second right brace ( } ), the very last brace.
Java Language • These braces together mark the beginning and end of (the body of) the class
FirstProgram.
Smart Tips!
(3) The main Method
System is a built-in
Java class found in the 1 In our example above, the FirstProgram class calls the main method:
java.lang package. It
contains many useful class FirstProgramBAKTI SDN. BHD. signature of
members, such as { main method
out (short for output) public static void main(String[] args)
which is an instance of { body of main
PrintStream type. We System.out.println(“Hello World!); method
will learn more about this }
in the next section. }
Topic 4 2 In Java, every application must contain a main method whose signature is:
• public — an access specifier that means we can access the method from
Mid Semester Test 1
every where;
• static — an access modifier that means we can call this method directly using
a class name without creating an object of it;
• void — the return type;
• main — gives the method name where string[] args means that it
accepts only string type of arguments.
3 In the example given above, the line:
System.out.println("Hello World!");
inside the body of the main method is a statement which prints the characters
between quotes to the console.
ILMU
(4) Body of the Method main( )
The body of the method main is enclosed within braces { }. It represents a set of
executable statements which may include:
• Creating objects
• Declaring variables
• Statements and expressions
AnswersPENERBIT
Creating Objects
1 A class provides the blueprint for objects. So basically, an object is created
from a class. In Java, the new keyword is used to create new objects.
2 There are three steps to creating an object from a class:
1 Declaration
In a declaration, we specify the class name and object name.
Example: MyClass myObject = new MyClass();
52
Java Language
2 Instantiation
The new keyword is used to create an object (or an instance of the
class). Memory is allocated for the new object.
3 Initialisation
The new keyword is followed by a call to a constructor. A constructor
is a special method that is used to initialise the new object, that is,
specify an initial value to assign to it.
PENERBIT
ILMU 3 We can create an object either from a built-in Java class, or from a user-definedSmart Tips! Topic 4
BAKTI SDN. BHD.class:
The Java platform comes Mid Semester Test 1
(a) Object from the Scanner class to read input data entered by the user. with a large class library
For example, to create the object sc from the class java.util.Scanner, that developers can use
in their own applications.
here is the code: The Scanner class is
used to get user input and
Java.util.Scanner sc = new java.utill.Scanner(System.in); it is found in the java.util
package.
(b) Object from class created by the programmer to call a user-defined
method.
Syntax:
ClassName objectName = new ClassName();
4 For example, to create the object obj from the class HelloWorld, the code is:
HelloWorld obj = New HelloWorld();
5 Objects will be used to call Java methods. This will be discussed later in Topic
8 on Java methods.
Declaring Variables
1 To use any variable in a Java program, you must first declare it.
2 Variable declarations consist of a type and a variable name. Here are some Answers
examples:
int myAge;
String myName;
boolean isTired;
3 Variable definitions can go anywhere in a method definition (that is, anywhere
a regular Java statement can go), although they are usually declared at the
beginning of the definition before they are used.
53
Java Language
Topic 4 Example: Variable definition BAKTI SDN. BHD.
Mid Semester Test 1 ILMU public static void main (String [args]) {
int count; //declare variable
AnswersPENERBIT String title; //declare variable
boolean isAsleep; //declare variable
…
…}
4 You can string together variable names of the same type like this:
int x, y, z; //declare variables
String firstName, LastName; //declare variables
5 You can also give each variable an initial value when you declare it:
int, mySize, numShoes = 28; //declare & initialize variable
String myName = “Laura”; //declare & initialize variable
boolean isTired = true; //declare & initialize variable
int a = 4, b = 5, c = 6; //declare & initialize variables
(Variables will be discussed in detail in Topic 5.)
Statements and Expressions
1 A statement is the simplest thing you can do in Java; a statement forms a
single Java operation. All the following are simple Java statements:
int i = 1;
System.out.println(“This car is a “+ colour + “ “ + make);
m.engineState = true;
2 Statements sometimes return values—for example, when you add two numbers
together or test to see whether one value is equal to another. These kinds of
statements are called expressions. Here is an example:
sum = a + b;
(We will discuss this later in subtopic 5.6.)
54
Quick Check 4.1 Java Language
1 Describe the four main principles of Object Oriented Programming (OOP). 55
2 List four components of a Java program.
3 Give an example for each way to write comments below:
(a) Single-line comments
(b) Multi-line comments
4 Give one example of a class declaration in a Java program.
5 Write the syntax of the declaration for the main method in a Java program.
6 List three components that may be included in the body of method main().
PENERBIT Topic 4
ILMU
BAKTI SDN. BHD.4.3 Input-Output in Java with Examples Mid Semester Test 1
1 The Java I/O (Input and Output) package is used to process input and output
operations. Java uses the concept of streams to make I/O operations fast.
The java.io package contains all the classes required for input and output
operations.
Inputstream Outputstream
READ
Source JAVA Destination
APPLICATION
WRITE
Figure 4.2 Various streams in the Java I/O package greatly simplify I/O operations
2 A stream is a sequence of data. In Java, a stream is composed of bytes. It is
called a stream because it is like a stream of water that flows continuously.
3 Java simplifies I/O operations by providing: Answers
(a) System.in: The standard input stream that typically reads input entered by
the user.
(b) System.out: The standard output stream that typically displays
information to the user.
Input Statements
1 Java provides different ways to get input from the user. For example, you can
get input from the user using an object of the Scanner class.
2 In order to use the object of Scanner, we need to import the java.util.
Scanner package:
import java.util.Scanner; //Import the Scanner class
Java Language 3 Then, we need to create an object of the Scanner class. We can then use the
object to accept an input from the user.
Smart Tips!
// create an object of Scanner
The object that will Scanner input = new Scanner(System.in);
be used in an input
statement must be the // take input from the user
same as the object that int number;
has been created. All number = input.nextInt();
object names must follow
the rules for creating 4 Alternatively, you can declare a variable and take input from the user at the
identifiers. same time by using the statement:
int number = input.nextInt();
BAKTI SDN. BHD.
Topic 4 Example
In this example, we use the nextLine() method, which is used to read strings:
Mid Semester Test 1 Smart Tips! import java.util.Scanner; // Import the Scanner class
class MyClass {
You can use any suitable public static void main(String[] args) {
name to create a Scanner // Create a Scanner object named input
object such as input, Scanner input = new Scanner(System.in);
sc, myObj, read, and so System.out.println("Enter username");
on. (Refer to Topic 5 on //Read user input
Identifiers.) //Input is the variable name for scanner object
String userName = input.next();
// Output user input
System.out.println("Username is: " + userName);
}
}
ILMU
Input Types
Table 4.1 shows the methods used for taking input of different data types.
AnswersPENERBIT
Table 4.1 Methods of obtaining input of different types
Method Description
nextInt() Reads a int value from the user
nextFloat() Reads a float value from the user
nextDouble() Reads a double value from the user
nextBoolean() Reads a boolean value from the user
next() Reads a String (single word) value from the user
nextLine()
Reads a String (entire input string including white
spaces) value from the user
next().charAt(0) Reads char value at the specified index 0 in character
sequence
56
Example Java Language
In this example, we use different methods to read data of various types.
Smart Tips!
import java.util.Scanner;
class MyClass { If you enter a wrong input
public static void main(String[] args) { (e.g. text in a numerical
Scanner myObj = new Scanner(System.in); input), you will get an
System.out.println("Enter name, age and salary:"); exception/error message
// String input (such as "InputMismatch
String name = myObj.nextLine(); Exception").
// Numerical input
int age = myObj.nextInt();
double salary = myObj.nextDouble();
// Output user input
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
}
}
PENERBIT Topic 4
ILMU
BAKTI SDN. BHD. Mid Semester Test 1
Output Statements
1 ‘Writing Console Output’ in Java refers to writing the output of a Java program
to the console or any particular file.
2 The methods used for streaming output are defined in the PrintStream class.
The methods used for writing console output are print() and println().
3 For displaying any particular string, the string to be displayed on screen is
written within double quotation marks (i.e. “ ”):
System.out.println(“Hello!! How are you?”); Answers
4 In addition, if you want to display the value of any particular variable used in
the program, then you have to append the variable name along with the string
with a plus (+) symbol.
System.out.println(“Name you have entered is ” + name);
String to be displayed Name of a variable
5 The basic differences between print() and println() methods are
summarised in Table 4.2.
Table 4.2 Differences between print() and println() methods
print() println()
Method displays the string in the same Method outputs a newline character
line after its execution
Method is used for directing output to Method is used for directing output to
the console only not only console but other sources
57
Summative Practice 4
1 Java Language is considered an object-oriented language because it is based on the concept of objects and
classes.
Identify the characteristic of Object-oriented Programming based on the following description.
PENERBIT
ILMUDescription Characteristic of
BAKTI SDN. BHD. Object-oriented Programming
A mechanism in which one object acquires all (i)
the properties and behaviours of a parent object
This feature protects data and methods from (ii) Topic 4
outside access or misuse
Concept by which we can perform a single (iii)
action in different ways
Process of hiding the implementation details and (iv)
showing only functionality to the user
2 Consider the Java program below and answer the questions: Mid Semester Test 1
class JavaExample {
public static void main(String[] args) {
int number = 10, p = 3;
double result = Math.pow(number, p);
System.out.println(number+"^"+p+" = "+result);
}
}
(a) Write a single line comment to explain Java program above.
(b) State a class name in the program.
(c) Identify two identifiers in the program.
(d) State an output statement in the program.
3 Study the Java program below and answer following questions: Answers
import java.util.Scanner;
class CourierCharge
{
public static void main(String[] args)
{
double weight, courierCharge;
Scanner scan = new Scanner(System.in);
System.out.print("Enter the Weight of Parcel (in Kilogram): ");
weight = scan.nextDouble();
if(weight<=5)
{
courierCharge = 6;
}
67
Topic 4 Java Language BAKTI SDN. BHD.
else
Mid Semester Test 1 {ILMU
weight = weight - 5;
AnswersPENERBIT courierCharge = (double)(6 + (weight*1.2));
}
System.out.println("\nThe Courier Charge is " + courierCharge);
}
}
(a) Identify the object from the class Scanner that accepts input data.
(b) State the statement declaring variables in the program.
(c) State an input statement in the program.
4 Write a simple Java program for each problem.
(a) Write a program in Java that converts the given weight (by user at runtime) from kilograms to grams.
(b) Take two int values from the user and print the greatest among them.
(c) A shop will give a discount of 10% if the cost of the quantity purchased is more than RM1000. Ask the
user for the quantity purchased supposing that one unit will cost RM100. Calculate and print total cost
for the user.
(d) A company decides to give a bonus of 5% to an employee whose length of service is more than 5 years.
Ask users for their salary and length of service and print the net bonus amount.
(e) A program reads the length and breadth of 6 rectangles from the user and checks if each is a square or
not.
68
ArraysPENERBIT7TOPIC
ILMU
BAKTI SDN. BHD.
Learning Outcomes
● Explain an array and its components
● Declare array reference variables and create arrays
● Access array elements – initialise, input, process and output.
● Construct programs that perform one-dimensional array operations for
problems involving linear search.
● Construct programs that perform one-dimensional array operations for
problems involving frequency and total.
7.1 Introduction
1 Java provides a data structure called the array that lets us store a fixed-sized
collection of data of the same type. We can think of an array as a collection of
variables of the same type:
An array is a data structure or container that stores the same type of
elements in a sequential format.
2 For instance, an array of type int is a collection of variables of the type int. The
variables in the array are ordered and each variable is referenced by its index.
3 As an example, let us say we want to store the test scores of a student for five
subjects. We can use the following statements:
int mark1 = 78;
int mark2 = 84;
int mark3 = 63;
int mark4 = 91;
int mark5 = 75;
117
Arrays Alternatively, we can store all five variables in a single index-based variable: an
array named marks.
118
marks[0] = 78;
marks[1] = 84;
marks[2] = 63;
marks[3] = 91;
marks[4] = 75;
4 We refer to each value or element in the array by its index. The first index is 0.
In the array marks, the first value is at the 0th index and the last value is at the 4th
index.
BAKTI SDN. BHD.
Topic 7 5 Figure 7.1 depicts how the above array marks will be represented in computer
memory.
[0] [1] [2] [3] [4] index
78 84 63 91 75
marks
int marks = new int[5];
Figure 7.1 Representation of the array marks in computer memory
Mid Semester Test 1 6 Characteristics of an array:
(a) All the elements have the same data type but they may have dissimilar
values.
(b) The whole array is saved contiguously in memory, meaning there is no
space between the elements.
ILMU
7.2 Components of an Array
AnswersPENERBIT
1 An array consists of four components:
(a) Data type
This is the data type of all the array elements. Valid data types include int,
float, etc.
(b) Name
This is a valid identifier.
(c) Size
This is the range of indices of the array elements.
(d) Index
The indices must be integers within the specified range. The smallest index
is referred to as the lower bound and the largest index is the upper bound.
Array Syntax
1 An array allows you to declare a collection of related variables (of the same type)
at once. Each value in an array is known as an element.
2 The programmer must specify the length of the array (the number of array
elements). Once the array is created, its length cannot be changed.
PENERBIT 3 For example, if we want to store the names of 100 people, then we can create an Arrays Topic 7
ILMU array of type string that can store 100 names.
BAKTI SDN. BHD. 119Mid Semester Test 1
String[] array = new String[100];
Answers
The number of values in the Java array is fixed. This means, the above array
cannot store more than 100 elements.
7.3 Declaring and Creating Arrays
To create an array in Java, you must do the following:
1 Declare a variable to hold the array.
2 Create a new array object and assign it to the array variable.
3 Store information in that array.
Declaring Arrays
1 We declare an array by providing a data type and a name.
Syntax:
dataType[] arrayName;
• dataType can be any primitive data type like int, char, double, byte, etc. or a
Java object.
• arrayName is an identifier.
2 For example, to create an array named data to hold values of type double, we
use
double[] data;
3 Here are a few more examples of array variable declarations:
int[] list;
String[] fruits;
float[] prices;
Creating Array Objects
1 The second step is to create an array object and assign it to that variable. There
are two ways to do this:
(a) Using new
(b) Directly initialising the contents of the array
2 Using new operator
After declaring an array variable, we can use the new operator to create a new
instance of the array
Syntax:
Arrayname = new datatype[SIZE];
• Arrayname is the name of the array being instantiated.
• datatype is the type of elements the array is going to store.
• SIZE is the number of elements that will be stored in the array.
Arrays Examples:
Smart Tips! list = new int[10];
fruits = new String[5];
Array indices always start prices = new float[4];
from 0. That is, the first
element of an array is at 3 Directly initialising the contents of that array
index 0. You can also declare an array variable and create an array object in a single
If the size of an array is n,
then the last element of statement, as follows:
the array will be at index
(n – 1). Syntax:
datatype arrayname = new datatype[SIZE];
Examples:
int list = new int[10];
String fruits = new Strinhg[5];
float prices = new float[4];
Topic 7 BAKTI SDN. BHD.
Store Array Elements (Initializers)
1 We can initialise arrays in Java in two different ways:
(a) By using index
(b) While declaring the array
Mid Semester Test 1 2 Initialise using index
Once an array is created, we can assign a value to any specific element using its
index. Unassigned elements automatically take the default value of the array’s
data type. In the case of the integer data type, it is 0.
Example
ILMU
// declare an array
AnswersPENERBIT int[] age = new int[5]
// initialize array
age[0] = 12; // assigned 12 at index 0
age[2] = 15; // assigned 15 at index 2
age[4] = 17; // assigned 17 at index 4
The resulting array is represented in Figure 7.2.
age[0] age[1] age[2] age[3] age[4]
12 0 15 0 17
Figure 7.2 Representation of the array age in computer memory
3 Initialise during declaration
We can also initialise the whole array while declaring it by using curly brackets
{ }. Strings must be in quotes, whereas int, float, etc. do not require that:
int[] myArray = {1, 2, 3, 4, 5}; // For integer type
String[] myArray1 = {“A”, “B”, “C”, “D”} // For string type
120
PENERBIT 7.4 Accessing Elements in an Array Arrays Topic 7
ILMU
BAKTI SDN. BHD. 1 Each element in the array can be accessed directly via its index. The index begins 121Mid Semester Test 1
with 0 and ends at [(total array size) – 1].
Answers
2 We can access every element of an array. There are two ways to do this: by using
index numbers, or by using the for loop.
Using Index Numbers
1 Using index numbers, we can implement one operation at a time.
2 You can accessed an array element with the array name followed by a subscript
or index enclosed within square brackets.
Syntax:
// access array elements
array[index]
3 For example, the following code stores the value 30 in the fifth element of the
array:
marks[4] = 30;
Example 1 Access array elements using index numbers
class Main {
public static void main(String[] args) {
// create an array
int[] age = {12, 4, 5, 2, 5};
// access each array elements
System.out.println("Accessing Elements of Array:");
System.out.println("First Element: " + age[0]);
System.out.println("Second Element: " + age[1]);
System.out.println("Third Element: " + age[2]);
System.out.println("Fourth Element: " + age[3]);
System.out.println("Fifth Element: " + age[4]);
}
}
Output:
Accessing Elements of Array:
First Element: 12
Second Element: 4
Third Element: 5
Fourth Element: 2
Fifth Element: 5
Using for Loop
1 We can also use the for loop to access all the elements of the array all at once.
Arrays 2 We will need to know the array’s length first. This can be done by using the Java
built-in property length.
Smart Tips!
(a) If we start the for loop with counter = 0, then the total iteration will be the
Another way of writing “ array’s length – 1.
i = i + 1“ is “i++”.
(b) If we start the for loop from counter = 1, then the total iteration will be the
length of the array.
Syntax:
// access the elements of the specified array
for (int i = 0; i < arr.length; i++)
System.out.println(“Element at index ” + i + “ : ” + arr[i];
Example 1 Access array elements using for loops
Topic 7 BAKTI SDN. BHD.
class ArrayDemo {
Mid Semester Test 1 ILMU public static void main (String[] args) {
AnswersPENERBIT // declaring and initializing an array
String strArray[] = {“Visual Basic”, “Java”,
“C++”, “C”, “Python”};
// using for loop
for (int i = 0; i < strArray.length; i++) {
System.out.println(strArray[i]);
}
}
}
Output:
Visual Basic
Java
C++
C
Python
Example 2 Access array elements using for loop to
enter data and print its content
import java.util.Scanner; //program uses Scanner class
class ArrayElements
{
public static void main(String[] args)
{
int[] numArray = new int[5];
int i;
Scanner input=new Scanner(System.in);
System.out.print("Enter the 5 Array Elements: ");
for(i=0; i<5; i++)
//Read number
numArray[i]=input.nextInt();
for (i=0; i<numArray.length; i++)
122
} //Print number Arrays
} System.out.println("Array element[" + i + "] : "
+numArray[i]); 123
PENERBITOutput:
ILMU
BAKTI SDN. BHD.Enter the 5 Array Elements: 4 5 6 7 8
Array element[0] : 4
Array element[1] : 5
Array element[2] : 6
Array element[3] : 7
Array element[4] : 8
Example 3 Access array elements using for loop to enter Topic 7
data, calculate sum, and print its content
Mid Semester Test 1
import java.util.Scanner; //program uses Scanner class
class ArrayElements Answers
{
public static void main(String[] args)
{
int[] numArray = new int[5];
int i, sum=0;
Scanner input=new Scanner(System.in);
System.out.print("Enter the 5 Array Elements: ");
for (i=0; i<5; i++)
{
numArray[i]=input.nextInt(); //Read number
sum=sum+numArray[i]; //Calculate sum of numbers entered
}
for (i=0; i<numArray.length; i++)
//Print number
System.out.println("Array element[" + i + "] : "
+numArray[i]);
//Print sum
System.out.println("Sum of "+ i +" Array Elements: " +sum);
}
}
Output:
Enter the 5 Array Elements: 1 2 3 4 5
Array element[0] : 1
Array element[1] : 2
Array element[2] : 3
Array element[3] : 4
Array element[4] : 5
Sum of 5 Array Elements: 15
Arrays Quick Check 7.1
124 1 Examine the results of the following code.
String[] wordArray = {“hello”, “world”};
System.out.println(wordArray[0]); BAKTI SDN. BHD. // outputs hello
System.out.println(wordArray.length); // outputs 2
double[] wordArray = new double
System.out.println(wordArray[0]); // outputs 0.0
System.out.println(wordArray.length); // outputs 365
Topic 7 Array elements are accessed by index numbers, starting at zero:
"hello" "world" 0.0 0.0 … 0.0
0 1 01 364
(a) What is the index for the element “world”?
(b) What is the length of the array wordArray?
(c) What is the length of the array numberArray?
(d) How would you access the last element of numberArray?
Mid Semester Test 1 2 Examine the Java code below and answer the questions that follow.
Array variables can be initialised without the new keyword:
int[] picks = {3, 5, 7, 2, 1}
String[] names = {“Grace”, “Alan”, “Tim”};
However, if the variable is already declared, new is required:
ILMU
picks = new int[] {3, 5, 7, 2, 1}
names = new String[] {“Grace”, “Alan”, “Tim”};
(a) Write expressions to create the following new arrays. (Do not declare
variables.)
(i) 0 14 1024 127 3 5521
AnswersPENERBIT
(ii) 3.23 1.54 32.5 1.27 3.9 5.21
(b) Write statements that both declare and initialise variables for new arrays.
(i) 0 14 1024 127 3 5521
(ii) 3.23 1.54 32.5 1.27 3.9 5.21
3 Draw a memory diagram for the following array declarations.
(a) int[] sizes = new int[5];
sizes[2] = 7;
(b) double[] costs = new double[4];
costs[0] = 0.99;
(c) String[] names = new String[3];
names[1] = "Anita";
PENERBIT 4 Write Java statements that do the following: Arrays Topic 7
ILMU (a) Declare an array called numbers which will hold up to ten values (of
BAKTI SDN. BHD. 125Mid Semester Test 1
type int).
(b) Declare an array called temps which will hold up to five temperatures Answers
(of type int).
(c) Declare an array called name that will hold up to ten individual char
values.
(d) Output the value of the tenth element of the array alpha.
(e) Set the value of the fifth element of the array alpha to 35.
(f) Set the value of the ninth element of the array alpha to the sum of the
sixth and thirteenth elements of the array alpha.
5 Write a statement that declares a string array initialized with the following
strings:
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" and
"Saturday".
6 Write a for loop to display the content of each element in the array that you
declared in Question 5.
7 What do you think the following code will print out?
class Test1
{
public static void main(String[] args)
{
String[ ] names = {"Jamal", "Emily", "Kamal",
"Nurul", "Sofia"};
int index = 1;
System.out.println(names[index - 1]);
index++;
System.out.println(names[index]);
System.out.println(names[index/2]);
names[index] = "Rafi";
index = index-1;
System.out.println(names[index+1]);
}
}
7.5 One-Dimensional Arrays in Java
1 An array can contain several rows or columns of values, but a one-dimensional
array consists of just one row or column of values.
2 In Java, a one-dimensional array represents a row or column of array elements
that share a common name and are distinguishable by their index values.
3 For example, the marks obtained by a student in five tests can be represented by a
one-dimensional array since the marks can be written in one row or one column.
Summative Practice 7
1 Identify the components of an array based on the given declaration and initialization.
double[] number = { 32.0, 96.0, 3.0 , 17.0 };
(a) Array name
(b) Data type
(c) State the highest index for the given array in 1(a).
BAKTI SDN. BHD.
2 Declare and create an array named age to hold 6 integer values.
Topic 7 3 Given an array initialiser as follows:
double[] gold_price = {280.60, 260.50, 271.10, 230.20};
(a) Write a Java statement to print the fourth element in the given array.
(b) Write a Java statement to change the value 271.10 to 222.20.
4 Write a for loop statement to enable a user to enter the status of 20 Covid-19 self-tests in the array named
resultC19. (true for positive, false for negative).
*Assume all the variables are already declared and object Scanner name is scan.
Mid Semester Test 1 5 Given the following code segment, complete a Java code to read 20 numbers into an array named arrNum and
determine the maximum number.
Scanner input = new Scanner(System.in);
int[] arrNum = new int[20];
System.out.print(“Maximum =” + max);
ILMU
AnswersPENERBIT 6 A standard triathlon event involves a continuous timed race over various distances, combining the three
disciplines of swimming, cycling and running. Triathlon events occur in that order – a swim, followed by a
cycle ride, followed by a run. Write a complete Java program to determine the winner of a triathlon based on
the average points of all three disciplines. Assume the number of athlete is five and each athlete will be given
an ID. The program will first accept the athlete ID and then followed by the points for the three disciplines in
the stated order.
Sample input Sample output
1001 88.3 98.5 87.0 The winner is athlete ID 2000
2000 100.0 97.0 90.0 With average points : 95.67
1502 77.8 100.0 98.0
2230 89.2 85.0 90.1
4107 86.9 87.7 91.2
132
Semester Examination
[70 marks] Time: 2 hours
PENERBITInstructions: Answer All the questions.
ILMU
BAKTI SDN. BHD.
1 (a) State the appropriate step or activity involved in the process of problem solving in computer
programming.
[4 marks]
Activity Step in problem solving
(i) To make sure the program is free from syntax errors,
logical errors or runtime errors
(ii) The process of converting an algorithm to writing a
computer program using a programming language
(iii) Analysing the process of a system that satisfies the
needs of development
(iv) Prepare a simple explanation of the program codes Semester Examination
(b) The use of appropriate control structures is very important when implementing program code. Identify
the most appropriate control structure for the following problems.
[2 marks]
Problem Control structure
(i) Calculate a book price based on category
(ii) Calculate annual bonus for each of Nana’s Patin
House kitchen employees
(c) The total wage of the part-time staff of Hibiscus Café is based on the wages per hour and the number of
hours worked. In addition, if the staff has worked for more than 35 hours, then she or he can get twice
the wages per hour for every extra hour that she or he has worked; otherwise the wages is based on the
rate per hour.
Identify the input, process and output to calculate and display the total wages of part-time staff at
Hibiscus Café.
[4 marks]
Input
Process
Output
165
Semester Examination
(d) Based on the algorithm below, identify the input, process and output. Take the value of x to be 21.
[4 marks]
Start
Read x
if (x equal to 21)
Display “yes, you’re lucky guy!”
x = x + 333
end if
if (x equal to 0)
Display “sorry, you’re unlucky!”
else
Display “try again, if you dare!”
endif
Stop
BAKTI SDN. BHD.
Input
Process
Output
Semester Examination 2 (a) Pasaraya Purple Star offers an incentive for its Year-End Sales Carnival to their staff as follows:
Work Experience Monthly Sales Incentive
5 years and above RM40 000 and above RM5 000
Less than RM40 000 RM3 000
Others RM1 000
Not specified
ILMU
Write pseudocode to calculate the incentive that will be received by a staff member.
[6 marks]
PENERBIT
166
Semester Examination
(b) Draw a flowchart for a program to Calculate Profit or Loss. This program allows the user to enter
the Actual amount and the Sales amount. By using those two values, the program checks whether the
product gives a profit or Loss. If the Actual amount is less than the Sales amount, it is a profitable
product. Else if the Actual amount is greater than the Sales amount, the product makes a Loss;
otherwise, there is no profit, no loss.
[10 marks]
PENERBIT Semester Examination
ILMU
BAKTI SDN. BHD.
3 Java is a high-level, class-based, object-oriented programming language that is designed to have as few
implementation dependencies as possible.
(a) Declare a variable based on the description of the primitive data type.
(i) Use this data type for simple flags that track true/false conditions.
[1 mark]
(ii) For decimal values, this data type is generally the default choice.
[1 mark]
(b) Construct the following expressions in the correct Java syntax.
(i) 2x3 + 6y2 – z
[2 marks]
(ii) 1+32a + 4(b+c)(5–d)
f
[2 marks]
167
Semester Examination
(c) Solve the following expressions by analysing the precedence of the respective operators.
(i) ( 5.0 * (98.4 – 32.0) ) / 9.0
[1 mark]
(ii) 3 + 6 / 2 * 3 – 1 + 2.0 BAKTI SDN. BHD.
[1 mark]
(d) What is the output of the following code?
(i) m = 10;
if(m < 15)
System.out.print("GOOD");
System.out.print("THANK YOU");
[2 marks]
Semester Examination (ii) b = 1;
while(b > 8)
{
System.out.print(b + " ");
b = b + 2;
}
[2 marks]
ILMU
(e) Mr Hassan wants to calculate the final marks of his students based on their test sccores. The final marks
is 30% of their test scores. Write a code segment to help him calculate and display the students' marks.
This calculation will continue until a value greater than 100 is entered to stop the process.
[5 marks]
PENERBIT
168
Semester Examination
(f) Write a Java program to calculate the sum of the odd numbers from 10 different positive numbers
entered by the user.
[8 marks]
PENERBIT
ILMU
BAKTI SDN. BHD.
4 Write a Java program for a class named HeaviestClass to find the heaviest watermelon from an array. The Semester Examination
class shall contain the main method and findHeaviest method.
(i) In the main method:
– Enter n (number of watermelons)
– Declare and create an integer array named weight[n]
– Use a loop statement to input weight[i]
– Assign the value returned by method findHeaviest to a variable named resultHeaviest.
– Display resultHeaviset.
(ii) In the findHighest method:
– Use a loop statement to determine the maximum value.
– Receive an integer array of values (m) through its parameter.
– Return the heaviest.
[15 marks]
169
Answers
1 Introduction to Programming Summative Practice 1
PENERBIT
ILMU Quick Check 1.1 1 (a) Programming language is a set of commands,
BAKTI SDN. BHD. instructions, and other syntax that is used to create a
1 A programming language is a set of words, abbreviations, and software program.
symbols that enables software developers to use a program (b) Programming paradigm is a style/way/approach that
a computer language user to look at the problem to be
development tool to create a program or app. solved.
2 Java,Visual Basic, C, C++, Python (c) Translator is a program that translates a computer
program/computer code into machine language.
3 Low-level Languages, High-level Languages
2 (a) The high-level language is a programming language
4 Low-level Language High-level Language that uses human-readable commands and allows a
programmer to write programs that are independent of a
It is a machine-friendly It is a programmer-friendly particular type of computer.
language. The computer language as the code is human
can easily understand the readable. (b) (Accept any one of the following answers)
instructions, – The high-level language is easy to read, write, and
It it is a non-portable It is a portable language that maintain as it is written in English-like words.
language. can run on any platform. – High-level languages are designed to overcome the
It is complex to debug It is simpler to debug and limitation of low-level language, i.e., portability. The
and maintain. maintain. high-level language is portable; i.e., these languages
are machine-independent.
An assembler is needed A compiler or interpreter (c) (Accept any of the following answers)
to translate assembly is needed to translate the
code into machine code. instructions into machine code. Low-level Language High-level Language
It is memory efficient. It is less memory efficient. It is a machine-friendly It is a programmer-
language. The computer friendly language as the
5 Programming paradigms are the different styles or ways by can easily understand the code is human readable.
instructions,
which computer languages look at the problem to be solved.
6 Procedural, Object-Oriented, Logic It it is a non-portable It is a portable language
language. It is machine- that can run on any
7 Paradigm 2: Paradigm 3: dependent. platform.
Paradigm 1: (Object- (Logic)
Oriented) It is complex to debug It is simpler to debug and
( Procedural) and maintain. maintain.
Designed Designed with Designed with An assembler is needed to A compiler or interpreter
with focus on focus on objects focus on facts and translate assembly code is needed to translate the
procedures and and methods rules into machine code. instructions into machine
data code.
Uses a linear Follows a bottom- Takes a It is memory efficient. It is less memory
or top-down up approach declarative efficient.
approach approach to
problem-solving,
based on formal 3 (a) (i) Logic paradigm (ii) OOP
logic
(b) A Procedural paradigm is a computer programming
technique which focuses on well-structured steps and
8 A translator is a program that translates programming source procedures.
code into machine language. (c) C / COBOL / MATLAB / Python
9 Assembler Compiler Interpreter 4 Assembler (translates assembly language to machine
language)
Converts Converts entire Translates and 5 (a) X Y
assembly high-level source executes high- Translates high-level Translates entire/whole
language into machine high level language into
language source code into machine level source code language line by line machine language
Aprsosgermamblyinto Llaanngguuaaggees like Linatnogmuaagchesinleikceode
lmanagchuiangeeluasnegsuaange C and C++ use Plienrel bayndliPney.thon
No object code created Object code created
assember compilers use interpreters during execution
(b) Java, / C++ / Visual Basic
170
Answers
PENERBIT 2 Approach in Problem Solving (l) Input: Birth year, current year Answers
ILMU Process: Determine age based on the birth year and
BAKTI SDN. BHD. Quick Check 2.1
current year, and print suitable messages for 10 persons
1 Problem solving in computer programming is the process Output: Ten ages and messages “Retired” or “Still
of identifying a problem, developing a solution, and finally
implementing the solution to develop a computer program. working”
(m) Input: (none)
2 Five main steps in problem solving: Process: Calculate the squares of the numbers 1 to 20
Step 1 : Problem analysis (IPO) Output: Squares of numbers
Step 2 : Design a solution (pseudocode/flowchart) (n) Input: n
Step 3 : Implement the solution (writing coding) Process: Calculate the sum of 1 to n
Step 4 : Test the solution (run) Output: Sum of 1 to n
Step 5 : Documentation
Summative Practice 2
3 (a) Input: Int1,int2
1 Step 1: Problem analysis —the process where we identify and
Process: Calculate the product of two integers understand the problem, determining the input, process and
output required.
Output: Product of two integers
(b) Input: Side of square Step 2: Design a solution– the process where the algorithm is
Process: Calculate the area of square based on side created to represent the solution of given problem statement.
entered by user
Output: Area of square 2 (Accept any two appropriate answers)
(c) Input: Height, width, length – Documentation allows a programmer to understand the
Process: Calculate the volume of a box based on height, flow of the program for future reference.
width and length entered by user – Documentation can be used to guide user on how to use the
Output: Volume of a box program.
(d) Input: Radius – It explains the purpose of code statements.
Process: Calculate the area and circumference of circle
based on radius 3 (a) Implementation
Output: Area and Circumference of Circle (b) Documentation
(e) Input: Int1, int2, int3 (c) Testing
Process: Determine the largest integers based on int1, (d) Design a solution
int2, int3 (e) Problem analysis
Output: Largest integer 4 Input: Operating hours
(f) Input: Mark1, mark2, mark3 Process: Calculate the number of requests that can be
Process: Calculate the average mark based on mark1,
mark2 and mark3 processed based on hours
Output: Average mark Output: Maximum number of customers
(You may use repetition to solve this problem too!) 5 Input: Purchase amount
Repetition Control Structure Process: Determine the number of RM20 vouchers based on
Input: Mark
Process: Calculate the average of 3 marks entered one by purchase amount.
one, by the user. Output: Number of RM20 vouchers
Output: Average of 3 marks 6 Input: User value
(g) Input: Distance in miles Process: Determine the message to display based on user
Process: Convert the distance in miles to kilometres
Output: kilometres value.
(h) Input: Price, sales tax rate Output: Message “VIVO”, or “OPPO” or “SAMSUNG” or
Process: Calculate the total price including sales tax
Output: Total price “iPhone”
(i) Input: 5 jumps 7 Input: Age, gender
Process: Calculate average of 5 jumps Process: Determine and and display the insurance policy rate
Output: Average of 5 jumps
Repetition Control Structure: repeatedly based on age of customers for n times
Input: Jump Output: Insurance policy rate
Process: Calculate average of 5 jumps entered one by 8 Input: Number of participants
one, by the user Process : Calculate the net profit for the seminar
Output: Average of 5 jumps Output : Net profit
(j) Input: Age
Process: Determine the ticket price based on age 3 Design a Solution
Output: Ticket price
(k) Input: Quantity, price per item Quick Check 3.1
Process: Calculate the total price based on quantity and
price per item with a 10% discount given if the total price 1 An algorithm is a well-defined step-by-step solution or a series
is more than 5000 of instructions to solve a problem, transforming the input into
Output: Total price the output.
2 (1) Pseudocode—A semiformal, English-like language
with a limited vocabulary that can be used to design an
algorithm.
171
Answers
(2) Flowchart—A graphical representation of an algorithm Pseudocode:
consisting of geometrical shapes that are connected by
flow lines. Start
Read price, discount_rate
3 Pseudocode discount = discount_rate*price
Advantages: price_after_discount = price – discount
(i) It can be quickly and easily converted into an actual Print price_after_discount
Stop
programming language as it is similar to a programming
AnswersPENERBIT language. Flowchart: Start
ILMU (ii) It is fairly easy to understand, even for non-programmers.
BAKTI SDN. BHD. (iii) It does not matter if there are errors in the syntax, as itRead price and
usually quite obvious what is intended. discount_rate
Disadvantages:
(i) It can be hard to see how a program flows. For example, discount = discount_rate * price
where does following one path as opposed to another
take the program? price_after_discount = price – discount
(ii) There is no standardised style or format, so one
pseudocode may be different from another. Print price_after_discount
Flowchart
Advantages: Stop
(i) It helps us to understand the logic of a given problem. 3 Problem analysis:
(ii) It is very easy to draw flowcharts in any word processing Input: Height, width, length
software like MS Word. Process: Calculate volume of box
(iii) Using only very few symbols, complex problems can be Output: Volume of box
represented in flowcharts.
Disadvantages: Pseudocode:
(i) Manual tracing is needed to check the correctness of a Start
flowchart drawn on paper. Read height, width, length
(ii) A simple modification to the problem logic may lead to Volume = height*width*length
complete redraw of a flowchart. Print volume
(iii) Modification of a flowchart is sometimes time Stop
consuming.
Flowchart: Start
Quick Check 3.2
Read height, width, length
1 Problem analysis:
Input: (None) volume = height*width*length
Process: Display message
Output: Message “Hello Matriculation” Print volume
Pseudocode:
Start
Print “Hello Matriculation”
Stop
Flowchart:
Start Stop
Print “Hello 4 Problem analysis:
Matriculation” Input: Number of umbrellas
Process: Calculate the total price of the umbrellas
Stop Output: Total price
2 Problem analysis:
Input: Price, discount rate Pseudocode:
Process: Calculate the price after discount Start
Output: Price after discount Read number_of_umbrellas
total_price=number_of_umbrellas*3
Print total_price
Stop
172
PENERBIT
ILMU
BAKTI SDN. BHD.