Download as pdf or txt
Download as pdf or txt
You are on page 1of 40

FUNDAMENTALS OF PROGRAMMING

CS 112

(Insert Design)

NOR-AINE M. CORPUZ
DANILYN A. FLORES
NOR-AINE M. CORPUZ

2021

UNIVERSITY OF SOUTHERN MINDANAO


Kabacan, Cotabato
FUNDAMENTALS OF PROGRAMMING

CS 112

NOR-AINE M. CORPUZ
DANILYN A. FLORES

2021

UNIVERSITY OF SOUTHERN MINDANAO


Kabacan, Cotabato
Author’s Declaration

Ideas, concepts, diagrams and/or illustrations depicted in this learning


material are excerpts from established references and properly noted in the list
of literatures cited herein. The author in this learning material does not claim
full and authentic ownership of all the contents of this material, nor in any
manner willfully infringe the copyright law and other existing provisions
appertaining thereto.

This learning material is printed for the sole use of classroom or


distance/remote learning of USM and is not intended for commercial purposes.
Any use or reproduction in part or in full, whether electronic or mechanical,
photocopying or recording in any information storage and retrieval system,
other than what it is intended for requires the consent of authorized and
competent authority of the University of Southern Mindanao.

CS 112: Fundamentals of Programming


iv
USM VISION

Quality and relevant education for its clientele to be globally competitive,


culture sensitive and morally responsive human resources for sustainable
development

USM MISSION

Help accelerate socio-economic development, promote harmony among


diverse communities and improve quality of life through instruction, research,
extension and resource generation in Southern Philippines.

UNIVERSITY QUALITY POLICY STATEMENT

The University of Southern Mindanao, as a premier university, is


committed to provide quality instruction, research development and extension
services and resource generation that exceed stakeholders’ expectations
through the management of continual improvement efforts on the following
initiatives.
1. Establish Key Result Areas and performance indicators across all
mandated functions;
2. Implement quality educational programs;
3. Guarantee competent educational service providers;
4. Spearhead need-based research outputs for commercialization,
publication, patenting, and develop technologies for food security,
climate change mitigation and improvement in the quality of life;
5. Facilitate transfer of technologies generated from research to the
community for sustainable development;
6. Strengthen relationship with stakeholders;
7. Sustain good governance and culture sensitivity; and
8. Comply to customer, regulatory and statutory requirements.

CS 112: Fundamentals of Programming


v
PREFACE

In the field of science and engineering, skill in computer programming is


a must-have. This book is an introductory computer programming textbook that
uses Java as the language of instruction. This is written to aid students in their
journey in learning the basics of programming.

This module is divided into five chapters.

• Chapter 1 talks about Introduction to Computer programming. In this


chapter computer programming is defined. Traits of a good programmer
is discussed. Good programming practices and qualities of a good
program is elaborated.
• Chapter 2 discusses Programming Fundamentals. In this chapter
Program Development Life Cycle, Comments, Tokens, Separators,
Identifiers, Keywords, Literals, Data Types, Variables, Operators,
Expressions, Statements and Blocks is explained.
• Chapter 3 users of this module are introduced to Inputs ang Outputs. It
is in this chapter where they are going to learn how to create simple
programs, displaying output in console, and displaying output and
getting input using graphical user interface.
• Chapter 4 is about Control structures, decision and repetition control
structures.
• The last chapter talks about Arrays. In this chapter topics including
Introduction to Arrays, Declaring Arrays, Accessing Array Element, Array
Length and Multidimensional Arrays are explained.

Every chapter of this module have intended learning outcomes for


students to be well guided to what they are going to learn. A few example
programs written in Java programing language are presented in every chapter.
Sample programs used in this book are edited and compiled using Jcreator Pro
4.5. At the end of each chapter, the authors included two summative tests, an
assignment, and a quiz. This is to quantify the level of learning each student
acquired in every chapter of this module.

CS 112: Fundamentals of Programming


vi
TABLE OF CONTENTS

Page
CHAPTER 4 Control Structures 1
Decision Control Structure 1
if 1
if-else 3
if-else-if 4
switch 8
Repetition Control Structure 10
while 10
do-while 11
for 11
Formative Assessment 9, 12
Chapter Summary 13
Summative Assessment 13
Chapter References 13
CHAPTER 5 Arrays 14
Introduction to Arrays 14
Declaring Arrays 14
Accessing an Array Element 15
Array Length 16
Multidimensional Arrays 16
Formative Assessment 17
Chapter Summary 18
Summative Assessment 18
Chapter References 18
APPENDICES 19
ANSWER KEY 21

CS 112: Fundamentals of Programming


vii
COURSE GUIDE

Course Information
Course Title Fundamentals of Programming
Course Code CS 112
Pre-requisite/Co-requisite None

Course Description
This course covers the use of general purpose programming language
to solve problems. The emphasis is to train students to design, implement, test,
and debug programs intended to solve computing problems using fundamental
computing constructs.
Fundamentals of Programming enables students to learn the important
basic programming concepts like variables, data types, operators, and control
structures, and apply these using the Java programming language. As an
introduction, this course gives an overview of the different problem-solving
strategies that will help them analyze problems to create programs throughout
the course.
The course helps students understand the processes and the
significance of making programs, its implementation, application, and
significance to the industry, and the community. Also, this course helps give
students a deep understanding and developed skills of all the basic concepts
of programming and effectively utilize the language and programming
structures in program-making that willhelp them learn other and new
programming languages for them to be competent individuals.

