0% found this document useful (0 votes)
2K views29 pages

Introduction To Programming (JAVASCRIPT) PDF

The document provides an introduction to programming concepts including software classification, programming vs programs, and the programming life cycle. It discusses application software, system software, language processors, interpreters, compilers, and the 5 steps of the programming life cycle: defining the problem, planning the solution, coding the solution, checking the program, and implementation and feedback. It also defines algorithms, flowcharts, operators, and basic logic structures used in programming.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
2K views29 pages

Introduction To Programming (JAVASCRIPT) PDF

The document provides an introduction to programming concepts including software classification, programming vs programs, and the programming life cycle. It discusses application software, system software, language processors, interpreters, compilers, and the 5 steps of the programming life cycle: defining the problem, planning the solution, coding the solution, checking the program, and implementation and feedback. It also defines algorithms, flowcharts, operators, and basic logic structures used in programming.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 29

LESSON 1

INTRODUCTION TO PROGRAMMING

Software and Classification of Software

Software refers to any computer program or instructions that cause the hardware to work.

Classification of Software
 Application Software – is a computer program people use to get their work done.
o Example: Word Processors, Spreadsheets
 System Software – is a program needed to keep all the hardware and software systems running together
smoothly.
o Example: Operating Systems (Microsoft, Unix), Language Processors
Language Processors – Software that converts computer Languages into machine readable form.
 It is a standardized communication technique for expressing instructions to a computer. Like human
languages, each language has its own syntax/format and grammar.
Interpreter – It is system software that converts the instructions into machine code line by line.
Compiler – Converts the whole program into machine code at once.

Computer Programming
The process of developing and implementing various sets of instructions to enable a computer to do a certain
task. These instructions are considered computer programs and help the computer to operate smoothly.
(businessdictionary.com)
Computer Programming is a process that leads from an original formulation of a computing problem to executable
programs. It involves activities such as analysis, understanding, and generically solving such problems resulting in an
algorithm, verification of requirements of the algorithm including its correctness and its resource consumption,
implementation (commonly referred to as coding) of the algorithm in a target programming language, testing, debugging,
and maintaining the source code, implementation of the build system and management of derived artifacts such as
machine code of computer programs.

Programming VS Program
A program is a set of commands that instructs a computer to perform a specific commands. Programming then is the
process of formulating and organizing these commands for a computer to understand, perform, and execute.

Programming Life Cycle


Program Life Cycle is a process by which a programmer follows to obtain a good and effective program.

5 Steps of Programming Life Cycle


1. Defining the Problem
2. Planning the Solution
3. Coding the Solution
4. Checking the Program
5. Implementation and Feedback

1. Defining the Problem


-answers: “What has to be Done?”
-understand the problem & careful analysis
-know exactly what the program will do before it is written

2. Planning the solution


-select the best method in solving the problem
-make a program flowchart
-select an appropriate programming language

3. Coding the Solution


Convert the steps depicted in the program flowchart into readable instructions that make up the actual program.
4. Checking the Program
Debugging is tracing the program step by step to eliminate big or small errors.
It is the task of finding errors (bugs) and correcting them so that the program runs correctly.
Testing is running the program with input data.

Types of errors:
Clerical Error – occurs in the coding or data entry process
Logical Error – occurs when the program runs well but the output is erroneous.

5. Implementation and Feedback


The deployment of the system includes changes, enhancements and maintenance.
Once the program begins, feedback from clients begins.

ALGORITHM
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.
It is called a “recipe for solving problem”.

It can be in a form of
1. Human language (English, Tagalog)
2. Pseudocode - which is a cross between human language and a programming language
3. Flowchart

Flowchart
A diagram representing the logical sequence in which a combination of steps or operations is to be performed.
It is a 2-dimensional representation of an algorithm.

Flowcharting Symbol
1. Terminal Symbol (oval) – used to designate the beginning and the end of a program.
START END

2. Input/Output Symbol (parallelogram) – represents an instruction to an input/output device.

Input Display Display


x “GOOD” X

3. Processing Symbol (rectangle) – represents a group of program instructions that perform a processing function of
the program.

sum = a + b p=a*b

4. Flow Lines (line) – connects each symbol together.

5. Flow Direction Indicators (arrowheads) – used to show the direction of processing or data flow.

2 Multiple Income Creating Project (MIC P) on ICT


6. Decision Symbol (diamond) – a point in the program where more than one path can be taken.

Y If N
x = 0?

7. On-Page Connector (small circle) – used to connect one part of a flowchart to another without drawing flow lines
within the same page.

A A

8. Off-Page Connector (small pentagon) – designate entry to or exit from a page when a flowchart requires more
than one page.
B
B

Solving a Problem using Flowchart


Problem:
Create a flowchart that will ask for two numbers. Compute and display the sum.

Pseudocode:

1. Ask for the value for variable x


2. Ask for the value for variable y
3. Compute for the sum of the values given
to x and y then store it to variable sum (
sum = x + y )
4. Display the value of the variable sum

Operators
Arithmetic Operator
These are the operators used in performing simple mathematical operations.

* Multiply values of operands a=x*y


/ Divide values of operands a=x/y
+ Adds values of operands a=x+y
- Subtract values of operands a=x-y
% Modulus operator to get the remainder a=b%2
of a division process
() Used for grouping equations / operations

Relational Operator

Multiple Income Creating Project (MIC P) on ICT 3


These are operators used to compare relative values. These are commonly used in the IF statement and loop
statement.

> Greater than x>5


< Less than y<5
>= Greater than or equal num1 >= x
<= Less than or equal p <= 10
== Equal L == 2
!= Not Equal r != 2

Logical Operator
These are operators used to show how two or more quantities are connected together using the rules of logic.

&& AND if(grade >= 90 && grade <= 100)


|| OR x > 2 || x < 10
! NOT if(! (c < 20 ))

Truth Table

AND OR
x y Result X y Result

F F F F F F

F T F F T T

T F F T F T

T T T T T T

Mathematical Equation to Programming Notation


Do you still remember translating math equation to programming notation? All math equation must be written in linear
form.

Example:
1. A x C  A*C
2. ab+2y  a*b+2*y
3. X + Y  (X + Y) / Z
Z
4. a2 + b3  a*a+b*b*b

Conversion Exercise:
Convert the following mathematical equation to programming notation.

1. c = a2 + b2

2. a=xyz

3. A= b + c
d

4. X = 2 3 +y
2

5. X = a – bc3

6. Z = 2x + 2b + 2x- 2b
Y A

4 Multiple Income Creating Project (MIC P) on ICT


7. A = 5 - 3x2 + 2y + 5a
4ab

8. C = 4x3 + 2y2 - 6a

9. N = b (2a + c) - 3b

10. X = y ( 2 ( 3b + 3 ) ) + y ( 4b + 2 ) – 7y2
5a+3 5b+5

BASIC LOGIC STRUCTURE


Programming is an organization of logical statements or instructions to provide solution. There are 3 basic logical
structure that are being used in programming:
 Sequential
 Branching
 Loop

Sequential
 Programs are linear in nature
 Instructions are executed based on its linear sequence
 Knowing this you must structure your program based on its logical ordering

Sample Problem:
Create a flowchart that will ask for two numbers. Compute and display the sum.

START

Pseudocode:
Input x, y

1. Ask for the value for variable x


2. Ask for the value for variable y
sum = x + y 3. Compute for the sum of the values given to x and
y then store it to variable sum ( sum = x + y )
4. Display the value of the variable sum

Display sum

END

**Note: You can use Human language Pseudocode (English, Filipino, own dialect (waray/bisaya)) if you think it will help
you understand more the problem to create a flowchart.
Exercise:
1. Create a flowchart that will ask for 5 quizzes grades then compute and display the average.
2. Create a flowchart that will ask for the radius of a circle then compute and display the area of the circle.
3. Create a flowchart that will ask for feet value then convert it to equivalent inches value.
1 ft = 12 in
4. Create a flowchart that will ask for the length and the width of a rectangle then compute and display the perimeter.
5. ABC Sari-sari Store wants to make their sales transaction be computerized. Given the following requirements
create a flowchart for the new sales transactions flow.
Input: 5 items prices, discount, cash
Output: Total amount to Pay (less discount amount), change
Multiple Income Creating Project (MIC P) on ICT 5
Branching / Selection
A programming instruction that directs the computer to another part of the program based on the results of comparison.
When an "Algorithm" makes a choice to do one of two (or more things) this is called branching.

Sample Problem:
Create a flowchart that will ask for two numbers and display the larger number.
START

Input x, y Pseudocode:

1. Ask for the value for variable x


N 2. Ask for the value for variable y
If
x>y Display y 3. If x > y
Display the value of variable x
Y Else
Display the value of variable y
End if
Display x

END

Exercise:
1. Create a flowchart that will ask for a grade then evaluate and display the grade status whether “PASSED” or
“FAILED”
2. Create a flowchart will ask for an age then evaluate the age if it is a qualifying age to vote or not.
3. Create a flowchart that will ask for two numbers. If the first number is greater than the second number compute
and display the sum otherwise compute and display the product of the numbers.
4. Create a flowchart that will ask for a number then determine if the number is Positive, Negative or Zero.
5. Create a flowchart that will ask for a number then determine if the number is Odd or Even number.
6. Create a flowchart that will ask for a grade then display the equivalent remarks
Grade Remarks
100-91 Excellent
90-81 Very Good
80-71 Good
70-51 Fair
50-0 Poor
Out of range Invalid

