Sei sulla pagina 1di 36

Silay Institute, Inc.

SILAY CITY
SENIOR HIGH SCHOOL DEPARTMENT
INSTRUCTIONAL MODULE
COMPUTER PROGRAMMING
2nd SEMESTER, S.Y. 2019 - 2020

TOPIC : PROGRAMMING CONCEPTS

LEARNING OBJECTIVES : The learners shall able to:

1. Know the steps required to create programs using a programming language and related terminology
2. Compare and contrast high level programming from machine language.

CONTENT:
PROGRAMMING LANGUAGES

Program is a set of instructions that tell a computer what to do. The execute program to carry out the instruction listed
by that program.

High level programming languages are programming languages that are rather natural people to write
Examples:
Java, C, C++, C#, Objective – C, Visual Basic, Pascal, Delphi, FORTRAN, AND COBOL.

Most primitive type of programming language is a machine language or object code.

Object code is a set of binary code that is unique to the type of CPU. Each instruction of the object code corresponds to
a fundamental operation of the CPU.

It usually requires many object code instructions to do what can be done in one line of high – level language code.
Writing object code directly is tedious and error prone.

High level language coded does not get executed on a computer directly. It needs to be translated from the high-level
language to suitable machine language first. Such a translator program is normally referred to as a compiler.

The input of a compiler is referred to as source code. Source code is compiled by a compiler to obtain target code.

Problem solving using Computer Program


The following steps when developing a computer program for some problems.
• Problem Defining - understand the thing that you want to solve. A clever solution for the wrong problem is a
waste.
• Analysis – determine inputs, outputs and relevant factors for the define problem.
• Design – describe the methods used for solving the defined problem. Provide a detailed process required to be
done in order to go from taking inputs to producing the outputs.
• Testing – test the program whether it delivers the correct results.
• Implementation – always go back to improve earlier steps so that code can be written in an efficient manner.
Think and Pair Task
1. What are the differences between machine languages and high-level programming languages?
2. Suppose you are to write a currency converter program that can convert the amount money among Baht, US
Dollar, and Euro. Describe how you would analyze the problem and design the program to be written.

ENRICHMENT
A. Identification:
Direction: Read each statement carefully. Identify the following statement.
_______________ 1. It is input of a compiler.
_______________ 2. The most primitive type of programming languages.
_______________ 3. A set if instructions that tell a computer what to do.
_______________ 4. These are programming languages that are rather natural people to write.
_______________ 5. A translator programs.
B. 6 – 10. Examples of High - Level Programming Languages
6. _________________ 7. ________________ 8. _____________ 9. ________________ 10. _____________
Prepared by: MS. KARLA A. LIDRES
Silay Institute, Inc.
SILAY CITY
SENIOR HIGH SCHOOL DEPARTMENT
INSTRUCTIONAL MODULE
COMPUTER PROGRAMMING
2nd SEMESTER, S.Y. 2019 - 2020

TOPIC : FLOWCHARTIG AND ALGORITHM


LEARNING OBJECTIVES : The learners shall able to:
1. Conceptually define flowchart and algorithm.
2. Design a flowchart to describe program process.
CONTENT:

FLOWCHARTING AND ALGORTIHMS


Flowchart – a diagram representing the logical sequence in which a combination of steps or operations is to be
performed. It is a blueprint of the program.

Algorithm – is a finite set of instructions that specify a sequence of operations to be carried out in order to solve a
specific problem or class of problems.

BASIC SYMBOLS USED IN FLOWCHARTING


SYMBOLS WHAT IT REPRESENTS

- Used to signify the beginning and end of flowchart

TERMINAL

- Signifies the preparation of data


- Used to select initial conditions.
PREPARATION/ INITIALIZATION

- shows input and output. Data are to be read into the


computer memory from an input device or data are
to be passed from the memory to an output device.
INPUT/OUTPUT

- performs any calculations that are to be done.

PROCESS

- signifies any decisions that are to be done.

DECISION

- shows the entry or exit point of the flowchart


- a non - processing symbol used to connect one part
ON PAGE CONNECTOR of a flowchart to another without drawing flowlines.

- designates entry to or exit from one page when a


flowchart requires more than one page.

OFF PAGE CONNECTOR

- signifies the process that is to be executed next.

Prepared by: MS. KARLA A. LIDRES


Silay Institute, Inc.
SILAY CITY
SENIOR HIGH SCHOOL DEPARTMENT
INSTRUCTIONAL MODULE
COMPUTER PROGRAMMING
2nd SEMESTER, S.Y. 2019 - 2020

BASIC CONTORL STRUCTURES


I. SEQUENCE – process is executed from one to another in a straightforward manner.

Examples:

1. Design a flowchart that will accept and display a number. Write its equivalent algorithm

FLOWCHART ALGORITHM

1. START
START 2. Read N
3. Print N
4. End

READ
N

PRINT
N

END

2. Draw a flowchart that will compute and display the sum and product of two numbers. Write its equivalent
algorithm.

ALGORITHM
START
1. Start
2. Initialize sum = 0 , product = 0
3. Read num1, num2
4. Compute
sum = 0 sum = num1 + num2
product = 0 product = num1 * num2
5. Print sum, product
6. End