Course Objectives/Outcomes
Upon passing the course, you must be able to:
1. Discuss the different concepts and techniques used in creating
computer programs.
2. Use appropriate programming components in designing a computer
program for a given problem.
3. Create computer programs using the Java programming language for
given problems.

Course Learning/Study Plan/Schedule


Week/Date Topic Teaching Learning Assessment
(Deadlines) and Materials
Learning
Activities
Introduction to Interactive Downloadabl Case Study
Computer Learning e
Programming Slides/Video Quiz
1
• What is Brainstormi s
Computer ng

CS 112: Fundamentals of Programming


viii
Programmin Independen Computer/M
g? t Learning obile Phone
• Traits of a
Good Module
Programmer
• Good
Programmin
g Practices
• Qualities of
a Good
Program
Programming Interactive Downloadabl Problem
Fundamentals Learning e Solving
• Program Slides/Video
Developmen Brainstormi s Quiz
t Life Cycle ng
• Comments Computer/M
• Tokens Independen obile Phone
• Separators t Learning
2-5 • Identifiers Module
• Keywords
• Literals
• Data Types
• Variables
• Operators
• Expressions
• Statements
• Blocks
Inputs and Interactive Downloadabl Problem
Outputs Learning e Solving
• Getting to Slides/Video
Know the Brainstormi s Quiz
Software ng
• Creating Computer/M
Simple Independen obile Phone
Programs t Learning
6-8 • Displaying Module
Output on
Console
• Getting
Input and
Displaying
Output using
Graphical
user
Interface
9 MIDTEM EXAM
Control Interactive Downloadabl Problem
10 - 12
Structures Learning e Solving

CS 112: Fundamentals of Programming


ix
Decision Slides/Video
Control Brainstormi s Quiz
Structures ng
• if Computer/M
• if-else Independen obile Phone
• if-else-if t Learning
• switch Module

Control Interactive Downloadabl Problem


Structures Learning e Solving
Repetition Slides/Video
Control Brainstormi s Quiz
Structure ng
13 - 15
• while Computer/M
• do-while Independen obile Phone
• for t Learning
Module

Arrays Interactive Downloadabl Problem


• Introduction Learning e Solving
to Arrays Slides/Video
• Declaring Brainstormi s Quiz
Arrays ng
• Accessing Computer/M
16 – 17 Independen obile Phone
Array
Element t Learning
• Array Module
Length
• Multidimensi
onal Arrays
18 FINAL EXAM

Course Requirements/Assessment and Evaluation


Scheme/Grading System
MIDTERM FINAL TERM FINAL GRADE
Requirement/ Percentage Requirement/ Percentage
Assessment Assessment
Task Task
Attendance 10 Attendance 10 Midterm 50%
Quizzes 25 Quizzes 25 Final 50%
Term
Summative 30 Summative 30 TOTAL 100%
Assessments Assessment
Midterm Exam 35 Final 35
Exam/Project
TOTAL 100% TOTAL 100%

House Rules/Class Policies


1. Students are REQUIRED to enroll in the course VLE where all course
materials are uploaded and course requirements are submitted.

CS 112: Fundamentals of Programming


x
2. Students are also REQUIRED to be in the course Facebook Group Chat
where all announcements and reminders will be posted.
3. Each student is encouraged to have a computer, either a desktop or a
laptop, and install the required or related software needed for convenience
in doing tasks required for the course.
4. Students are enjoined to attend the online live lectures. If a student cannot
attend the lectures, the recording will be posted on the course VLE for
download and viewing offline.
5. Students should wear appropriate clothing while attending the online live
lecture.
6. Plagiarism is highly discouraged and will not be taken lightly. Tasks are
required to be submitted together with a plagiarism receipt using any online
plagiarism checker. The instructor will also manually check the authenticity
of submissions.
7. Tasks should be submitted on time. Submissions have extended deadlines
considering resources especially hardware and internet speed.
8. Students should inform their instructor on the time allocated or within 5 days
after the time allocated for a quiz/exam to explain why they cannot take or
have not taken the quiz/exam for them to be given considerations.
9. Students are encouraged to communicate with their instructor for
consultations via any media the instructor will provide from Monday-Friday
between 8AM-5PM only.

CS 112: Fundamentals of Programming


xi
CHAPTER 4
Control Structures

In the examples given in the previous sections, programs were


sequential wherein statements are executed one after another in a fixed order.
Control Structures allows changing the ordering of how statements in programs
are executed.

DECISION CONTROL STRUCTURE

These control structures allows selecting and executing specific blocks of


code while skipping other sections.

1. if

The if specifies that a statement or block will be executed if and only if a


certain condition is true. As shown in the syntax and flowchart in Fig. 38, only
one of two events can happen:

a. When the condition in the boolean expression is true, the if block will
be executed then proceed to the next lines of code; or

b. Skip the if block and proceed to the next lines of code.

Syntax:

if(boolean_expression) { true
boolean_exp
statement;
statement1; }

statement
Fig. 38. Flowchart for if

The statement in the sample flowchart in Fig. 38 is not necessarily a


process. Though it can be a process, it can also be an input or output or another
decision that depends entirely to the analysis of the problem. And it is not limited
to only one. It can be multiple processes or inputs or outputs or decisions.

CS 112: Fundamentals of Programming