7. ABC Sari-sari store wants to automate their employees’ salary computation to have faster and efficient process.
Salary is given in a weekly basis. 40 hours in a week and beyond that is considered as overtime. Overtime pay
(per hour) is 150% of the hourly rate of an employee. Your goal is to create a flowchart with the given
requirements:
Input: rate per hour, number of hours worked in a week
Output: Overtime pay, Total salary

6 Multiple Income Creating Project (MIC P) on ICT


Loop / Iteration
In cases that certain instructions or processes are repeated the programming language has a way through that by making
use of loops.

Sample Problem
Create a flowchart that will display numbers form 1 - 10.

START
Pseudocode:

1. Initialize the variable c to 1


c=1 2. while c > 10
Display the value of variable c
Increment the variable c by 1
Go back to step 2
Y End of while
If
c <= 10 Display c c=c+1

END

Exercise
1. Create a flowchart that will display the numbers from 1-20.
2. Create a flowchart that will display the numbers from 20-1.
3. Create a flowchart that will ask for 10 numbers then compute and display the sum and average of the inputted
numbers.
4. Create a flowchart that will ask for numbers until a negative number is inputted.
5. Create a flowchart that will ask for N number then display the numbers from 1 to N.
6. Create a flowchart that will ask for 20 numbers then count the Positive, negative and zero inputted values.
7. Create a flowchart that will ask for 15 numbers then count the number of Odd and Even numbers.
8. ABC Sari-sari store wants to upgrade their sales transactions. Items is now unlimited instead of 5 items only,
calculates discount (if any), and checks sufficiency of cash tendered (input again if not sufficient).
Input: item price, quantity, discount (if any), cash (checks of sufficient)
Output: Total amount (less discount), Change

Multiple Income Creating Project (MIC P) on ICT 7


LESSON 2

JAVASCRIPT FUNDAMENTALS
What is JavaScript?

JavaScript started life as LiveScript, but Netscape change the name, possibly because of the excitement being generated
by Java to JavaScript. JavaScript made its first appearance in Netscape 2.0 in 1995 with a name LiveScript.

JavaScript is a lightweight, interpreted programming language with object-oriented capabilities that allows you to build
interactivity into otherwise static HTML pages.

The general-purpose core of the language has been embedded in Netscape, Internet Explorer, and other web browsers.

JavaScript is:
 A lightweight, interpreted programming language
 Complementary to and integrated with Java
 Complementary to and integrated with HTML
 Open and cross-platform

Client-side JavaScript

Client-side JavaSript is the most common form of the language. The script should be included in or referenced by an
HTML document for the code to be interpreted by the browser.

It means that a web page need no longer be static HTML, but can include programs that interact with the user, control the
browser, and dynamically create HTML content.

The JavaScript client-side mechanism features many advantages over traditional Common Gateway Interface (CGI)
server-side scripts. For example, you might use JavaScript to check if the user has entered a valid e-mail address in a
form field.

The JavaScript code is executed when the user submits the form, and only if all the entries are valid they would be
submitted to the Web Server.

JavaScript can be used to trap user-initiated events such as button clicks, link navigation, and other actions that the
explicitly or implicitly initiates.

Advantages of JavaScript:

The merit of using JavaSript are:

 Less server interaction: You can validate user input before sending the page off to the server. This saves server
traffic, which means less load in your server.

 Immediate feedback to the visitors: They don’t have to wait for a page reload to see if they have forgotten to enter
something.

 Increase interactivity: You can create interfaces that react when the user hovers over then with a mouse or
activates them via the keyboard.

 Richer interfaces: You can use JavaScript to include such items as drag-and-drop components and sliders to give
a Rich Interface to your site visitors.

8 Multiple Income Creating Project (MIC P) on ICT


Once again, JavaScript is a lightweight, interpreted programming language that allows you to build interactivity into
otherwise static HTML pages.

JavaScript Syntax
Scripts in HTML must be inserted between <script> and </script> tags.
Scripts can be put in the <body> and in the <head> section of an HTML page.

A JavaScript consists of JavaScript statements that are placed within the <script>…</script> HTML tags in a web page.

The <script> Tag


To insert a JavaScript into an HTML page, use the <script> tag.
The <script> and </script> tells where the JavaScript starts and ends.
The <script> tag alert the browser program to begin interpreting all the text between these tags as a script.
The lines between the <script> and </script> contain the JavaScript:

<script>
JavaScript code…
</script>

The browser will interpret and execute the JavaScript code between the <script> and </script> tags.

The script tag takes two important attributes:

 Language: This attribute specifies what scripting language you are using. Typically, its value will be JavaScript.
Although recent versions of HTML (and XHTML, its successor) have phased out the use of this attribute.

 Type: This attribute is what is now recommended to indicate the scripting language in use and its value should be