Read Print
sum= num1 + num2 END
num1, sum,
product = num1 * num2
num 2 product
Prepared by: MS. KARLA A. LIDRES
Silay Institute, Inc.
SILAY CITY
SENIOR HIGH SCHOOL DEPARTMENT
INSTRUCTIONAL MODULE
COMPUTER PROGRAMMING
2nd SEMESTER, S.Y. 2019 - 2020

OPERATORS COMMONLY USED IN FLOWCHARTING

Operators Meaning Logical Operators


+ Addition && AND
- Subtraction II OR
* Multiplication ! NOT
/ Division

Relational Operators

= equal
> greater than
< less than
=! Not equal
>= greater than or equal to
<= less than or equal to

Think and Pair Task

Briefly explain the following.


1. What are the benefits of using flowcharts?
2. Compare flowchart from algorithm

Enrichment:

1. Draw a flowchart that will input his name and two numbers. Compute the sum of two numbers. Display his name and the sum.
Write its equivalent algorithm.

2. Construct a flowchart that will compute and display the sum and average of 5 numbers. Write its equivalent algorithm.

3. Read two (2) records in a computer. The first record will contain unit price and the second record will be quantity. Draw a
flowchart that will compute and display the amount by multiplying unit price and quantity.

Prepared by: MS. KARLA A. LIDRES


Silay Institute, Inc.
SILAY CITY
SENIOR HIGH SCHOOL DEPARTMENT
INSTRUCTIONAL MODULE
COMPUTER PROGRAMMING
2nd SEMESTER, S.Y. 2019 - 2020

TOPIC : FLOWCHARTING AND ALGORITHM (SELECTION AND LOOP)


LEARNING OBJECTIVES : The learners shall be able to:
1. Draw a flowchart and algorithm with use of selection and loop structure.
CONTENT:

• Selection (if - then - else) - a choose is provided between two alternatives.

F T

⚫ LOOP - this structure provides for the repetitive execution of an operation or routine while the condition is true. The condition is
evaluated before executing any process statement. As long as the condition is true, the process, control flows out of the structure.

T F
C

LOOP

Examples:

1. Draw a flowchart that will input the values of num1 and num2. Compare the two values inputted and print
which of the value is higher including the remark “higher”. Write its equivalent algorithm.

START

Read
num1,
num 2

num1 >
num2

Print Num2, “higher” Print Num1, “higher”

END
Prepared by: MS. KARLA A. LIDRES
Silay Institute, Inc.
SILAY CITY
SENIOR HIGH SCHOOL DEPARTMENT
INSTRUCTIONAL MODULE
COMPUTER PROGRAMMING
2nd SEMESTER, S.Y. 2019 - 2020

2. Construct a flowchart that will count from 1 to 10 and print each number counted using the do while repetition
structure. Write it’s equivalent algorithm.

START

c=0

C < 10 END

c=c+1

Print c

Algorithm
1. Start
2. Initialize c = 0
3. Test if c < 10
4. If c < 10, Increment the value of C by 1.
Print c, loop back and proceed to step 2.
5. If c > 10, end the process.
Think and Pair Task
1. Draw a flowchart describing a process that a bank customer could use in making cash withdrawal from an ATM machine.
2. Construct a flowchart that asks for the amount of purchased by the customer. If the customer purchases more than
2,000.00, then a 5% discount is given. Display the net amount to be paid. Write its equivalent algorithm.
3. Draw a flowchart that will input a grade of the student and determine whether the grade is greater than or equal to 75,
“PASSED” otherwise “FAILED”. Print the name, grade and remarks of the student. Write its equivalent algorithm.

Enrichment
1. The initial value of the radius of a circle is equal to 1 unit and each succeeding radius is 1 unit greater than the value
before it. Draw a flowchart to compute the Area of a circle starting with R = 1 up to R = 5, then display each radius and the
corresponding area of a circle.
2. DEI Manufacturing Company plans to give a year - end bonus to each of the employee. Draw a flowchart which will
compute the bonus of an employee. Consider the following conditions. If the employee’s monthly salary is less than 2,000
pesos, the bonus is 50% of the salary; for the employees with salaries greater than 2,000 pesos, the bonus is 1,500 pesos.
Print the name and the corresponding bonus for each employee. Write its equivalent algorithm.

Prepared by: MS. KARLA A. LIDRES


Silay Institute, Inc.
SILAY CITY
SENIOR HIGH SCHOOL DEPARTMENT
INSTRUCTIONAL MODULE
COMPUTER PROGRAMMING
2nd SEMESTER, S.Y. 2019 - 2020

TOPIC : INTRODUCTION TO JAVA PROGRAMMING


LEARNING OBJECTIVES : The learners shall be able to:
1. Familiar with the basic structure of a Java program
2. Create Java program to obtain desired results.
CONTENT
HISTORY OF JAVA

James Gosling initiated Java language project in June 1991 for use in one of his many set top box projects. The language,
initially called ‘Oak’ after an oak tree that stood outside Gosling's office, also went by the name ‘Green’ and ended up later
being renamed as Java, from a list of random words.

Sun released the first public implementation as Java 1.0 in 1995. It promised Write Once, Run Anywhere (WORA), providing
no-cost run-times on popular platforms.

On 13 November, 2006, Sun released much of Java as free and open source software under the terms of the GNU General
Public License (GPL).

On 8 May, 2007, Sun finished the process, making all of Java's core code free and open source, aside from a small portion
of code to which Sun did not hold the copyright.

Popular Java Editors