1
Example 1
Problem: Create a program that will display “Congratulations! You Passed!”
if the value of grade is greater than 60 using the if control structure
Problem Analysis Program Design
Output:
Congratulations! START grade = 68
You Passed!
if value of grade > 60
grade>60
true
Input: None

Process:
grade = 68 Display “Congratulations!”

Display “You Passed!”


STOP

Program Coding
public class grade {
public static void main(String []args) {
int grade = 68;
if(grade>60) {
System.out.println(“Congratulations!”);
System.out.println(“You Passed!”); }
}}
Example 2
Problem: Create a program that will display a remarks of “PASSED” if
grade >60 using if control structure
Program Analysis Program Design
Output: remarks
START grade = 68
Input: None
true
Process: grade>60
grade = 68
remarks = “PASSED” if grade >60 remarks = “PASSED”
Display remarks

STOP

Program Coding
public class grade {
public static void main(String []args) {
int grade = 68;
String remarks = “”;
if(grade>60) {
remarks = “PASSED”; }
System.out.println(“Remarks: ” + remarks);
}}

CS 112: Fundamentals of Programming


2
2. if-else

This is used if a statement or a block should be executed if the condition


is true and a different statement or block if the condition is false. As shown in
the syntax and flowchart in Fig. 39, only one of two events can happen:

a. When the condition in the boolean expression is true, the if block will
be executed, skip the else block, then proceed to the next lines of
code; or

b. Skip the if block, execute the else block, then proceed to the next lines
of code.

Syntax:

if(boolean_expression) {
statement1; true false
boolean_expr
statement2; }
else {
statement3; statement statement
statement4; }
Fig. 39. Flowchart for if-else

The statements in Fig. 39 are not necessarily processes. Though it can


be a process, it can also be an input or output or another decision that depends
entirely to the analysis of the problem. And it is not limited to only one. It can be
multiple processes or inputs or outputs or decisions.

Example 1
Problem: Create a program that will display “Congratulations! You Passed!”
if grade>60 otherwise display “Sorry, you Failed!” using if-else
Problem Analysis Program Design
Output:
“Congratulations! START grade = 68

You Passed!” if the


value of grade > 60 or true false
“Sorry, you Failed” grade>60

Input: None Display “Congratulations!” Display “Sorry, you


Failed!”

Process:
Display “You Passed!” STOP
grade = 68

Program Coding
public class grade {
public static void main(String []args) {
int grade = 68;

CS 112: Fundamentals of Programming


3
if(grade>60) {
System.out.println(“Congratulations!”);
System.out.println(“You Passed!”); }
else {
System.out.println(“Sorry, you Failed!”); }
}}

Example 2
Problem: Create a program that will display the remarks based on the
value of grade. Remarks will be “PASSED” if grade is greater than 60,
otherwise “FAILED” using if-else
Problem Analysis Program Design
START grade = 68
Output: remarks

Input: None true false


grade>60

Process:
grade = 68 remarks = “PASSED” remarks = “FAILED”
remarks = “PASSED”
if grade >60 or remarks

remarks = “FAILED”
STOP

Program Coding
public class grade {
public static void main(String []args) {
int grade = 68;
String remarks = “”;
if(grade>60) {
remarks = “PASSED”; }
else {
remarks = “”FAILED”; }
System.out.println(“Remarks: ” + remarks);
}}

3. if-else-if

This allows the else clause of an if-else to be another if-else. This allows
making more complex selections. As shown in the flowchart in Fig. 40, one of
3 events can happen:

a. When the condition in the 1st boolean expression is true, the if block will
be executed, skip the else if and else blocks, then proceed to the next
lines of code;
b. Skip if block, and when condition in 2nd boolean expression is true,
execute else if block, skip else block, and proceed to the next lines of
code; or

CS 112: Fundamentals of Programming


4
c. Skip if and else if blocks, execute else block and proceed to next lines of
code.
The number of events will depend on the number of else ifs.

Syntax:

if(boolean_expression1) {
statement1; boolean_expr1
true
statement2; } false
else if(boolean_expression2) {
statement3;
true boolean_expr2 false
statement4; }
else { statement
statement5; statement statement
statement6; } }
Fig. 40. Flowchart of if-else-if

The statements in Fig. 40 are not necessarily processes. Though it can


be a process, it can also be an input or output or another decision that depends
entirely to the analysis of the problem. And it is not limited to only one. It can be
multiple processes or inputs or outputs or decisions.

Example 1
Problem: Create a program that will display “Congratulations! You Passed!”
if the value of grade is greater than 90, “Good!” if greater than 75, or “Sorry,
you Failed!” using if-else-if
Problem Analysis Program Design

Output: START grade = 68


“Congratulations!
You Passed!” if true
grade > 90, if not, grade>90
0 false
“Good!” if grade
>75 or Display “Congratulations!”
“Sorry, you grade>75
Failed!” true false
Display “You Passed!”

Input: None Display “Good!” Display “Sorry,


you Failed!”
Process:
grade = 68
STOP

Program Coding
public class grade {
public static void main(String []args) {
int grade = 68;
if(grade>90) {
System.out.println(“Congratulations!”);
System.out.println(“You Passed!”); }

CS 112: Fundamentals of Programming


5
else if(grade>75) {
System.out.println(“Good!”); }
else {
System.out.println(“Sorry, you Failed!”); } } }

Example 2
Problem: Create a program that will determine the remarks based on the
grade. “Very Good!” if grade > 90, if not, “Good!” if grade > 75, otherwise
“Better luck next semester” using if-else-if
Problem Analysis Program Design
START
Output: remarks