set to “text/javascript”.

Old example may have type=”text/javascript” in the <script> tag. This is no longer required. JavaScript is the default
scripting language in all modern browsers and in HTML5.

JavaScript in <head> or <body>


You can place an unlimited number of scripts in an HTML document.

Scripts can be in the <body> or in the <head> section of HTML, and/or in both. But for this training we will focus only on
JavaScript codes.

JavaScript in <body> and <head>


In this example, JavaScript writes into the HTML <head> and <body> while the page loads:
Example:

<html>
<head>
<title>JavaScript</title>
<script>
document.write(“JAVASCRIPT”);
</script>
</head>
<body>
<script>
document.write(“<h1>My First JavaScript</h1>”);
document.write(“<p>Hello World!</p>”);
</script>
</body>
</html>

Multiple Income Creating Project (MIC P) on ICT 9


Output:

For this training, let’s omit the other HTML tags and leave only the <script> tag and its content. Use <br> tag to create a
new line.

<script>
document.write(“JAVASCRIPT<br>”);
document.write(“My First JavaScript <br>”);
document.write(“Hello World!<br>”);
</script>

Writing your fist Program

Step 1: Open text editor or notepad


Step 2: Type the above code
Step 3: Save your file in your folder and name it to sample.html

Opening your File

Step 1: Open Windows Explorer (Ctrl + E)


Step 2: Locate your file
Step 3: Double-click your file or Open with Web Browser

Case Sensitive
JavaScript is a case-sensitive language. This means that language keywords, variables, function names, and any other
identifiers must always be typed with a consistent capitalization of letters.

Note: Care should be taken while writing your variable and function names in JavaScript.

Comment in JavaScript
JavaScript supports both C-style and C++ style comments, thus:

Any text between a // and the end of a line is treated as a comment and is ignored by JavaScript.

Any text between the characters /* and */ is treated as a comment. This may span multiple lines.

JavaScript also recognized the HTML comment opening sequence <!--. JavaScript treats this as a single-line comment,
just as it does the // comment.

The HTML comment closing sequence --> is not recognized by JavaScript so it should be written as //-->.

Example:

<script>

10 Multiple Income Creating Project (MIC P) on ICT


// This is a comment. It is similar to comments in C++

/* This is a multiline comment in JavaScript


It is very similar to comments in C Programming
*/

<!-- This is a comment. //-->

</script>

Exercise: Writing Document Output


Create a web page that will display your full name, school, year level and section, address, likes and dislikes, and
description of yourself. Use document.write() function.

JavaScript Variables
As with algebra, JavaScript variables can be used to hold values (x=5) or expressions (z=x+y).

Variable can have short names (like x and y) or more descriptive names (age, sum, totalvolume)

 Variable names must begin with a letter


 Variable names are case sensitive (y and Y are different variables)
 Variable names must not be a reserve word ( words used by the programming language as a function like if, else,
for, var etc.)

Both JavaScript statements and JavaScript variables are case-sensitive.

JavaScript Keywords

break finally this


case for throw
catch function true
continue if try
debugger in typeof
default instanceof var
delete new void
do null while
else return with
false switch

Browser Keywords
alert innerHeight outerWidth
blur innerWidth parent
closed length screen
document location screenX
focus navigator screenY
frames open Statusbar
history outerHeight windo

Scope
The scope of an identifier is either

Multiple Income Creating Project (MIC P) on ICT 11


 Global – An identifier that is accessible anywhere on the page
 Local – Is accessible only within the function it is declared within

A global variable is typically declared simply by assigning a value to it.

globalVariable = 100;

A local variable is declared within a function using the var keyword.

globalVariable = 100;

function someFunction() {
var counter = 0;
}

The identifier, counter, is local to the function and can only be used in that function. However, the identifier,
globalVariable, is not preceded by the var keyword and is thus a global variable that can be used anywhere on the page,
inside or outside of the function.

JavaScript Data Types


There are six data types in JavaScript :

 Numbers – Integer or floating point numbers


 Booleans – Either true/false or a number (0 being false) can be used for boolean values
 Strings – Sequence of characters enclosed in a set of single or double quotes
 Objects – Entities that typically represents elements of a HTML page
 Null – No value assigned which is different from a 0
 Undefined – Is a special value assigned to an identifier after it has been declared but before a value has been
assigned to it

JavaScript is a dynamically typed language. The data type of the identifier is not assigned when the identifier is declared.
When a value is assigned to the identifier the identifier takes on that type. The data type of the variable is not important
until an operator is applied to the variable. The behavior of the operator is dependent of the data type being acted upon.

For example:
var name = “Sally”;
name = 34;

The string, Sally, is first assigned to the variable. Next, the integer 34 is assigned to the variable. Both are legal but usage
of the identifier is inconsistent. It is better if we are consistent when assigning a data type to a variable. This leads to less
confusing code.