To write your Java programs, you will need a text editor. There are even more sophisticated IDEs available in the market.
But for now, you can consider one of the following:

• Notepad: On Windows machine, you can use any simple text editor like Notepad (Recommended for this tutorial),
TextPad.

• Netbeans: A Java IDE that is open-source and free, which can be downloaded from http://www.netbeans.org/index.html.

• Eclipse: A Java IDE developed by the eclipse open-source community and can be downloaded from
http://www.eclipse.org/.

Basic Syntax

When we consider a Java program, it can be defined as a collection of objects that communicate via invoking each other's
methods. Let us now briefly look into what do class, object, methods, and instance variables mean.

• Object - Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behavior such as
wagging their tail, barking, eating. An object is an instance of a class.

• Class - A class can be defined as a template/blueprint that describes the behavior/state that the object of its type supports.

• Methods - A method is basically a behavior. A class can contain many methods. It is in methods where the logics are
written, data is manipulated and all the actions are executed.

• Instance Variables - Each object has its unique set of instance variables. An object's state is created by the values assigned
to these instance variables.

Prepared by: MS. KARLA A. LIDRES


Silay Institute, Inc.
SILAY CITY
SENIOR HIGH SCHOOL DEPARTMENT
INSTRUCTIONAL MODULE
COMPUTER PROGRAMMING
2nd SEMESTER, S.Y. 2019 - 2020

First Java Program


Let us look at a simple code that will print the words Hello World.

public class MyFirstJavaProgram {


/* This is my first java program.
* This will print 'Hello World' as the output
*/
public static void main(String[] args) {
System.out.println("Hello World"); // prints Hello World
}
}

Output:
C:\> javac MyFirstJavaProgram.java
C:\> java MyFirstJavaProgram
Hello World

About Java programs, it is very important to keep in mind the following points.
• Case Sensitivity - Java is case sensitive, which means identifier Hello and hello would have different meaning in Java.

• Class Names - For all class names the first letter should be in Upper Case. If several words are used to form a name of the
class, each inner word's first letter should be in Upper Case.
Example: class MyFirstJavaClass

• Method Names - All method names should start with a Lower-Case letter. If several words are used to form the name of
the method, then each inner word's first letter should be in Upper Case.
Example: public void myMethodName()

• Program File Name - Name of the program file should exactly match the class name. When saving the file, you should save
it using the class name (Remember Java is case sensitive) and append '.java' to the end of the name (if the file name and
the class name do not match, your program will not compile).
Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should
be saved as 'MyFirstJavaProgram.java'

• public static void main(String args[]) - Java program processing starts from the main() method which is a mandatory part
of every Java program.

Java Identifiers
All Java components require names. Names used for classes, variables, and methods are
called identifiers. In Java, there are several points to remember about identifiers. They are as follows:
• All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an underscore (_).
• After the first character, identifiers can have any combination of characters.
• A key word cannot be used as an identifier.
• Most importantly, identifiers are case sensitive.
• Examples of legal identifiers: age, $salary, _value, __1_value.
• Examples of illegal identifiers: 123abc, -salary.

Prepared by: MS. KARLA A. LIDRES


Silay Institute, Inc.
SILAY CITY
SENIOR HIGH SCHOOL DEPARTMENT
INSTRUCTIONAL MODULE
COMPUTER PROGRAMMING
2nd SEMESTER, S.Y. 2019 - 2020

Java Modifiers
Like other languages, it is possible to modify classes, methods, etc., by using modifiers. There are two categories of
modifiers:
• Access Modifiers: default, public , protected, private
• Non-access Modifiers: final, abstract, strictfp We will be looking into more details about modifiers in the next section.

Java Variables
Following are the types of variables in Java:
• Local Variables
• Class Variables (Static Variables)
• Instance Variables (Non-static Variables)

Java Arrays
Arrays are objects that store multiple variables of the same type. However, an array itself is an object on the heap.

Java Enums
Enums were introduced in Java 5.0. Enums restrict a variable to have one of only a few predefined values. The values in this
enumerated list are called enums. With the use of enums it is possible to reduce the number of bugs in your code.

For example, if we consider an application for a fresh juice shop, it would be possible to restrict the glass size to small,
medium, and large. This would make sure that it would not allow anyone to order any size other than small, medium, or
large.

Example

class FreshJuice {
enum FreshJuiceSize{ SMALL, MEDIUM, LARGE
}
FreshJuiceSize size;
}
public class FreshJuiceTest {

public static void main(String args[]){

FreshJuice juice = new FreshJuice();

juice.size = FreshJuice.FreshJuiceSize.MEDIUM ;
System.out.println("Size: " + juice.size);
}
}

The above example will produce the following result:

Size: MEDIUM

Prepared by: MS. KARLA A. LIDRES


Silay Institute, Inc.
SILAY CITY
SENIOR HIGH SCHOOL DEPARTMENT
INSTRUCTIONAL MODULE
COMPUTER PROGRAMMING
2nd SEMESTER, S.Y. 2019 - 2020

Java Keywords
The following list shows the reserved words in Java. These reserved words may not be used as constant or variable or any other
identifier names.

abstract assert boolean break


byte case catch case
class const continue default
do final else enum
extends Goto finally float
For instanceof if implements
Import native int interface
long protected new package
private static public return
short synchronized strictfp super
switch transient this throw
throws while try void
volatile double

