Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
SILAY CITY
SENIOR HIGH SCHOOL DEPARTMENT
INSTRUCTIONAL MODULE
COMPUTER PROGRAMMING
2nd SEMESTER, S.Y. 2019 - 2020
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.
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.
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
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.
TERMINAL
PROCESS
DECISION
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
Relational Operators
= equal
> greater than
< less than
=! Not equal
>= greater than or equal to
<= less than or equal to
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.
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
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.
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.
• 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.
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.
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 {
juice.size = FreshJuice.FreshJuiceSize.MEDIUM ;
System.out.println("Size: " + juice.size);
}
}
Size: MEDIUM
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.
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.
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.
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.
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.
String breed;
int ageC;
String color;
void barking(){
}
void hungry(){
}
void sleeping(){
}
}
• 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
Example
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:
Output:
The length of the txt string is: 26
String Methods
There are many string methods available, for example toUpperCase() and toLowerCase():
Output
HELLO WORLD
hello world
The indexOf() method returns the index (the position) of the first occurrence of a specified text in a string (including
whitespace):
Output:
7
String Concatenation
The + operator can be used between strings to combine them. This is called concatenation:
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) {
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:
\\ \ Backslash
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:
class MyClass {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
String 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
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);
// String input
String name = myObj.nextLine();
// Numerical input
int age = myObj.nextInt();
double salary = myObj.nextDouble();
Output
1. Use the correct method to print the length of the txt string.
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
CONTENT:
You can use these conditions to perform different actions for different decisions.
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) {
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:
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
Syntax
if (condition) {
} else {
Output
Good evening.
Syntax
if (condition1) {
} else if (condition2) {
} else {
Syntax
Example
Good evening.
Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
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
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.
Sample Program:
Output:
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.
The while loop loops through a block of code as long as a specified condition is true:
Syntax
while (condition) {
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
Syntax
do {
while (condition);
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
Syntax
for (statement 1; statement 2; statement 3) {
Statement 1 is executed (one time) before the execution of the code block.
Statement 3 is executed (every time) after the code block has been executed.
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) {
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
(int i = 0; i < 5; ){
System.out.println( );
}
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");
}
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.
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.
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:
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.
Example
cars[0] = "Opel";
Output
Opel
Array Length
To find out how many elements an array has, use the length property:
Output:
4
Output:
Volvo
BMW
Ford
Mazda
Syntax
for (type variable : arrayname) {
...
The following example outputs all elements in the cars array, using a "for-each" loop:
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:
Example
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
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):
Enrichment:
1. Explain why the following code segment lead to a failed compilation.
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.
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:
// code to be executed
Example Explained
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!");
}
Example
public class MyClass {
static void myMethod() {
System.out.println("I just got executed!");
}
2.Insert the missing part to call myMethod from main two times.
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.