Variable exercise:
Evaluate the following variable name whether valid or invalid.

1. Sum
2. 10percent
3. Street no
4. #five
5. num1
6. if
7. studentno.
8. 2num
9. average_of_a_b
10. product_of_x&y

JavaScript Operator
Operators are symbols that perform specific mathematical, relational or logical manipulation.

12 Multiple Income Creating Project (MIC P) on ICT


Just like what we applied in flowcharting the same Arithmetic, Relational, and Logical operators will be used.

Sample Program
The program below will compute for the sum of the values of 2 variables.

<html>
<head>
<title>Sum of 2 Numbers </title>
</head>
<body>
<script>
var x=5, y=2;
var sum=x+y;
//display the values of the 2 numbers and the sum
document.write(“First number:” + x);
document.write(“<br>Second number: ” + y);
document.write(“<br>The sum is ” + sum);
</script>
</body>
</html>

Output

Exercise:
1. Create JavaScript program that will compute and display the sum, difference, product and quotient of two variables.

2. Create JavaScript program that will compute and display the square of a number.

3. Create JavaScript program that will compute the average of 3 quizzes grades. The program will display the 3 quizzes
grades including the average.

Using Prompt Box


Prompt box is one of the JavaScript Popup boxes that is used if you want the user to input a value. When a
prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value.
If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns null.

Syntax
window.prompt("sometext","defaultText");

The window.prompt() method can be written without the window prefix.

prompt("sometext","defaultText");

Sample:

<html>
<head>
<title>Using Prompt Box </title>

Multiple Income Creating Project (MIC P) on ICT 13


</head>
<body>
<script>

var name=prompt("Enter your name","Name");


document.write("Welcome " + name);

</script>
</body>
</html>

Output:

The value inputted in a Prompt box is treated as string. If you want to treat the input number as a number literal use
Number() to convert the prompt value to number

Example:

var x=Number(prompt(“Enter a number”, “”));

Exercises:
1. Create a program that will ask for a name then redisplay the inputted name.

2. Create a program that will ask for the score and number of items of a quiz. Compute and display the equivalent
grade using the formula grade=score / no. of items * 100.

3. Create a program that will ask for 5 quizzes grades then compute and display the average.

4. Create a program that will ask for the radius of a circle then compute and display the area of the circle.

5. Create a program that will ask for feet value then convert it to equivalent inches value.
1 ft = 12 in
6. Create a program that will ask for the length and the width of a rectangle then compute and display the perimeter.

14 Multiple Income Creating Project (MIC P) on ICT


7. ABC Sari-sari Store wants to make their sales transaction be computerized. Given the following requirements
create a program for the new sales transactions flow.
Input: 5 items prices, discount, cash
Output: Total amount to Pay (less discount amount), change

LESSON 3

CONTROL STRUCTURE
BRANCHING / CONDITIONAL STATEMENTS

Branching or Conditional Statements


As we had discussed in flowcharting, branching structure is a programming instruction that directs the computer to
another part of the program based on the results of comparison.

Conditional statements are used to perform different actions based on different conditions.

In JavaScript we have the following conditional statements:


 if statement - use this statement to execute some code only if a specified condition is true
 if...else statement - use this statement to execute some code if a condition is true and another code if the
condition is false
 if...elseif....else statement - use this statement to select one of several blocks of code to be executed
 switch statement - use this statement to select one of many blocks of code to be executed

The if Statement
Use the if statement to execute some code only if a specified condition is true.

Syntax
if (condition)
{
code to be executed if condition is true;
}

The example below will output “Positive" if number is greater than 0 (zero):

<script>
var num = 10;
if (num>0)
document.write(“Positive”);

</script>

Note: Notice that there is no ..else.. in this syntax. The code is executed only if the specified condition is true.
You may or may not put curly braces if there is only one statement in a block of code.

Multiple Income Creating Project (MIC P) on ICT 15


Coding Guidelines
To avoid confusion, always place the statement or statements of an if or if-else block inside curly braces {}.
You can have nested if-else blocks. This means that you can have other if-else blocks inside another if-else block.

The if...else Statement


Use the if....else statement to execute some code if a condition is true and another code if a condition is false.

Syntax
if (condition)
{
code to be executed if condition is true;
}
else
{
code to be executed if condition is false;
}

Example:
The example below will output "Positive" if the number is greater than 0 (zero), otherwise it will output "Negative":

<script>
var num = -10;
if (num>0){
document.write(“Positive”);
}
else{
document.write(“Negative”);
}
</script>

The if...elseif....else Statement


Use the if....elseif...else statement to select one of several blocks of code to be executed.

Syntax
if (condition)
{
code to be executed if condition is true;
}
else if (condition)
{
code to be executed if condition is true;
}
else
{
code to be executed if condition is false;
}