Comments in Java
Java supports single-line and multi-line comments very similar to C and C++. All characters available inside any comment
are ignored by Java compiler.

public class MyFirstJavaProgram {


/* This is my first java program.
* This will print 'Hello World' as the output
* This is an example of multi-line comments.
*/
public static void main(String[] args) {

// This is an example of single line comment


/* This is also an example of single line comment. */

System.out.println("Hello World"); // prints Hello World


}
}

Using Blank Lines


A line containing only white space, possibly with a comment, is known as a blank line, and Java totally ignores it.

Inheritance
In Java, classes can be derived from classes. Basically, if you need to create a new class and here is already a class that has
some of the code you require, then it is possible to derive your new class from the already existing code. This concept allows
you to reuse the fields and methods of the existing class without having to rewrite the code in a new class. In this scenario,
the existing class is called the superclass and the derived class is called the subclass.

Prepared by: MS. KARLA A. LIDRES


Silay Institute, Inc.
SILAY CITY
SENIOR HIGH SCHOOL DEPARTMENT
INSTRUCTIONAL MODULE
COMPUTER PROGRAMMING
2nd SEMESTER, S.Y. 2019 - 2020

Think and Pair Task


1. Write a complete Java program that shows your first name and last name on screen.
2. Change this source code as little as possible, so that it gets compiled successfully.

Enrichment:

1. Write a program that will compute and display the area of rectangle as the following output. Draw a
flowchart for the program.
Formula: Area = Length * Width
Assume Output:
Enter Length : 5

Enter Width : 3

Area of Rectangle : 15

2. Write a complete Java program that will compute the sum and the average of the integer 1 to 5 as the
following output. Draw a flowchart for the program.

Output: The sum of 1 t0 5 is : 15.0

The average of 1 to 5 : 3.0

Prepared by: MS. KARLA A. LIDRES


Silay Institute, Inc.
SILAY CITY
SENIOR HIGH SCHOOL DEPARTMENT
INSTRUCTIONAL MODULE
COMPUTER PROGRAMMING
2nd SEMESTER, S.Y. 2019 - 2020

TOPIC : JAVA CLASSES AND OBJECTS


LEARNING OBJECTIVES : The learners shall be able to:
1. Understand classes and objects
2. Use class methods and data from existing classes.
3. Familiar with String class and use its methods.

CONTENT
In real world, the word class is used to identify category of things, while objects of a class are instances of things
belonging to that category.

• Object - Objects have states and behaviors. Example: A dog has states - color, name, breed as well as
behaviors – wagging the tail, barking, eating. An object is an instance of a class.

• Class - A class can be defined as a template/blueprint that describes the behavior/state that the object
of its type support.

Objects in Java
Let us now look deep into what are objects. If we consider the real-world, we can find many objects
around us, cars, dogs, humans, etc. All these objects have a state and a behavior.

If we consider a dog, then its state is - name, breed, color, and the behavior is - barking, wagging the tail,
running.

If you compare the software object with a real-world object, they have very similar characteristics.
Software objects also have a state and a behavior. A software object's state is stored in fields and
behavior is shown via methods.

So in software development, methods operate on the internal state of an object and the object-to-object
communication is done via methods.

Classes in Java
A class is a blueprint from which individual objects are created.

Following is a sample of a class.

public class Dog{

String breed;

int ageC;

String color;

void barking(){
}
void hungry(){
}
void sleeping(){
}
}

A class can contain any of the following variable types.


Prepared by: MS. KARLA A. LIDRES
Silay Institute, Inc.
SILAY CITY
SENIOR HIGH SCHOOL DEPARTMENT
INSTRUCTIONAL MODULE
COMPUTER PROGRAMMING
2nd SEMESTER, S.Y. 2019 - 2020

• Local variables: Variables defined inside methods, constructors or blocks are called local variables. The variable will be
declared and initialized within the method and the variable will be destroyed when the method has completed.

• Instance variables: Instance variables are variables within a class but outside any method. These variables are initialized
when the class is instantiated. Instance variables can be accessed from inside any method, constructor or blocks of that
particular class.

• Class variables: Class variables are variables declared within a class, outside any
method, with the static keyword.

A class can have any number of methods to access the value of various kinds of methods. In the above example, barking(),
hungry() and sleeping() are methods.

Java Strings

Strings are used for storing text.

A String variable contains a collection of characters surrounded by double quotes:

Example

public class MyClass {


public static void main(String[] args) {
String greeting = "Hello";
System.out.println(greeting);
}
}
Output:
Hello
String Length

A String in Java is actually an object, which contain methods that can perform certain operations on strings. For example,
the length of a string can be found with the length() method:

public class MyClass {


public static void main(String[] args) {
String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println("The length of the txt string is: " + txt.length());
}
}

Output:
The length of the txt string is: 26

Prepared by: MS. KARLA A. LIDRES


Silay Institute, Inc.
SILAY CITY
SENIOR HIGH SCHOOL DEPARTMENT
INSTRUCTIONAL MODULE
COMPUTER PROGRAMMING
2nd SEMESTER, S.Y. 2019 - 2020

String Methods
There are many string methods available, for example toUpperCase() and toLowerCase():

public class MyClass {


public static void main(String[] args) {
String txt = "Hello World";
System.out.println(txt.toUpperCase());
System.out.println(txt.toLowerCase());
}
}

Output
HELLO WORLD
hello world

Finding a Character in a String