Input: None grade = 68

Process:
grade = 68 grade>90
remarks = “Very Good!” if true false
grade>90, if not,
remarks = “Good!” if
remarks = “Very Good!”
grade>75
otherwise remarks = grade>75
“Better luck next true
false
semester”
remarks=“Good remarks=“Better
!” luck next
semester”

Display remarks

STOP

Program Coding
public class grade {
public static void main(String []args) {
int grade = 68;
String remarks = “”;
if(grade>90) {
remarks = “Very Good!”; }
else if(grade>75) {
remarks = “Good!”; }
else {
remarks = “Better luck next semester”; }
System.out.println(“Remarks: ” + remarks);
}}

CS 112: Fundamentals of Programming


6
Example 3
Problem: Create a program that will determine the remarks based on the
grade. “Excellent!” if grade>=90, if not, “Very Good!” if grade>=84.5 and
<=95, if not, “Good!” if grade>=74.5 and <85, if not, “Better luck next
semester” using if-else-if
Problem Analysis Program Design
START

Output: remarks
grade = 92.0
Input: None

Process:
grade>=95
grade=92.0 true false
remarks =
“Excellent!” if
remarks = “Excellent!”
grade>=95, if not,
(grade<95)&&
(grade>=84.5)
remarks=”Very true false

Good!” if
grade>=84.5 and remarks=“Very Good!”
<95, if not,
(grade<85)&&
true (grade>=74.5)
remarks=”Good!” if false
grade>=74.5 and
<85
remarks=“Good!”

otherwise,
remarks=”Better remarks=“Better
luck next time” Display remarks
luck next
semester”

STOP

Program Coding

public class grade {


public static void main(String []args) {
double grade = 92.0;
String remarks = “”;
if(grade>=95) {
remarks = “Excellent!”; }
else if((grade<95) && (grade>=84.5)) {
remarks = “Very Good!”; }
else if((grade<85) && (grade>=74.5)) {
remarks = “Good!”; }
else {
remarks = “Better luck next semester”; }
System.out.println(“Remarks: ” + remarks);
}}

CS 112: Fundamentals of Programming


7
4. switch

The switch executes the statement or block if and only if the value in the
switch expression is equal to a specific case. If none of the cases are satisfied,
the default block is executed.
The value in the switch expression should only be of either type int or
char. The case selectors should also match the type of the switch expression.
As shown in the syntax and flowchart in Fig. 41, the int or char value of
the variable in the switch_expression will be compared to the cases. When a
case is a match, the block in that case will be executed and all other blocks in
the switch will be skipped. If none of the cases matched, the block of the default
will be executed.

switch expression
Syntax:
true block 1
switch(switch_expression) { case_1
statements
case case_selector1:
statement1;
statement2; true
break; block 2
case_2
statements
case case_selector2:
statement3;
statement4;
break; default block
default: statements
statement5;
statement6;
} Fig. 41. Flowchart of switch

Example 1
START grade = 92 switch(grade)

public class Grade {


public static void main(String []args) {
int grade = 92; Display “Excellent!” case 100
true
switch(grade){
case 100:
System.out.println(“Excellent!”);
break; case 90
Display “Very Good!” true
case 90:
System.out.println(“Very Good”);
break;
Display “Good!” case 80
case 80: true
System.out.println(“Good!”);
break;
default: STOP Display “Failed!”
System.out.println(“Failed!”); }
}} Fig. 42. Flowchart of Example 1

CS 112: Fundamentals of Programming


8
Example 2
START grade = 92 switch(grade)

public class Grade {


public static void main(String []args) {
int grade = 92; remarks = “Excellent!” case 100
true
String remarks = “”;
switch(grade){
case 100:
remarks = “Excellent”; remarks = “Very Good!” case 90
true
break;
case 90:
remarks = “Very Good”;
remarks = “Good!” case 80
break; true
case 80:
remarks = “Good”;
break; Display remarks remarks = “Failed!”
default:
remarks = “Failed”; }
STOP
System.out.println(“Remarks: ” + remarks); Fig. 43. Flowchart of Example 2
}}

FORMATIVE ASSESSMENT 1

1. Create a simple program using PDLC that will prompt for a whole number
input from 0-10 and output into words using if-else-if.
Output “Error: Number not in range.” for numbers not 0-10.
(Refer to Appendix A for sample output)

2. Modify Chapter 3 Formative Assessment 1 to include a decision control


structure, that will determine the remarks whether the average is Passed or
Failed. Passing grade is 74.5 and above.
(Refer to Appendix B for sample output)

CS 112: Fundamentals of Programming


9
REPETITION CONTROL STRUCTURE

Repetition Control Structures are Java statements that allow executing


specific blocks of codes a number of times.

1. while

In a while loop, the statements inside the block are executed


repeatedly as long as the boolean expression evaluates to true. The syntax
and flowchart (Fig. 44) are shown below.

Syntax:
boolean_expr
while(boolean_expression) { false
statement1; true
statement2;
... statements
increment/decrement; } Fig. 44. Flowchart of while

The statements can be a variable declaration, a prompt for an input,


a process or an output. Also, the number of statements inside a block has
no limit.

Start i=4
Example 1

public class while_1{ i>0 Stop


false
public static void main(String []args){ true
int i = 4;
while(i > 0) { Display i
System.out.println(i);
i--; } } }
i--
Fig. 45. Flowchart of Example 1
Example 2
public class while_2{ Display x x++

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


int x = 0; Start x=0 x<10
while(x < 10) {
false
System.out.println(x);
x++; } } } Stop