16 Multiple Income Creating Project (MIC P) on ICT


Example:
The sample program will output "Positive" if the number is greater than zero (0), and "Negative" if the number is less than
zero (0). Otherwise the output is “Zero” (0).

<script>
var num = 10;
if (num>0){
document.write(“Positive”);
}
else if (num<0){
document.write(“Negative”);
}
else{
document.write(“Zero”);
}
</script>

Common Errors
1. Writing elseif instead of else if.
2. Using = (single equal sign) instead of == (double equal sign) for comparison.
3. Missing curly brace ( { or } ) in compound statements.

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

Syntax
switch (n)
{
case value1:
code to be executed if n=value1;
break;
case value2:
code to be executed if n=value2;
break;
:
:

default:
code to be executed if n is
different from both value1 and value2;
}

This is how it works:

First we have a single expression n (most often a variable), that is evaluated once. The value of the expression is then
compared with the values for each case in the structure. If there is a match, the block of code associated with that case is
executed. Use break to prevent the code from running into the next case automatically. The default statement is used if
no match is found.

Multiple Income Creating Project (MIC P) on ICT 17


<script>
x=1;
switch (x)
{
case 1:
document.write(“ONE”);
break;
case 2:
document.write(“TWO”);
break;
case 3:
document.write(“THREE”);
break;
default:
document.write(“INVALID”);
}
</script>

Coding Guidelines
1. Deciding whether to use an if statement or a switch statement is a judgment call. You can decide which to use,
based on readability and other factors.
2. An if statement can be used to make decisions based on ranges of values or conditions, whereas a switch
statement can make decisions based only on a single integer or character value. Also, the value provided to each
case statement must be unique.

Exercises
1. Create a program that will determine if age is qualified to vote or not. Display “QUALIFIED” if age is qualified to vote,
otherwise display “NOT QUALIFIED”

2. Create a program that will determine if a number is Odd or Even number. The program will display the number and the
result.

3. Create a program that will ask for a number then determine if the number is Positive, Negative or Zero.

4. Create a program that will ask for a letter then determine if the letter is vowel or consonant.

5. Create a program that will ask for two numbers. If the first number is greater than the second number compute and
display the sum otherwise compute and display the product of the numbers.

6. Create a program that will ask for the score and number of items of a quiz then compute the equivalent grade with the
formula
grade = score / number of items * 100

evaluate the grade then display the grade classification according to the following:

100-91 Excellent
90-81 Very Good
80-71 Good
70-51 Fair
50-0 Poor
Out of range Invalid

7. ABC Sari-sari store wants to automate their employees’ salary computation to have faster and efficient process.
Salary is given in a weekly basis. 40 hours in a week and beyond that is considered as overtime. Overtime pay (per
hour) is 150% of the hourly rate of an employee. Your goal is to create a program with the given requirements:
Input: rate per hour, number of hours worked in a week
Output: Overtime pay, Total salary

18 Multiple Income Creating Project (MIC P) on ICT


LESSON 4

CONTROL STRUCTURE
LOOP / ITERATION
Loops execute a block of code a specified number of times, or while a specified condition is true.

Often when you write code, you want the same block of code to run over and over again in a row. Instead of adding
several almost equal lines in a script we can use loops to perform a task like this.

In JavaScript we have the following looping statements:


 while - loops through a block of code while a specified condition is true
 do...while - loops through a block of code once, and then repeats the loop as long as a specified condition is true
 for - loops through a block of code a specified number of times

A. The while Loop

The while loop executes a block of code while a condition is true.

Syntax
while (condition)
{
code to be executed;
}

Example
The example below first sets a variable i to 1 (i=1;).

Then, the while loop will continue to run as long as i is less than, or equal to 5. i will increase by 1 each time the loop runs:

<script>
i = 1;
while( i <= 5 )
{
document.write(“<br />The number is ”+ i);
i++;
}
</script>

Output:
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

B. The do-while Statement


The do-while statement will always execute the block of code once, it will then check the condition, and repeat the loop
while the condition is true.

Syntax
Do
{
code to be executed;
}
while (condition);

Multiple Income Creating Project (MIC P) on ICT 19


Example
The example below first sets a variable i to 1 ( i=1;).

Then, it starts the do...while loop. The loop will increment the variable i with 1, and then write some output. Then the
condition is checked (is i less than, or equal to 5), and the loop will continue to run as long as i is less than, or equal to 5:
<script>
i=1;
do
{
i++;
document.write(“<br />The number is ”+ i);
}while (i<=5);
</script>

Output:
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6

C. The for Loop


The for loop is used when you know in advance how many times the script should run.

Syntax
for (init; condition; increment)
{
code to be executed;
}
Parameters:
 init: Mostly used to set a counter (but can be any code to be executed once at the beginning of the loop)
 condition: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE,