The indexOf() method returns the index (the position) of the first occurrence of a specified text in a string (including
whitespace):

public class MyClass {


public static void main(String[] args) {
String txt = "Please locate where 'locate' occurs!";
System.out.println(txt.indexOf("locate"));
}
}

Output:
7

String Concatenation

The + operator can be used between strings to combine them. This is called concatenation:

public class MyClass {


public static void main(String args[]) {
String firstName = "John";
String lastName = "Doe";
System.out.println(firstName + " " + lastName);
}
}

Output:
John Doe

Note that we have added an empty text (" ") to create a space between firstName and lastName on print.

You can also use the concat() method to concatenate two strings:
public class MyClass {
public static void main(String[] args) {

Prepared by: MS. KARLA A. LIDRES


Silay Institute, Inc.
SILAY CITY
SENIOR HIGH SCHOOL DEPARTMENT
INSTRUCTIONAL MODULE
COMPUTER PROGRAMMING
2nd SEMESTER, S.Y. 2019 - 2020

String firstName = "John ";


String lastName = "Doe";
System.out.println(firstName.concat(lastName));
}
}
Output:
John Doe

Special Characters

Because strings must be written within quotes, Java will misunderstand this string, and generate an error:

String txt = "We are the so-called "Vikings" from the north.";

The solution to avoid this problem, is to use the backslash escape character.

The backslash (\) escape character turns special characters into string characters:

Escape character Result Description

\' ' Single quote

\" " Double quote

\\ \ Backslash

The sequence \" inserts a double quote in a string:

public class MyClass {


public static void main(String[] args) {
String txt = "We are the so-called \"Vikings\" from the north.";
System.out.println(txt);
}
}
Output:
We are the so-called "Vikings" from the north

Prepared by: MS. KARLA A. LIDRES


Silay Institute, Inc.
SILAY CITY
SENIOR HIGH SCHOOL DEPARTMENT
INSTRUCTIONAL MODULE
COMPUTER PROGRAMMING
2nd SEMESTER, S.Y. 2019 - 2020

Java User Input


The Scanner class is used to get user input, and it is found in the java.util package.

To use the Scanner class, create an object of the class and use any of the available methods found in the Scanner class
documentation. In our example, we will use the nextLine() method, which is used to read Strings:

import java.util.Scanner; // import the Scanner class

class MyClass {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
String userName;

// Enter username and press Enter


System.out.println("Enter username");
userName = myObj.nextLine();

System.out.println("Username is: " + userName);


}
}

Input Types
In the example above, we used the nextLine() method, which is used to read Strings. To read other types, look at the
table below:

Method Description

nextBoolean() Reads a boolean value from the user

nextByte() Reads a byte value from the user

nextDouble() Reads a double value from the user

nextFloat() Reads a float value from the user

Prepared by: MS. KARLA A. LIDRES


Silay Institute, Inc.
SILAY CITY
SENIOR HIGH SCHOOL DEPARTMENT
INSTRUCTIONAL MODULE
COMPUTER PROGRAMMING
2nd SEMESTER, S.Y. 2019 - 2020

nextInt() Reads a int value from the user

nextLine() Reads a String value from the user

nextLong() Reads a long value from the user

nextShort() Reads a short value from the user

In the example below, we use different methods to read data of various types:

import java.util.Scanner;

class MyClass {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);

System.out.println("Enter name, age and salary:");

// String input
String name = myObj.nextLine();

// Numerical input
int age = myObj.nextInt();
double salary = myObj.nextDouble();

// Output input by user


System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
}
}

Output

Enter name, age and salary:

Prepared by: MS. KARLA A. LIDRES


Silay Institute, Inc.
SILAY CITY
SENIOR HIGH SCHOOL DEPARTMENT
INSTRUCTIONAL MODULE
COMPUTER PROGRAMMING
2nd SEMESTER, S.Y. 2019 - 2020

Think and Pair Task

1. Use the correct method to print the length of the txt string.

String txt = "Hello";


System.out.println( . );

2. Convert the value of txt to upper case.

String txt = "Hello";


System.out.println( . );

3. Use the correct method to concatenate two strings:

String firstName = "John ";


String lastName = "Doe";
System.out.println(firstName. (lastName));

4. Explain why the String Class is available in program without the use of an import statement and why an import
statement is required when using Scanner class in our program.

Enrichment

1. Write valid Java statements that perform the following steps.

1. Declare a variable for storing a String. Name it s1.


2. Have s1 refer to a new String object whose content is “Java”.
3. Declare another variable named s2 and have it referred to a new String object whose content is “Programming”.
Print the concatenation of s1 and s2 on screen.

Prepared by: MS. KARLA A. LIDRES


Silay Institute, Inc.
SILAY CITY
SENIOR HIGH SCHOOL DEPARTMENT
INSTRUCTIONAL MODULE
COMPUTER PROGRAMMING
2nd SEMESTER, S.Y. 2019 - 2020

TOPIC : JAVA CONDITIONAL STATEMENTS

LEARNING OBJECTIVES : The learners shall able to:

1. Create a program using the Java conditional statements

CONTENT:

Java Conditions and If Statements


Java supports the usual logical conditions from mathematics:

• Less than: a < b


• Less than or equal to: a <= b
• Greater than: a > b
• Greater than or equal to: a >= b
• Equal to a == b
• Not Equal to: a != b

