Professional Documents
Culture Documents
CS 112 MODULE Chapter 4-5 1st Sem 2021-2022
CS 112 MODULE Chapter 4-5 1st Sem 2021-2022
CS 112
(Insert Design)
NOR-AINE M. CORPUZ
DANILYN A. FLORES
NOR-AINE M. CORPUZ
2021
CS 112
NOR-AINE M. CORPUZ
DANILYN A. FLORES
2021
USM MISSION
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
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.
1. if
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
Syntax:
if(boolean_expression) { true
boolean_exp
statement;
statement1; }
statement
Fig. 38. Flowchart for if
Process:
grade = 68 Display “Congratulations!”
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);
}}
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
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
Process:
Display “You Passed!” STOP
grade = 68
Program Coding
public class grade {
public static void main(String []args) {
int grade = 68;
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
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
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
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
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!”); }
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
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);
}}
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
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)
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)
1. while
Syntax:
boolean_expr
while(boolean_expression) { false
statement1; true
statement2;
... statements
increment/decrement; } Fig. 44. Flowchart of while
Start i=4
Example 1
Syntax:
do { statements
statement1;
statement2;
... true false
boolean_expr
increment/decrement; }
while(boolean_expression);
Fig. 48. Flowchart of do-while
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
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:
where,
InitializationExpression – initializes the loop variable
LoopCondition – compares the loop variable to some limit value
StepExpression – updates the loop variable
statements
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
true
Display i
FORMATIVE ASSESSMENT 2
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)
SUMMATIVE ASSESSMENT
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.
Introduction to Arrays
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[ ];
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:
…
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.
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.
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,
Multidimensional Arrays
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:
SUMMATIVE ASSESSMENT
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.
Appendix A
Appendix B
Appendix C
Appendix E
Appendix F
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
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.";}
2.
Problem Analysis Program Design
Process:
remarks = “ ”
average =
(CS112+CS113+CS114+
GE1+SocSci1+PE1+NST
P)/7
remarks = “PASSED!” if
average >=74.5 otherwise
remarks = “FAILED!”
Formative Assessment 2
1.
Process:
count = 1
count++
Output:
name while count is <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
Program Design
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);} } }
import javax.swing.*;
public class ArrayDirectory{
public static void main (String[] args) {
String info[][] = new String[5][3];
System.out.println("DIRECTORY\n");
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: ")); }