the loop ends.
 increment: Mostly used to increment a counter (but can be any code to be executed at the end of the iteration)

Note: The init and increment parameters above can be empty or have multiple expressions (separated by commas).

Example
The example below defines a loop that starts with i=1. The loop will continue to run as long as the variable i is less than,
or equal to 5. The variable i will increase by 1 each time the loop runs:
<script>
for (i=1; i<=5; i++)
{
document.write(“<br />The number is ”+ i);
}
</script>

Output:
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

Exercises:

20 Multiple Income Creating Project (MIC P) on ICT


1. Create a program that will display the numbers from 1-20.
2. Create a program that will display the numbers from 20-1.
3. Create a program that will ask for 10 numbers then compute and display the sum of the inputted numbers.
4. Create a program that will ask for numbers until a negative number is inputted.
5. Create a program that will ask for 20 numbers then count the Positive, negative and zero inputted values.
6. Create a program that will ask for 15 numbers then count the number of Odd and Even numbers.
7. Create a program that will ask for N number then display the numbers from 1 to N.
8. ABC Sari-sari store wants to upgrade their sales transactions. Items is now unlimited instead of 5 items only,
calculates discount (if any), and checks sufficiency of cash tendered (input again if not sufficient).
Input: item price, quantity, discount (if any), cash (checks of sufficient)
Output: Total amount (less discount), Change

LESSON 5

Multiple Income Creating Project (MIC P) on ICT 21


JAVASCRIPT ARRAY

What is an Array?
An array stores multiple values in one single variable:
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:

cars1="Volvo";
cars2="BMW";
cars3="Toyota";

However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?
The solution is to create an array! An array can hold many values under a single name, and you can access the values by
referring to an index number.

Creating an Array
Using an array literal is the easiest way to create a JavaScript Array.

Syntax:
With constant values/elements
var array_name = [item1, item2, ...];

Example:
var cars = ["Saab", "Volvo", "BMW"];
or
var cars = [
“Saab”,
“Volvo”,
“BMW”
];

Empty Array
var array_name=[];

Example:
var cars=[];

Accessing the Elements of an Array


Index refers to the location or address of an element in an array. Index starts from zero [ 0 ].
Element refers to the content of the array.
You refer to an array element by referring to the index number.

The statement below access the value of the first element in array cars:
var name = cars[0];

The statement below modifies the first element in cars:


cars[0] = "Opel";

The statements below display the elements of array cars:

document.write(cars[0] +“,”+cars[1]+ “,”+cars[2]);

or

document.write(cars);

Output

22 Multiple Income Creating Project (MIC P) on ICT


Opel,Volvo,BMW

The length Property


The length property of an array returns the length of an array (the number of array elements).

Example:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.length; // the length of fruits is 4

Adding Array Elements


The easiest way to add a new element to an array is to use the length property:

Example:
var fruits = ["Banana", "Orange", "Apple","Mango"];

// adds a new element (Lemon) to fruits


// fruits[fruits.length] = "Lemon";

Loop Through an Array


To loop through and print all the values of an array, you could use a for loop like this:

Example
<script>
var cars=["Volvo","BMW","Toyota"];
arrlength=cars.length;
for(x=0; x < arrlength; x++)
{
document.write(cars[x]+ "<br>");
}
</script>

Exercises:
1. Create a program that will use an array with 10 names then display the names.

2. Create a program that will use an array with 10 names. Display all the names with even number index.

3. Create a program that will ask for 10 numbers for an array. Compute and display the sum and average of the
elements.

4. Create a program that will ask for 10 values for an array of integer then redisplay all the elements with odd
number index.

5. Create a program that will ask for 10 values for an array of integer then ask for a number to search in the array. If
the number inputted is present in the array elements display “FOUND” otherwise display “NOT FOUND”

Multiple Income Creating Project (MIC P) on ICT 23


LESSON 6

JAVASCRIPT FUNCTION

A function consists of the function keyword followed by the name of the function, a set of open and close parentheses
enclosing an optional parameter list and a body enclosed in a set of curly braces.

Syntax:
function functionName( parameter_list ) {
//body
//code to execute
return statement (if any)
}

The parameter_list is a comma-separated list of identifiers. These identifiers, called formal parameters, are used within
the body of the function. The role of parameters is to act as placeholders for actual values that are passed to the function
when it is called.

The return statement has two important use:


1. It is used to return a value.
2. It causes an immediate exit from the function it is in.
Below is a sample function that takes two parameters, then computes and returns their sum.

function getSum(a, b) {
sum = a + b;
return sum;
}

Function Call
To execute the function getSum(), a function call is made somewhere in a program. A function call causes the execution
of the statements in the body of the function.

Syntax of a function call:

function_name(arguments);

arguments are the values that are passed to the formal parameters of a function.