You can use these conditions to perform different actions for different decisions.

Java has the following conditional statements:

• Use if to specify a block of code to be executed, if a specified condition is true


• Use else to specify a block of code to be executed, if the same condition is false
• Use else if to specify a new condition to test, if the first condition is false
• Use switch to specify many alternative blocks of code to be executed

The if Statement

Use the if statement to specify a block of Java code to be executed if a condition is true.

Syntax

if (condition) {

// block of code to be executed if the condition is true

Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.

In the example below, we test two values to find out if 20 is greater than 18. If the condition is true, print some text:

public class MyClass {


public static void main(String[] args) {
if (20 > 18) {
System.out.println("20 is greater than 18"); // obviously
}
}
}

OUTPUT:

20 is greater than 18
Prepared by: MS. KARLA A. LIDRES
Silay Institute, Inc.
SILAY CITY
SENIOR HIGH SCHOOL DEPARTMENT
INSTRUCTIONAL MODULE
COMPUTER PROGRAMMING
2nd SEMESTER, S.Y. 2019 - 2020

The else Statement


Use the else statement to specify a block of code to be executed if the condition is false.

Syntax

if (condition) {

// block of code to be executed if the condition is true

} else {

// block of code to be executed if the condition is false

public class MyClass {


public static void main(String[] args) {
int time = 20;
if (time < 18) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
}
}

Output
Good evening.

The else if Statement


Use the else if statement to specify a new condition if the first condition is false.

Syntax
if (condition1) {

// block of code to be executed if condition1 is true

} else if (condition2) {

// block of code to be executed if the condition1 is false and condition2 is true

} else {

// block of code to be executed if the condition1 is false and condition2 is false

Prepared by: MS. KARLA A. LIDRES


Silay Institute, Inc.
SILAY CITY
SENIOR HIGH SCHOOL DEPARTMENT
INSTRUCTIONAL MODULE
COMPUTER PROGRAMMING
2nd SEMESTER, S.Y. 2019 - 2020

public class MyClass {


public static void main(String[] args) {
int time = 22;
if (time < 10) {
System.out.println("Good morning.");
} else if (time < 20) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
}
}
Output:
Good evening.

Short Hand If...Else (Ternary Operator)


There is also a short-hand if else, which is known as the ternary operator because it consists of three operands. It
can be used to replace multiple lines of code with a single line. It is often used to replace simple if else statements:

Syntax
Example

variable = (condition) ? expressionTrue : expressionFalse;

public class MyClass {


public static void main(String[] args) {
int time = 20;
String result;
result = (time < 18) ? "Good day." : "Good evening.";
System.out.println(result);
}
}
Output:

Good evening.

Java Switch Statements


Use the switch statement to select one of many code blocks to be executed.

Syntax
switch(expression) {

case x:

// code block

Prepared by: MS. KARLA A. LIDRES


Silay Institute, Inc.
SILAY CITY
SENIOR HIGH SCHOOL DEPARTMENT
INSTRUCTIONAL MODULE
COMPUTER PROGRAMMING
2nd SEMESTER, S.Y. 2019 - 2020

break;

case y:

// code block

break;

default:

// code block

This is how it works:

• The switch expression is evaluated once.


• The value of the expression is compared with the values of each case.
• If there is a match, the associated block of code is executed.
• The break and default keywords are optional

Sample Program:
public class MyClass {
public static void main(String[] args) {
int day = 4;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
}
}
}
Output:
Thursday
Prepared by: MS. KARLA A. LIDRES
Silay Institute, Inc.
SILAY CITY
SENIOR HIGH SCHOOL DEPARTMENT
INSTRUCTIONAL MODULE
COMPUTER PROGRAMMING
2nd SEMESTER, S.Y. 2019 - 2020

The break Keyword


When Java reaches a break keyword, it breaks out of the switch block.

This will stop the execution of more code and case testing inside the block.

When a match is found, and the job is done, it's time for a break. There is no need for more testing.

A break can save a lot of execution time because it "ignores" the execution of all the rest of the code in the switch
block.

The default Keyword


The default keyword specifies some code to run if there is no case match:

Sample Program:

public class MyClass {


public static void main(String[] args) {
int day = 4;
switch (day) {
case 1:
System.out.println("Today is Saturday");
break;
case 2:
System.out.println("Today is Sunday");
break;
default:
System.out.println("Looking forward to the Weekend");
}
}
}

Output:

Looking forward to the Weekend

Loops
Loops can execute a block of code as long as a specified condition is reached.

Loops are handy because they save time, reduce errors, and they make code more readable.

Java While Loop

The while loop loops through a block of code as long as a specified condition is true:

Prepared by: MS. KARLA A. LIDRES


Silay Institute, Inc.
SILAY CITY
SENIOR HIGH SCHOOL DEPARTMENT
INSTRUCTIONAL MODULE
COMPUTER PROGRAMMING
2nd SEMESTER, S.Y. 2019 - 2020

Syntax

while (condition) {

// code block to be executed

In the example below, the code in the loop will run, over and over again, as long as a variable (i) is less than 5:

Sample Program:
public class MyClass {
public static void main(String[] args) {
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
}
}
Output:
0
1
2
3
4

The Do/While Loop


The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the
condition is true, then it will repeat the loop as long as the condition is true.

Syntax
do {

// code block to be executed

while (condition);

Prepared by: MS. KARLA A. LIDRES


Silay Institute, Inc.
SILAY CITY
SENIOR HIGH SCHOOL DEPARTMENT
INSTRUCTIONAL MODULE
COMPUTER PROGRAMMING
2nd SEMESTER, S.Y. 2019 - 2020

The example below uses a do/while loop. The loop will always be executed at least once, even if the condition is
false, because the code block is executed before the condition is tested:

Sample Program

public class MyClass {


public static void main(String[] args) {
int i = 0;
do {
System.out.println(i);
i++;
}
while (i < 5);
}
}
Output:
0
1
2
3
4
Do not forget to increase the variable used in the condition, otherwise the loop will never end!

Java For Loop


When you know exactly how many times you want to loop through a block of code, use the for loop instead of
a while loop:

Syntax
for (statement 1; statement 2; statement 3) {

// code block to be executed

Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.

Prepared by: MS. KARLA A. LIDRES


Silay Institute, Inc.
SILAY CITY
SENIOR HIGH SCHOOL DEPARTMENT
INSTRUCTIONAL MODULE
COMPUTER PROGRAMMING
2nd SEMESTER, S.Y. 2019 - 2020

The example below will print the numbers 0 to 4:

public class MyClass {


public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
}
}
Output:
0
1
2
3
4

For-Each Loop
There is also a "for-each" loop, which is used exclusively to loop through elements in an array:

Syntax
for (type variableName : arrayName) {

// code block to be executed

The following example outputs all elements in the cars array, using a "for-each" loop:

Example
public class MyClass {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
System.out.println(i);
}
}
}
Output:
Volvo
BMW
Ford
Mazda

Prepared by: MS. KARLA A. LIDRES


Silay Institute, Inc.
SILAY CITY
SENIOR HIGH SCHOOL DEPARTMENT
INSTRUCTIONAL MODULE
COMPUTER PROGRAMMING
2nd SEMESTER, S.Y. 2019 - 2020

Think and Pair Task

1. Use a for loop to print "Yes" 5 times:

(int i = 0; i < 5; ){
System.out.println( );
}

2. Print "Hello World" if x is greater than y.

int x = 50;
int y = 10;
(x y) {
System.out.println("Hello World");
}

3. Complete the switch statement, and add the correct keyword at the end to specify some code to run if there is
no case match in the switch statement.

int day = 4;
switch ( ){
1:
System.out.println("Saturday");
break;
2:
System.out.println("Sunday");
;
:
System.out.println("Weekend");
}

Prepared by: MS. KARLA A. LIDRES


Silay Institute, Inc.
SILAY CITY
SENIOR HIGH SCHOOL DEPARTMENT
INSTRUCTIONAL MODULE
COMPUTER PROGRAMMING
2nd SEMESTER, S.Y. 2019 - 2020

4. If n is an integer greater than 0, how many times is boohoo() executed in the following code segment?

Enrichment:
1. Explain why the following program cannot be compiled successfully.

Prepared by: MS. KARLA A. LIDRES


Silay Institute, Inc.
SILAY CITY
SENIOR HIGH SCHOOL DEPARTMENT
INSTRUCTIONAL MODULE
COMPUTER PROGRAMMING
2nd SEMESTER, S.Y. 2019 - 2020

TOPIC : ARRAY
LEARNING OBJECTIVES : The learners shall able to:
1. Define, initialize and use one dimensional as well as multidimensional arrays correctly.
2. Write code to sort array elements in any orders desired.
3. Write code to search elements in array.
CONTENT:

Java Arrays
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.

To declare an array, define the variable type with square brackets:

String[] cars;

We have now declared a variable that holds an array of strings. To insert values to it, we can use an array literal -
place the values in a comma-separated list, inside curly braces:

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

To create an array of integers, you could write:

int[] myNum = {10, 20, 30, 40};

Access the Elements of an Array


You access an array element by referring to the index number.

This statement accesses the value of the first element in cars:

Example
public class MyClass {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars[0]);
}
}
Output
Volvo

Note: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.

Prepared by: MS. KARLA A. LIDRES


Silay Institute, Inc.
SILAY CITY
SENIOR HIGH SCHOOL DEPARTMENT
INSTRUCTIONAL MODULE
COMPUTER PROGRAMMING
2nd SEMESTER, S.Y. 2019 - 2020

Change an Array Element


To change the value of a specific element, refer to the index number:

Example
cars[0] = "Opel";

public class MyClass {


public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
System.out.println(cars[0]);
}
}

Output

Opel

Array Length
To find out how many elements an array has, use the length property:

public class MyClass {


public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars.length);
}
}