Fig. 46. Flowchart of Example 2


Example 3
Display “Hello” x++
public class while_3{
public static void main(String []args){ true

int x = 1; Start x =1 x<10

while(x < 10) { false


System.out.println(“Hello”);
Stop
x++; } } } Fig. 47. Flowchart of Example 3

CS 112: Fundamentals of Programming


10
2. do-while loop

In a do-while loop, the statement/s inside the block is/are executed


at least once and then repeated several times as long as the boolean
expression is true. The format is shown below and the flowchart is shown in
Fig. 48.

Syntax:

do { statements
statement1;
statement2;
... true false
boolean_expr
increment/decrement; }
while(boolean_expression);
Fig. 48. Flowchart of do-while

The statements can be a variable declaration, a prompt for an input,


a process or an output. Also, the number of statements inside a block has
no limit.

Example 1:
Start x=0
public class do_while_1{
public static void main(String []args){
int x = 0; Display x
do {
System.out.println(x);
x++
x++; }
while(x<10);
true false
}} X<10 Stop

Fig. 49. Flowchart of Example 1


3. for loop

Like the previous loops, the for loop allows for execution of
statements a number of times as long as the boolean expression or
condition is true. The format is shown below and the flowchart is shown in
Fig. 50.

Syntax:

for(InitializationExpression; LoopCondition; StepExpression) {


statement1;
statement2;
... }

where,
InitializationExpression – initializes the loop variable
LoopCondition – compares the loop variable to some limit value
StepExpression – updates the loop variable

CS 112: Fundamentals of Programming


11
false

Initialization_expr Loop_con Step_expr


d
true

statements

Fig. 50. Flowchart of for loop

Example 1:
public class for_1{
public static void main(String [] args){
for(int i = 0; i < 10; i++) {
System.out.println(i); } } } Stop

false

Start i=0 i < 10 i = i+1

true

Display i

Fig. 51. Flowchart of Example 1

FORMATIVE ASSESSMENT 2

1. Create a flowchart for the code given below.