Example:
Calling the function getSum

getSum(5,10);

Sample program that uses the getSum() function.

<script>
function getSum(a, b) {
sum = a + b;
return sum;
}

var x=2, y=20;


document.write(“The sum of ” + x + “ and ” + y + “ is ” + getSum(x,y) + “.”);
</script>

Output
The sum of 2 and 20 is 22.
A function may not have parameter list, and it may not return any value.

24 Multiple Income Creating Project (MIC P) on ICT


function printMsg() {
document.write(“Hello World”);
document.write(“This is a function”);
}

Sample program that uses printMsg() function.

<script>
function printMsg(){
document.write("Hello World <br>");
document.write("This is a function");
}

printMsg();
</script>

Output:
Hello World
This is a function

Why Functions?
You can reuse code: Define the code once, and use it many times.
You can use the same code many times with different arguments, to produce different results.

Exercises:
1. Create a program that will display your name 20 times. Use printName() to display your name and a loop to call
the function 20 times.

2. Create a program that will ask for a number then redisplay the number inputted. The program will use
inputNumber() to ask for an input and redisplay the number.

3. Create a program that will ask for a number then evaluate it if it is an ODD or EVEN number. The program will
use oddEven() to evaluate the number then display if odd or even number aGrnd will use the number as its
passing argument.

4. Create a program that will ask for 5 items’ prices bought by a customer in a grocery store. Compute and display
the total amount to pay. Ask for the cash then compute and display the change.
The program will use computeTotal() to compute and return the total amount to pay and will use the 5 items’
prices as its parameter. And computeChange() to compute and return the change and will use the total amount
and the cash as its parameter.

LESSON 7
Multiple Income Creating Project (MIC P) on ICT 25
Using TEXTBOX and BUTTON

Creating Textbox
Aside from Prompt box as we used in this module to ask for an input, we can also use the HTML <input> tag to create
textboxes and to ask for values.

The <input> tag specifies an input field where the user can enter data. <input> elements are used within a <form>
element to declare input controls that allow users to input data but for now we are not going to use the <form> element.
An input field can vary in many ways, depending on the type attribute.

To create textbox we will use the <input> element, type attribute and “text” value.

<html>
<body>
<input type=“text”>
</body>
</html>
Using the code above it will create a textbox in your page.

To put description for the inputted value you can just write the text before the <input> element.

<html>
<body>
Enter a number <input type=“text”>
</body>
</html>

If you need to ask for 3 numbers you can have the following code.

<html>
<body>
<p> Enter a number <input type=“text”> </p>
<p> Enter a number <input type=“text”> </p>
<p> Enter a number <input type=“text”> </p>
</body>
</html>

26 Multiple Income Creating Project (MIC P) on ICT


Adding a button
To create a button we will use the <input> element, type attribute with “button” value and value attribute with “Compute”
value or your desired text that will appear in your button.

<input type=“button” value=“Compute”>

Let’s combine the code with the textboxes.

<html>
<body>
<p> Enter a number <input type=“text”> </p>
<p> Enter a number <input type=“text”> </p>
<p> Enter a number <input type=“text”> </p>
<input type=“button” value=“Compute”>
</body>
</html>

To perform JavaScript code we may use onclick event using the button.

The given codes below will compute for the sum the of 3 numbers and display it using the alert() box.

<html>
<head>
<script>
function sum(){
x=Number(document.getElementById("num1").value);
y=Number(document.getElementById("num2").value);
z=Number(document.getElementById("num3").value);
sum=x+y+z;
alert(“The sum is ” + sum);
}

Multiple Income Creating Project (MIC P) on ICT 27


</script>
<head>
<body>
<p>Enter a number <input type="text" id="num1"> </p>
<p>Enter a number <input type="text" id="num2"> </p>
<p>Enter a number <input type="text" id="num3"> </p>
<input type="button" value="Compute" onclick="sum()">
</body>
</html>

The program use sum() to compute and display the sum. The sum() uses document.getElementById().value to get the
value of the textboxes and convert the value to number using the Number() since all values inputted in a textbox are
string.

We added id attribute to the different textboxes as their unique names and these id will also correspond to the values
given in the document.getElementById().value. The id given in the textbox must be the same with the value given in the
document.getElementById(“idValue”).value.

The program use the onclick event in the button to call the sum() function.

After entering values to the 3 textboxes and pressing enter this will be a sample output.

28 Multiple Income Creating Project (MIC P) on ICT


References:

www.w3schools.com

http://www.evl.uic.edu/luc/bvis546/Essential_Javascript_--_A_Javascript_Tutorial.pdf

www.businessdictionary.com/definition/computer-programming.html

Java Education and Development Initiative (JEDI) Introduction to Programming Manual

Multiple Income Creating Project (MIC P) on ICT 29

You might also like