Output:
4

Loop Through an Array


You can loop through the array elements with the for loop, and use the length property to specify how many times
the loop should run.The following example outputs all elements in the cars array:
public class MyClass {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.length; i++) {
System.out.println(cars[i]);
}
}
}

Prepared by: MS. KARLA A. LIDRES


Silay Institute, Inc.
SILAY CITY
SENIOR HIGH SCHOOL DEPARTMENT
INSTRUCTIONAL MODULE
COMPUTER PROGRAMMING
2nd SEMESTER, S.Y. 2019 - 2020

Output:
Volvo
BMW
Ford
Mazda

Loop Through an Array with For-Each


There is also a "for-each" loop, which is used exclusively to loop through elements in arrays:

Syntax
for (type variable : arrayname) {

...

The following example outputs all elements in the cars array, using a "for-each" loop:

public class MyClass {


public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
System.out.println(i);
}
}
}

Output:
Volvo
BMW
Ford
Mazda

The example above can be read like this: for each String element (called i - as in index) in cars, print out the value of i.

If you compare the for loop and for-each loop, you will see that the for-each method is easier to write, it does not
require a counter (using the length property), and it is more readable.

Multidimensional Arrays
A multidimensional array is an array containing one or more arrays.

To create a two-dimensional array, add each array within its own set of curly braces:

Prepared by: MS. KARLA A. LIDRES


Silay Institute, Inc.
SILAY CITY
SENIOR HIGH SCHOOL DEPARTMENT
INSTRUCTIONAL MODULE
COMPUTER PROGRAMMING
2nd SEMESTER, S.Y. 2019 - 2020

Example
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

myNumbers is now an array with two arrays as its elements.

To access the elements of the myNumbers array, specify two indexes: one for the array, and one for the element
inside that array. This example accesses the third element (2) in the second array (1) of myNumbers:

Example
public class MyClass {
public static void main(String[] args) {
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
int x = myNumbers[1][2];
System.out.println(x);
}
}
Output:
7

We can also use a for loop inside another for loop to get the elements of a two-dimensional array (we still have to
point to the two indexes):

public class MyClass {


public static void main(String[] args) {
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
for (int i = 0; i < myNumbers.length; ++i) {
for(int j = 0; j < myNumbers[i].length; ++j) {
System.out.println(myNumbers[i][j]);
}
}
}
}
Output:
1
2
3
4
5
6
7

Prepared by: MS. KARLA A. LIDRES


Silay Institute, Inc.
SILAY CITY
SENIOR HIGH SCHOOL DEPARTMENT
INSTRUCTIONAL MODULE
COMPUTER PROGRAMMING
2nd SEMESTER, S.Y. 2019 - 2020

Think and Pair Task

1. Print the second item in the cars array.

String[] cars = {"Volvo", "BMW", "Ford"};


System.out.println( );

2. Find out how many elements the cars array have.

String[] cars = {"Volvo", "BMW", "Ford"};


System.out.println( );

3. Show how to declare variables corresponding to the following:


a. An array of int.
b. An array of boolean.
c. An array of String.
d. An array of arrays of double.

Enrichment:
1. Explain why the following code segment lead to a failed compilation.

Prepared by: MS. KARLA A. LIDRES


Silay Institute, Inc.
SILAY CITY
SENIOR HIGH SCHOOL DEPARTMENT
INSTRUCTIONAL MODULE
COMPUTER PROGRAMMING
2nd SEMESTER, S.Y. 2019 - 2020

TOPIC : METHODS
LEARNING OBJECTIVES : The learners shall able to:
1. Define new methods and use them correctly.
2. Understand the process of method invocation
CONTENT:

Java Arrays
A method is a block of code which only runs when it is called.

You can pass data, known as parameters, into a method.

Methods are used to perform certain actions, and they are also known as functions.

Why use methods? To reuse code: define the code once, and use it many times.

Create a Method
A method must be declared within a class. It is defined with the name of the method, followed by parentheses ().
Java provides some pre-defined methods, such as System.out.println(), but you can also create your own methods to
perform certain actions:

Example
Create a method inside MyClass:

public class MyClass {

static void myMethod() {

// code to be executed

Example Explained

• myMethod() is the name of the method


• static means that the method belongs to the MyClass class and not an object of the MyClass class. You will
learn more about objects and how to access methods through objects later in this tutorial.
• void means that this method does not have a return value

Prepared by: MS. KARLA A. LIDRES


Silay Institute, Inc.
SILAY CITY
SENIOR HIGH SCHOOL DEPARTMENT
INSTRUCTIONAL MODULE
COMPUTER PROGRAMMING
2nd SEMESTER, S.Y. 2019 - 2020

Call a Method
To call a method in Java, write the method's name followed by two parentheses () and a semicolon;

In the following example, myMethod() is used to print a text (the action), when it is called:

Example
Inside main, call the myMethod() method:
public class MyClass {
static void myMethod() {
System.out.println("I just got executed!");
}

public static void main(String[] args) {


myMethod();
}
}
Output:

I just got executed!

A method can also be called multiple times:

Example
public class MyClass {
static void myMethod() {
System.out.println("I just got executed!");
}

public static void main(String[] args) {


myMethod();
myMethod();
myMethod();
}
}
Output:
I just got executed!
I just got executed!
I just got executed!

Prepared by: MS. KARLA A. LIDRES


Silay Institute, Inc.
SILAY CITY
SENIOR HIGH SCHOOL DEPARTMENT
INSTRUCTIONAL MODULE
COMPUTER PROGRAMMING
2nd SEMESTER, S.Y. 2019 - 2020

Think and Pair Task

1.Insert the missing part to call myMethod from main.

static void myMethod() {


System.out.println("I just got executed!");
}

public static void main(String[] args) {


;
}

2.Insert the missing part to call myMethod from main two times.

static void myMethod() {


System.out.println("I just got executed!");
}

public static void main(String[] args) {


;
;
}

3. Explain the benefits of having a program perform some sets of instruction inside methods. Can you think of any
downsides of doing so?

Enrichment
1. Determine the output of the following code segment.

Prepared by: MS. KARLA A. LIDRES

Potrebbero piacerti anche