import javax.swing.JOptionPane;
public class Power{
public static void main (String[] args) {
int num = 0;
int pow = 0;
int numpow = 0;
String label = "";
num = Integer.parseInt(JOptionPane.showInputDialog("Enter a whole
number:"));
pow = Integer.parseInt(JOptionPane.showInputDialog("Enter Power
(also another whole number):"));
numpow = num;
for(int i = 1; i<pow; i++) {
numpow*=num; }
label = num + " to the power of "+ pow +" = ";
JOptionPane.showMessageDialog(null, label + numpow); } }

2. Create a simple program that will prompt for a name and will display that
name 100 times using do-while.
(Refer to Appendix C for sample output)
3. Modify Chapter 3 Formative Assessment 2 #2 to include a repetition control
structure that will prompt for the details of 3 employees and will display the
information of the employees like a payroll.
(See Appendix D for sample output)

CS 112: Fundamentals of Programming


12
CHAPTER 4 SUMMARY

In order to create more complex programs, control structures are used.


There are two types of control structures: decision control structures and
repetition control structures.
Under decision control structures there is the if, the if-else, the if-else-if
and the switch that can be used to create programs that can change the order
in which lines of code are executed. Using if, the statement/s inside the block
are executed when the condition is true and skipped otherwise. Using the if-
else, when the condition is true, the statements/s inside the if block will be
executed and skip the else block or the else block will be executed and skip the
if block otherwise. Using the if-else-if, the statement/s inside the block where
the condition evaluates true is executed and the rest is skipped. Using the
switch, the only accepts int or char variables, the statement/s under the
matched case will be executed and the rest will be skipped.
Under repetition control structures there is the while, the do-while and
the for loops that can be used to repeat the execution of certain lines of code
as long as the condition is true or the limit is reached.
There is no right or wrong decision in choosing the most applicable
control structure to use for a certain program as long as the program satisfies
the requirements and it is coded with the least number of lines.

SUMMATIVE ASSESSMENT

1. Chapter 4 Activity (See VLE)


2. Chapter 4 Quiz (See VLE)

CHAPTER 4 REFERENCES

[1] Burd, B. (2017). Beginning Programming with Java For Dummies (5th Ed).
New Jersey: John Wiley and Sons, Inc.
[2] Cavida, D.G, Frio, F.M., Flores, D. (2010). Computer Programming I.
Unpublished Workbook, University of Southern Mindanao, Kabacan, Cotabato.
[3] Flask, R. (ND). Java for Beginners 2nd Edition [PDF File]. Retrieved from
http://staff.um.edu.mt/__data/assets/pdf_file/0010/57169/jn.pdf
[4] Mayfield, B. (2016). From Problem Analysis to Program Design Lab
Manual (3rd ed.). Philippines: Cengage Learning Asia Pte Ltd.

CS 112: Fundamentals of Programming


13
CHAPTER 5
Arrays

Introduction to Arrays

In the previous chapters, it was discussed how to declare different


variables using different data types. In declaring variables, a unique identifier
name and data type should be used. In order to use the variable, its identifier
name is called.
For example, there are three (3) variables of type int with different names
for each variable:

int num1 = 0;
int num2 = 0;
int num3 = 0;

num1 = 1;
num2 = 3;
num3 = 5;

It seems like a tedious task in order to initialize or assign values and use
the variables. In Java and other programming languages, there is one capability
wherein one variable can store a list of data and manipulate them more
efficiently. This type of variable is called an array.
An array stores multiple data items of the same data type, in a
contiguous block of memory, divided into a number of slots. Think of an array
as a stretched variable – a location that still has one identifier name, but can
hold more than one value. For example you can declare an int array variable
named num that can hold three (3) values: 1, 3, and 5 (Fig. 52) instead of
declaring three (3) variables that can hold one (1) value each like in the example
above.

0 1 2
num:
1 3 5
Fig. 52. Visual Representation of an Array Variable

Declaring Arrays

Arrays must be declared like all variables. To declare an array, list the
data type, followed by a set of square brackets [ ], and followed by the
identifier name. For example,

int [ ]num;

The square brackets can also be placed after the identifier name. For example,

int num[ ];

CS 112: Fundamentals of Programming


14
After declaring, the array must be created and its length must be
specified with a constructor statement. This process in Java is called
instantiation (the Java word for create). Take note that the size of the array
cannot be changed once initialized. For example,

int num[ ];
num = new int[100];
or
int [ ]num = new int[100];

In the example, the declaration tells the Java compiler that the identifier
num will be used as the name of an array containing integers and to create a
new array containing 100 elements.

0 1 2 3 4 99
num:

Instead of using the new keyword to instantiate an array, it can also be


automatically declared, created and assigned values at once with the elements
enclosed in a pair of curly braces ( { } ) and separated by commas ( , ).
For example,

boolean results[ ] = {true, false, true, false};

double [ ]grades = {100, 90.99, 80.25, 75.0};

String days[ ] = {“Mon”,”Tue”,”Wed”,”Thu”,”Fri”,”Sat”,”Sun”};

Accessing an Array Element

To access an array element, or a part of the array, a number called an


index or a subscript is used.
An index or a subscript is assigned to each member of the array,
allowing the program and the programmer to access individual values when
necessary. Index numbers are always integers. They begin with a zero (0)
and progress sequentially by whole numbers to the end of the array. Take note
that the index of the elements inside an array is from 0 to (size of the array –
1).
For example, given the array declared earlier,

num[0] = 10; //assigns 10 as the first element of the array


System.out.print(num[50]); //outputs the 51st element of the array

Take note that once an array is declared and created, the stored value
of each member of the array will be initialized to 0 for number data. However,
reference data types such as Strings are not initialized to blanks or an empty
string “”. Therefore, String arrays must be populated clearly.
The following is a sample code on how to assign user inputs as the
elements of an array. This uses a for loop, so the code is shorter.

CS 112: Fundamentals of Programming


15
import javax.swing.JOPtionPane;
public class ArraySample_1{
public static void main(String [ ]args) {
int [ ]num = new int[100];
for(int i = 0; i<100; i++) {
num[i]=Integer.parseInt(JOptionPane.showInputDialog(“Enter a
number:”)); }
}}

The following is a sample code on how to print all the elements in the
array. This uses a for loop, so the code is shorter.

public class ArraySample_2{


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

Array Length
In order to get the number of elements in an array, the length field of an
array can be used. The length field of an array returns the size of the array.
It can be used by writing,

<arrayName>.length

For example, given the code in the previous example, it can be rewritten as,

public class ArraySample{


public static void main(String [ ]args) {
int [ ]num = new int[100];
for(int i = 0; i<num.length; i++) {
System.out.print(num[i]); } } }

Below is another example where a named variable is used as the


declared size of an array so as to make the size easy to change.

public class ArraySample{


public static void main(String []args) {
int x = 100;
int num[ ] = new int[x];

for(int i = 0; i<num.length; i++) {


System.out.print(num[i]); } } }

Multidimensional Arrays

Multidimensional arrays are implemented as arrays of arrays.


Multidimensional arrays are declared by placing the appropriate number of
bracket pairs before or after the array name. For example,

CS 112: Fundamentals of Programming


16
int [ ][ ]twoD = new int [512][128];

char threeD[ ][ ][ ] = new char[8][16][24];

String [ ][ ]dogs = {{“Terry”,”Brown”},


{“Rave”,”White”},
{“Toby”,”Gray”,},
{“Fido”,”Black”}};

Accessing an array element in a multidimensional array is just the same


as accessing the elements in a one dimensional array. For example, to access
the first element in the first row of the array dogs, write,

System.out.print(dogs[0][0]); //Outputs Terry


The following is an example on how to print the elements of a
multidimensional array using loops.

public class ArraySample{


public static void main(String [ ]args) {
String [ ][ ]dogs= {{“Terry”,”Brown”}, {“Rave”,”White”}, {“Toby”,”Gray”},
{“Fido”,”Black”}};
for(int i = 0; i<dogs.length; i++) {
for(int j = 0; j<dogs[i].length; j++){
System.out.print(dogs[i][j]); } } } }

FORMATIVE ASSESSMENT 1
1. Directory
Create a program (Design and Code) that will prompt 5 user to enter
name, telephone number and address, store the data in an array variable
and display like a directory. (See Appendix E for sample output)

Example:

Name : Angelina Jolie


Telephone No.: 572-1234
Address: Hollywood

Name: Jackie Chan


Telephone No.: 246-0987
Address: China
...

2. X and Y Axis Points


Create a program (Design and Code) that will prompt for 4 pairs of x and
y axis points, store them in a multidimensional array, display the points
and its corresponding quadrant in the Cartesian plane.
(See Appendix F for sample output)

CS 112: Fundamentals of Programming


17
CHAPTER 5 SUMMARY
An array is a variable that can store multiple data items of the same data
type. Using arrays enables programmers to create shorter functional codes.
Arrays like regular variables has a data type, a name, and an initial value. But
unlike variables, arrays has an array size which specifies how many data it is
capable of holding. Each element of an array can be accessed or assigned
values using an index or a subscript which is usually a whole number from 0 to
the size of the array minus 1. To access and assign values to arrays, repetition
control structures are used like the for loop.
The length field of an array can be used to get the number of elements
an array has. It is normally used in the loops so as not to commit mistakes when
determining the size of the array especially in accessing or assigning elements.
Arrays can be multidimensional. Multidimensional arrays are an array of
arrays which means that each element of the array is an array.
Arrays are just one of the many ways in programming that can help
programmers write shorter but functional codes.

SUMMATIVE ASSESSMENT

1. Chapter 5 Activity (See VLE)


2. Chapter 5 Quiz (See VLE)

CHAPTER 5 REFERENCES
[1] Burd, B. (2017). Beginning Programming with Java For Dummies (5th Ed).
New Jersey: John Wiley and Sons, Inc.
[2] Cavida, D.G, Frio, F.M., Flores, D. (2010). Computer Programming I.
Unpublished Workbook, University of Southern Mindanao, Kabacan, Cotabato.
[3] Flask, R. (ND). Java for Beginners 2nd Edition [PDF File]. Retrieved from
http://staff.um.edu.mt/__data/assets/pdf_file/0010/57169/jn.pdf
[4] Mayfield, B. (2016). From Problem Analysis to Program Design Lab
Manual (3rd ed.). Philippines: Cengage Learning Asia Pte Ltd.

CS 112: Fundamentals of Programming


18
APPENDICES

Appendix A

Appendix B

Appendix C

CS 112: Fundamentals of Programming


19
Appendix D

Appendix E

Appendix F

CS 112: Fundamentals of Programming


20
ANSWER KEY

Chapter 4
Formative Assessment 1
1.
Problem Analysis

Input: num

Process:
if num is 0 word = “ZERO” otherwise
if num is 1 word = “ONE” otherwise
if num is 2 word = “TWO” otherwise
if num is 3 word = “THREE” otherwise
if num is 4 word = “FOUR” otherwise
if num is 5 word = “FIVE” otherwise
if num is 6 word = “SIX” otherwise
if num is 7 word = “SEVEN” otherwise
if num is 8 word = “EIGHT” otherwise
if num is 9 word = “NINE” otherwise
if num is 10 word = “TEN” otherwise
word = “Error: Number not in range.”

Output: word

Program Design

Flowcharts created using Lucidchart at www.lucid.app

CS 112: Fundamentals of Programming


21
Program Coding

import javax.swing.JOptionPane;
public class NumInWords{
public static void main (String[] args) {
String word = "";
int num = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter a whole
number from 0-10:", "NUMBER",JOptionPane.PLAIN_MESSAGE));

if(num==0) {
word = "ZERO";}
else if(num==1) {
word = "ONE";}
else if(num==2) {
word = "TWO";}
else if(num==3) {
word = "THREE";}
else if(num==4) {
word = "FOUR";}
else if(num==5) {
word = "FIVE";}
else if(num==6) {
word = "SIX";}
else if(num==7) {
word = "SEVEN";}
else if(num==8) {
word = "EIGHT";}
else if(num==9) {
word = "NINE";}
else if(num==10) {
word = "TEN";}
else {word = "ERROR: Number not in range.";}

JOptionPane.showMessageDialog(null, word, "NUMBER IN WORDS", 1); } }

2.
Problem Analysis Program Design

Input: CS112, CS113,


CS114, GE1, SocSci1,
PE1, NSTP1

Process:
remarks = “ ”

average =
(CS112+CS113+CS114+
GE1+SocSci1+PE1+NST
P)/7

remarks = “PASSED!” if
average >=74.5 otherwise
remarks = “FAILED!”

Output: average, remarks

Flowcharts created using Lucidchart at www.lucid.app

CS 112: Fundamentals of Programming


22
Program Coding

import javax. swing.JOptionPane;


public class _1SemAveGrade{
public static void main (String[] args) {
String remarks = " ";
double CS112 = Double.parseDouble(JOptionPane.showInputDialog(null, "Enter CS
112 Grade: ","CS 112 Grade", JOptionPane.PLAIN_MESSAGE));
double CS113 = Double.parseDouble(JOptionPane.showInputDialog(null, "Enter CS
113 Grade: ","CS 113 Grade", JOptionPane.PLAIN_MESSAGE));
double CS114 = Double.parseDouble(JOptionPane.showInputDialog(null, "Enter CS
114 Grade: ","CS 114 Grade", JOptionPane.PLAIN_MESSAGE));
double GE1 = Double.parseDouble(JOptionPane.showInputDialog(null, "Enter GE 1
Grade: ","GE 1 Grade", JOptionPane.PLAIN_MESSAGE));
double SocSci1 = Double.parseDouble(JOptionPane.showInputDialog(null, "Enter
Soc Sci 1 Grade: ","Soc Sci 1 Grade", JOptionPane.PLAIN_MESSAGE));
double PE1 = Double.parseDouble(JOptionPane.showInputDialog(null, "Enter PE 1
Grade: ","PE 1 Grade", JOptionPane.PLAIN_MESSAGE));
double NSTP1 = Double.parseDouble(JOptionPane.showInputDialog(null, "Enter
NSTP 1 112 Grade: ","NSTP 1 Grade", JOptionPane.PLAIN_MESSAGE));
double average = (CS112+CS113+CS114+GE1+SocSci1+PE1+NSTP1)/7;
if(average>=74.5) {
remarks = "PASSED!"; }
else {
remarks = "FAILED!"; }
System.out.println("Your average grade for this semester is: " + average);
System.out.println("This means you " + remarks); } }

Formative Assessment 2
1.

Flowcharts created using Lucidchart at www.lucid.app

CS 112: Fundamentals of Programming


23
2.
Problem Analysis Program Design
Input: name

Process:
count = 1
count++

Output:
name while count is <101

Flowcharts created using Lucidchart at www.lucid.app


Program Coding

import javax. swing.JOptionPane;


public class NameLoop{
public static void main (String[] args) {
String name = JOptionPane.showInputDialog("Enter name: ");
int count = 1;
do {
System.out.println(name);
count++;
}
while(count<101);
} }

3.
Problem Analysis

Input:
emName and daysWorked while i<3

Process:
dailyRate = 500
philHealth = 330
sss = 220
grossSalary = (dailyRate * daysWorked)
monthlySaary = grossSalary - (sss + philHealth)
i=1
i++
output = empName+ " "+ daysWorked +"
"+grossSalary+" "+sss+"
"+philHealth+" "+monthlySalary

CS 112: Fundamentals of Programming


24
Output:
output while i<3

Program Design

Flowcharts created using Lucidchart at www.lucid.app

CS 112: Fundamentals of Programming


25
Program Coding

import javax.swing.JOptionPane;
public class SalaryCalculator{
public static void main (String[] args) {
int dailyRate = 500;
int philHealth = 330;
int sss = 220;
String output = "";
System.out.println("
BYTES LIMITED INCORPORATED");
System.out.println("
CEIT, USM");
System.out.println("
Kabacan, Cotabato");
System.out.println("
Tel. No.: (064) 572-1234\n\n");
System.out.println("
GENERAL PAYROLL");
System.out.println("
Month: October");
System.out.println("-----------------------------------------------------------------------------------------------
------------------------------");
System.out.println("Empolyee Name | Days Worked |
Gross Salary | Deductions |
Net Monthly Salary");
System.out.println("
SSS
Philhealth (Pesos)");
System.out.println("-----------------------------------------------------------------------------------------------
------------------------------");
for(int i=0;i<3;i++){
String empName = JOptionPane.showInputDialog("Enter Employee's Full Name: ");
int daysWorked = Integer.parseInt(JOptionPane.showInputDialog("Enter Number of Days
Worked for the month: "));
double grossSalary = (dailyRate*daysWorked);
double monthlySalary = grossSalary-(sss+philHealth);
output = empName+ " "+ daysWorked +"
"+grossSalary+" "+sss+"
"+philHealth+" "+monthlySalary;
System.out.println(output);} } }

CS 112: Fundamentals of Programming


26
Chapter 5
Formative Assessment 1
1.
Program Design

Flowcharts created using Lucidchart at www.lucid.app


Program Coding

import javax.swing.*;
public class ArrayDirectory{
public static void main (String[] args) {
String info[][] = new String[5][3];
System.out.println("DIRECTORY\n");

for(int i=0; i<info.length;i++){


for(int j=0;j<info[i].length;j++){
if(j==0){
info[i][j] = JOptionPane.showInputDialog("Enter Name: ");
System.out.println("Name: "+ info[i][j]); }
else if (j==1){
info[i][j] = JOptionPane.showInputDialog("Enter Telephone Number: ");
System.out.println("Telephone Number: "+ info[i][j]); }
else {
info[i][j] = JOptionPane.showInputDialog("Enter Address: ");
System.out.println("Address: "+ info[i][j]+"\n"); }
}
}
} }

CS 112: Fundamentals of Programming


27
2.
Program Design

Flowcharts created using Lucidchart at www.lucid.app


Program Coding

import javax.swing.*;
public class CartesianPlane{
public static void main (String[] args) {
int pair[][] = new int[4][2];
for(int x=0; x<pair.length;x++){
for(int y=0;y<pair[x].length;y++){
if(y==0){
pair[x][y]= Integer.parseInt(JOptionPane.showInputDialog("Enter X Axis Point: ")); }

if (y==1){
pair[x][y]= Integer.parseInt(JOptionPane.showInputDialog("Enter Y Axis Point: ")); }

if((pair[x][0]>0) && (pair[x][1]>0)){


System.out.println("Pair " + (x+1) + ": ("+pair[x][0]+","+pair[x][1]+") is in Quadrant 1");}

if((pair[x][0]<0) && (pair[x][1]>0)){


System.out.println("Pair " + (x+1) + ": ("+pair[x][0]+","+pair[x][1]+") is in Quadrant 2");}

CS 112: Fundamentals of Programming


28
if((pair[x][0]<0) && (pair[x][1]<0)){
System.out.println("Pair " + (x+1) + ": ("+pair[x][0]+","+pair[x][1]+") is in Quadrant 3");}

if((pair[x][0]>0) && (pair[x][1]<0)){


System.out.println("Pair " + (x+1) + ": ("+pair[x][0]+","+pair[x][1]+") is in Quadrant 4");}
} } } }

CS 112: Fundamentals of Programming


29

You might also like