Sunteți pe pagina 1din 123

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St.

, Baguio City, Philippines (074) 444-8246 loc 281

Programming Fundamentals 1 Laboratory (IT 112L) Computer Programming 1 (ICS 112L)

Course Manual

Prepared by The faculty of the IT/CS department

June 2013

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

Syllabus
OBJECTIVES OF THE SCHOOL The School of Computing and Information Sciences (SCIS) is envisioned as the universitys instrument in bridging the digital divide between the academe, industry and community by being an excellent center for education in computing and information sciences. Being so, SCIS will continuously offer updated computing and information science programs committed to nurture the Christian Spirit of creative, competent and socially involved individuals who are advocates of peace and progress. Christian Spirit. SCIS rears Information and Computing professionals and practitioners who are grounded on Christian values making them responsible and ethical citizens of the globe. Creativity. SCIS trains potential Information and Computing professionals in abstraction and analysis processes enabling them to participate in lifelong learning and adaptation to the fast changing environment. Competence. SCIS equips faculty and students with appropriate knowledge and computing skills. Social Involvement. SCIS provides continuing Computing and Information solutions, education, consultancy and assistance to members of the community who are faced with issues and problems. I. DESCRIPTIVE TITLE Programming Fundamentals 1 / Computer Programming 1 II. COURSE NUMBER IT 112L / ICS 112L III. PREREQUISITE SUBJECTS NONE III. COURSE DESCRIPTION Writing computer programs through a programming language is a basic skill for potential Information and Computing professionals. IT 112L requires students to design, develop and test programs using a programming language (i.e. Java ). Program development exercises will be done so that the students will realize the essence of the problem solving process, algorithm, syntax and semantics, variables, operators, primitive data types, expressions, input/output, the sequence construct, the conditional

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

construct, the iteration construct, functions/methods, parameter passing, program decomposition, aggregate data types and user-defined types. IV. COURSE OBJECTIVES With guidance, instructions and lectures, the student is expected to be able to acquire and develop the knowledge, skills, attitudes and values espoused by the University: On Competence: Be able to develop algorithms for simple applications and hypothetical problems Be able to implement algorithms by writing Java source codes for simple applications and hypothetical problems Be able to choose appropriate program constructs and data representation for any given programming task Be able to apply the program decomposition or top-down programming approach ( i.e. Be able to write programs composed of functions/methods that are aggregated through function/method invocation and parameter passing) Be able to write programs that use one-dimensional arrays, strings and records.

On Creativity, Research and Scholarly Work

Enhance the problem solving skills of the students so that they are able to produce programming solutions to typical programming problems Provide an opportunity that will allow students to manifest their innovative character through problem solving exercises

On Social Involvement and Christian Spirit Encourage the students to explore solutions to programming problems that have applications on their personal environment Let the students realize that the knowledge and skills they get from the course are necessary for them to understand and participate in the business processes inherent with the environment with which they are members

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

Other Objectives Demonstrate punctuality in accomplishing tasks and functions as a student Show appropriate behavior in dealing with classmates, authorities and mentors while accomplishing the course requirements Be oriented with ways of acquiring updated knowledge in the field of programming Possess in-depth understanding of the fact that programming is a subject area that encompasses all other fields of study. Number of Meetings (1.5 hours per meeting) 2 Strategies

V. COURSE CONTENT Content

Using an Integrated Development Environment (i.e. JCreator) Writing a source code Compiling a source code Executing a Bytecode Understanding the structure of a correct Java Program Developing and implementing algorithms for problems that require variable declaration, assignment statements, using arithmetic operators, simple output statements, input statements, String, type casting and the sequence program construct

Hands-on Encoding, compiling and executing given correct programs Modification of a given correct program Hands-on programming Programming Projects Programming Quiz/Exam LMS-Based Online Quiz/Exam on knowledge, analysis and synthesis questions Hands-on programming Programming Project Programming Quiz/Exam LMS-Based Online Quiz/Exam on knowledge, analysis and synthesis questions

10

Developing and implementing algorithms that involve conditional constructs and 10 Iteration constructs

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

Developing and implementing algorithms that require method definitions and 10 invocations (Program decomposition), One-dimensional array, Linear Search, Simple Sorting algorithms, and Parallel Arrays

Hands-on programming Programming Projects Programming Quiz/Exam LMS-Based Online Quiz/Exam on knowledge, analysis and synthesis questions

VI. COURSE REQUIREMENTS FOR EVALUATION A. Short programming exercises (Programs will be collected/submitted on specified deadlines. Late submissions will be required for students who will not be able to cope with the deadlines. However, the maximum score that will be given to a late program is 50% of the highest score earned by students who submitted the requirement on time.) B. Cases and Programming Projects (Projects will be collected/submitted on specified deadlines. Late submissions will be required for students who will not be able to beat the deadlines. However, the maximum score that will be given to a late project is 50% of the highest score earned by students who submitted the project on time.) C. Major Quizzes and Examinations ( The university policies for special quizzes and exams will be followed: Students who will miss a quiz should present an Excused Slip obtained from the Student Affairs Office as soon as he/she attends the class after the absence. Students who will miss a major exam should present a Special Examination Permit obtained from the Deans Office as soon as he/she attends the class after the absence.) VII. ATTENDANCE and GRADING SYSTEM University policies on attendance will be implemented. Three Periodic Grades (prelim-PG, midterm-MG, and tentative final grade-TFG) and a final grade-FG will be given. The final subject grade (FG) is computed by the formula FG = (PG+MG+TFG)/3. Grades (PG, MG and TFG) are computed based on students scores on activities for the prelim period, midterm period, and final period respectively. A class standing grade (CSG) is computed using the scores for activities and quizzes. An examination grade (EG) is computed based on the examination score. The scores

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

are proportionately rated based on a 50-100 grade scale through the formula

CSG = ((Students Total CS Score)/(Perfect CS Score))*50+50 EG = ((Students Exam Score)/(Perfect Exam Score))*50+50 PG = (CSG + EG)/2 MG = (CSG + EG)/2 TFG = (CSG + EG)/2

A PG, MG or FG that is lower than or equal to 65 is set to 65 and a PG, MG or FG that is equal to 100 is set to 99. Unless the student can present concrete evidences that the computation of his/her is erroneous, the grade cannot be changed. If necessary, request for correction of grade must be done personally by the student. The student should bring his/her compilation of his/her examination/quiz papers to the instructor when the latter is available for consultation in the faculty room. Phone calls and visits to the facultys residence by the student for the purpose of grade verification will not be entertained. Any form of cheating is not allowed in the course. A student who cheats will be given zero on the quiz/exam/requirement for which cheating is done. (See student handbook). The following are some of the behaviors that are considered acts of cheating Opening of notes, books and the like during classroom tests regardless of whether the student was able to copy from the material or not. Making glances at classmates papers/Copying from classmates paper during tests is cheating Using communication paraphernalia such as cellular phones, ipads, tabs, and the like during examinations is considered cheating. Copying/ sharing outputs for any homework or project is considered cheating Writing notes on walls, chairs, floor, dress, body and the like for purposes of classroom exams. During examinations, it is any students responsibility to guard his/her papers/terminals accessibility to his/her classmates. Any student who willfully lets his/her answers be copied by other students will be subjected to the same penalty as the cheaters.

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

VIII. MATERIALS & REFERENCES Activity Manuals (This manual This manual will be given in piecemeal fashion because write-ups of some activities includes solutions of previous activities.) and Course Notes prepared by the instructor that are disseminated through the SLU Learning Management System(course area in my.slu.edu.ph) Knuth, D.(2005). The Art of Computer Programming Liang, D. (2005). Introduction to Java Programming: Comprehensive Version Lewis, J. (2004). Java Software Solutions for AP Computer Science: Foundations for Program Design Lewis, J. et al., (2012). Java Foundations: Introduction to Program Design and Data Structures. Pearson International Edition. (Older editions may be used) Java Programming Language manuals and Documentations Microsystems/Java Educational Development Initiatives/Oracle Inc. from Sun

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

IT 112L Programming Fundamentals I Laboratory Prelim Activity Number 1 Objectives 1. Know how to create a Java source program using an Integrated Development Environment(IDE) [JCreator] 2. Know how to compile a Java source program into Bytecode using an IDE (Use JCreator) 3. Know how to run a compiled Java program using an IDE (Use JCreator) 4. Become familiar with the structure of a Java Program with a main method (Executable program) 5. Become familiar with the output statement of the form System.out.println() 6. Know the implication of the rule that the Java programming language is case-sensitive [i.e. The keywords import, public, class, static, and void are in lowercases (small letters). The identifiers String and System begin with capital letters. The identifiers main and args are in lowercase] Activities 1. Open/Run the JCreator. (If available, click on the shortcut icon on the desktop. If there is no shortcut icon, open the program form start. ) 2. Through JCreator, create a file containing the program shown below. You have to type your name as the author of the program. You should indicate the date. Do not miss or misspell a symbol or word. /* is a part of the source code. You should type starting from /*. (File, New, Java File) 3. Save and compile the program. (Choose Build File or click the compile file icon). If there are error messages, fix the problem and compile again. Repeat this process until program compilation results to no error. 4. Run the program (Run) and study the output against the program 5. Modify the program so that the output on screen will be different from the "hello world in a box formed by asterisks. For example, let the output of the program be typical of the content of a calling card (your calling card). 6. Save your final program in your personal memory device (memory stick ). Erase the file that you may have temporarily saved in the computer that you are using.

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

/** *Author: ( Last Name, First Name, Middle Initial ) *Programming Date : _______________________ *Activity Name and Number : Prelim Activity 1 */ //This source code should be saved in a file called Exer1.java import java.lang.*; // import statement public class Exer1{ // Class declaration public static void main(String[] args) { // main method declaration System.out.println("************************************"); System.out.println("* *"); System.out.println("* *"); System.out.println("* hello world *"); System.out.println("* *"); System.out.println("* *"); System.out.println("************************************"); System.exit(0); // terminate the program } // end of main method } // end of Exer1 class

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

Pointers for further reading: The following are some of the important points that the you need to be familiar with. Your Java programs should always end with the .java extension. Filenames should match the name of your public class. For example, if the name of your public class is Hello, you should save it in a file called Hello.java. You should write comments in your code explaining what a certain class does, or what a certain method do. Comments are notes included in a code for documentation purposes. The comments are not part of the program and they do not affect the flow of the program. Single line comments starts with //. All the text after // are treated as comments. For example, // This is a single line comment Multiline comments starts with a /* and ends with a */. All text in between the two delimiters (/* and */ ) are treated as comments. Unlike single line comments, the multiline comment can span multiple lines. For example, /* this is an example of multiline comments */ Special Javadoc comments are used for generating an HTML documentation for your Java programs. You can create javadoc comments by starting the line with /** and ending it with */. Like multiline comment, the special javadoc comment can span lines. It can also contain certain tags to add more information to your comments. For example, /** This is an example of special java doc comments used for \n generating an html documentation. It uses tags like: @author Francisco Balagtas @version 1.2 */ A statement is one or more lines of code terminated by a semicolon.

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

Example of a single statement System.out.println(Hello world); A block is one or more statements bounded by a pair of an opening curly brace and closing curly brace that groups the statements as one unit. Block statements can be nested indefinitely. ( A block may be inside a block.) Any amount of white space is allowed. Example of a block public static void main( String[] args ) { System.out.println("Hello"); System.out.println("world"); } // end of main

In creating blocks, you can place the opening curly brace in line with the statement, for example,

public static void main( String[] args ){ } // end of main or you can place the curly brace on the next line, for example public static void main( String[] args ) { } // end of main It is conventional to indent the next statements after the start of a block, for example,

public static void main( String[] args ){ System.out.println("Hello"); System.out.println("world"); } // end of main You may encounter three kinds of errors as you develop your programs: compile-time error, runtime error and logical error. The compiler checks to make sure that you are using the correct syntax. If you have any statement that does not conform to the syntactic rules of the language, the compiler will produce a syntax error. The compiler also tries to find other problems, such as the use of incompatible types of data. The syntax might be technically correct, but you may be attempting to do something that the language doesnt semantically allow. Any error identified by the compiler is called a compile-time error. If a compile-time error occurs, an executable version of the program is not created. The second kind of problem occurs during program execution. It is

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

called run-time error and causes the program to terminate abnormally. For example, if we attempt to divide by zero, the program will crash and halt execution at that point. Because the operation is undefined, the system simply abandons its attempt to continue processing your program. The best programs are robust; that is, they avoid as many run-time errors as possible. For example, the program code could guard against the possibility of dividing by zero and handle the situation appropriately if it arises. In Java, many run-time problems are called exceptions that can be caught and dealt with accordingly. The third kind of software problem is logical error. In this case, the software compiles and executes without complaint, but it produces incorrect results. For example, a logical error occurs when a value is calculated incorrectly or when a graphical button does not appear in the correct place. A programmer must test the program thoroughly, comparing the expected results to those that actually occur. When defects are found, they must be traced back to the source of the problem in the code and corrected. The process of finding and correcting defects in a program is called debugging. Logical errors can manifest themselves in many ways, and the actual root cause might be difficult to discover. (Java Foundations by J. Lewis, et al.)

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

IT 112L Programming Fundamentals I Laboratory Prelim Activity Number 2

Objectives 1. Be able to write programs that have assignment statements 2. Use the data types int and double 2.1. Realize that variable declared with the int data type must be assigned whole numbers only. 2.2. Realize that a variable declared with the double data type must be assigned real numbers (i.e. numbers with or without a decimal point) 3. Know the rules for creating identifiers The names of classes, methods and variables are called identifiers. In programming, there are symbols that cannot be made part of identifier. For example, the space character cannot be made a part of an identifier (e.g. My Class is not a valid identifier). Although numeral digits may be made part of an identifier, a numeral digit cannot be the first character of an identifier (e.g. 2Name is not a valid identifier.) 4. Follow the convention for naming classes in Java programming In Java programming, the Pascal-case format is the convention followed when naming a class. The Pascal-case format is such that the first letter of the identifier is a capital letter and when words are concatenated to form an identifier, the first letter of every word in the identifier should be capitalized. (e.g. NameOfClass). 5. Follow the convention in naming variables in Java programming In Java programming, the Camel-case format is the convention for naming variables. The Camelcase format is such that an identifier begins with a small letter and when words are concatenated to form an identifier, the second word, third word, etc. should begin with a capital letter (i.e. areaOfCircle). Activities: 1. Using JCreator, encode, compile and test the program given below (the Circle class). 2. Understand the program. Verify that it implements the given algorithm. 3. Create a program that computes and shows the perimeter and the area of a Rectangle with a given length and width (Rectangle class). Show the appropriate algorithm in the same way as done with the Circle class. Take note that a rectangle has a length and a width. Instead of circumference, a rectangle has a perimeter. The perimeter of a rectangle is 2*length + 2*width. The area of a rectangle is length*width. Save your final program in your personal memory device ( flash drive, memory stick). The program will be submitted later. 4. Create a program that computes and shows the perimeter and the area of a square with a given side(Square class). Show the appropriate algorithm in the same way as done with the Circle class.

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

Take note that a square has a side. The perimeter of a square is 4*side. The area of a square is side*side. Save your final program in your personal memory device ( flash drive, memory stick). The program will be submitted later. 5. Create a program that computes and shows the perimeter and the area of a Right Triangle with a given base, height and hypotenuse(RightTriangle class). Show the appropriate algorithm in the same way as done with the Circle class. Take note that a Right Triangle has a base and a height. The perimeter of a right triangle is base + height + hypotenuse. The area is 0.50*base*height. Save your final program in your personal memory device ( flash drive, memory stick). The program will be submitted later. ---------------------------------------------------------------------------------------------------------// The filename for the following source code must be Circle.java /** * Name: _____________________________ * Programming Date: ___________________ * Activity Name and Number: Prelim Activity 2 --------------------------------------------------------------Input: Radius of a circle (radius) Processes: Compute the circumference of the circle Compute the area of the circle Display results Output: circumference, area -----------------------------------------------------------------Algorithm: 1. Assign the radius of the circle 2. Compute the circumference : circumference = 2*PI*radius 3. Compute the area: area = PI*radius*radius 4. Show the radius of the circle 5. Show the circumference of the circle 6. Show the area of the circle -----------------------------------------------------------------------------------****/ import java.lang.*; public class Circle{ public static void main (String [] args) { /* Every variable must be declared with a data type with reference to the kind of value that is to be assigned to it. If the value for a radius is constrained to a whole number and circumference and area may be floating point numbers (A floating point number is a number with the decimal point), the variables radius, circumference and areaOfCircle must be respectively declared with the int, double and double data types as shown in the following lines */ int radius; double circumference; double areaOfCircle; // Assignment statement that stores a value to a variable. radius=10; //Assigns the integer value 10 to radius.

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

//A mathematical expression represents a value that may be assigned to a variable circumference =2* 3.1416*radius; //Instead of typing 3.1.416, you may type Math.PI. areaOfCircle = 3.1416 * radius *radius; //Show some outputs on the screen System.out.println( ); System.out.println( ); System.out.println(" *********************************************"); System.out.println(" * *"); System.out.println(" * *"); System.out.println(" * Radius of circle is " + radius +" *"); System.out.println(" * Circumference of circle is " + circumference+" *"); System.out.println(" * Area of circle is " + areaOfCircle +" *"); System.out.println(" * *"); System.out.println(" * *"); System.out.println(" *********************************************"); } // end of main method } // end of class

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

Pointers for further reading Identifiers are tokens that represent names of variables, methods, classes, etc. Examples of identifiers : Hello, main, System, Out Java identifiers are case-sensitive. This means that the identifier: Hello is not the same as hello. Identifiers must begin with either a letter, an underscore _, or a dollar sign $. Letters may be lower or upper case. Subsequent characters may use numbers 0 to 9. Note: No space character in the identifier! Java keywords, like class, public, void, etc. cannot be identifiers Keywords are predefined identifiers reserved by Java for a specific purpose. The following is the list of Java keywords.

It is conventional to capitalize the first letter of the class name (Pascal-case). Example ThisIsAnExampleOfClassName For names of methods and variables, the convention is that the first letter of the identifier should start with a small letter (Camel-case) Example thisIsAnExampleOfMethodName In case of multi-word identifiers that are not intended as names of classes, use capital letters to indicate the start of the word except the first word.

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

Example: charArray, fileNumber, firstName.

Avoid using underscores at the start of the identifier such as _read or _write. Literals are tokens that have values that do not change or are constant. The different types of literals in Java are: Integer Literals, Floating-Point Literals, Boolean Literals, Character Literals and String Literals. Integer literals come in different formats: decimal (base 10), hexadecimal (base 16), and octal (base 8). In using integer literals in our program, we have to follow some special notations. For decimal numbers, we have no special notations. We just write a decimal number as it is. For hexadecimal numbers, it should be preceded by 0x or 0X. For octals, they are preceded by 0. For example, consider the number 12. It's decimal representation is 12, while in hexadecimal, it is 0xC, and in octal, it is equivalent to 014. Integer literals default to the data type int. An int is a signed 32-bit value. In some cases, you may wish to force integer literal to the data type long by appending the l or L character. A long is a signed 64-bit value. We will cover more on data types later. Floating point literals represent decimals with fractional parts. An example is 3.1415. Floating point literals can be expressed in standard or scientific notations. For example, 583.45 is in standard notation, while 5.8345e2 is in scientific notation. Floating point literals default to the data type double which is a 64-bit value. To use a smaller precision (32-bit) float, just append the f or F character. Boolean literals have only two values, true or false. Character Literals represent single Unicode characters. A Unicode character is a 16-bit character set that replaces the 8-bit ASCII character set. Unicode allows the inclusion of symbols and special characters from other languages. To use a character literal, enclose the character in single quote delimiters. For example, the letter a, is represented as a.

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

To use special characters such as a newline character, a backslash is used followed by the character code. For example, \n for the newline character, \r for the carriage return, \b for backspace. String literals represent multiple characters and are enclosed by double quotes. An example of a string literal is, Hello World. The Java programming language defines eight primitive data types. -boolean (for logical ), -char (for textual), -byte, short, int, long (integral), -double and float (floating point). A boolean data type represents two states: true and false. An Example is, boolean result = true; The example declares a variable named result as boolean type and assigns it a value of true. A character data type (char), represents a single Unicode character. It must have its literal enclosed in single quotes( ). For example, a //The letter a \t //A tab To represent special characters like ' (single quotes) or " (double quotes), use the escape character \. For example, \'' //for single quotes '\"' //for double quotes A String represents a data type(reference type) that contains multiple characters. String is not a primitive data type, it is a class. It has its literal enclosed in double quotes(). Example, String message=Hello world! Integral data types in Java uses three forms decimal, octal or hexadecimal. Examples are, 2 //The decimal value 2 077 //The leading 0 indicates an octal value 0xBACC //The leading 0x indicates a hexadecimal value An integral value (whole number) in a program statement has int as its default data type. You can define a long value by appending the letter l or L. Data types are sets of values. (The numerical values are usually represented as range of values. The following are the integral data types with their storage sizes and ranges

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

Integer length (Storage size per value) 8 bits 16 bits 32 bits 64 bits

Name of type byte short int long

Range (-27) to (27- 1) -128 to 127 (-215) to (215-1) (-231) to (231- 1) (-263) to (263-1)

In defining a long value, a lowercase L is not recommended because it is hard to distinguish it from the digit 1. Floating point types has double as default data type. Floating-point literal includes either a decimal point or one of the following, E or e //(denote multiplication by a power of 10) F or f //(float) D or d //(double) Examples 3.14 6.02E23 2.718F 123.4E+306D

//A simple floating-point value (a double) //A large floating-point value 6.02X1023. //A simple float size value //A large double value with redundant D

In the example shown above, the 23 after the E in the second example is implicitly positive. That example is equivalent to 6.02E+23. The following are the floating point types with their storage sizes and ranges Storage size 32 bits 64 bits Name of Type float double Range Approximately 3.4e+38 with 7 significant digits Approximately 1.7e+308 with 15 significant digits

A variable is an item of data used to store state of objects. A variable has a data type and a name.

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

The data type indicates the type of value that the variable can hold. Hence, the data type defines the possible values for the variable. The variable name must follow rules for identifiers. Syntax for declaring a variable <data type> <name> [=initial value]; Values enclosed in <> are required values, while those values enclosed in [] are optional. Examples /*declare a data type with variable name result and boolean data type */ boolean result; /*declare a data type with variable name option and char data type */ char option; option = 'C'; //assign 'C' to option /*declare a data type with variable name grade, double data type and initialized to 0.0 */ double grade = 0.0;

It always good to initialize your variables as you declare them. Use descriptive names for your variables. Like for example, if you want to have a variable that contains a grade for a student, name it as, grade and not just some random letters you choose. Declare one variable per line of code. For example, the variable declarations, double exam=0; double quiz=10; double grade = 0; is preferred over the declaration, double exam=0, quiz=10, grade=0;

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

IT 112L Programming Fundamentals I Laboratory Prelim Activity Number 3 Objectives 1. Be able to write programs that have assignment statements 2. Be able to use some features of the Math class that is included in the java.lang package. Use the value of PI ( a constant) defined in the Math class (Math.PI) Use the method in the Math class (Math.sqrt( ? )) that returns the square root of a given number Notes: By including the statement import java.lang.*; in your program, you are allowing the program to access/use the classes that are saved in the java.lang package/folder. One of the classes in java.lang is the Math class. The value of the constant PI is defined in the Math class. To access the value, use the expression Math.PI. The Math class includes a method/program that may be used to get the positive square root of a number. To use the method/program, use the expression Math.sqrt( number ). Replace number by the actual number or expression. For example, Math.sqrt(10) results to the positive square root of 10. Math.sqrt( 10*area) results to the positive square root of the value of the expression 10*area. Activities: 1. Using JCreator, encode, compile and test the program given below (the Circle2 class). 2. Understand the program. Verify that it implements the given algorithm. 3. Create a program for determining the hypotenuse of a Right Triangle with a given base and height (RightTriangle2 class). Show the appropriate algorithm in the same way as done with the Circle2 class. Take note that the hypotenuse of a Right Triangle with a given base and height is equal to the square root of the sum of base2 + height2. Recall the Pythagorean Theorem that says if a, b and c are respective the base, height and hypotenuse of a Right Triangle, c2=a2+b2. Hence, if you are interested with c, c = square root of (a2+b2). Save your final program in your personal memory device ( flash drive, memory stick).

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

/* // The filename for the following source code must be Circle2.java Problem: Write a program that will show the radius of a circle with a given area. Analysis: Input: area of a circle (area) Processes: Compute the radius of the circle Display the data associated with the circle Output: radius Algorithm: 1. Assign the area of the circle 2. Compute the radius: radius = square root of (area/PI) 3. Show the given area of a circle 4. Show the computed radius of the circle with a given area */ import java.lang.*; public class Circle2{ public static void main (String [] args) { double radius; // double is the appropriate data type of radius because the value // of radius may be a floating point number. double area; area = 100.0; // Assigns 100 as the area of a circle radius= Math.sqrt ( area/ Math.PI) ; //computes the radius of the circle // with a given area. //Show data about the circle System.out.println( ); System.out.println( ); System.out.println(" *********************************************"); System.out.println(" * Given area of circle = " + area + " *"); System.out.println(" * Computed radius of the circle = " + radius+" *"); System.out.println(" *********************************************"); } // end of the main method } // end of Circle2 class

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

IT 112L Programming Fundamentals I Laboratory Prelim Activity Number 4 Notes: You should finish prelim activity number 2 before working on this activity. Hence, you should already have your own program named Circle.java, Rectangle.java, Square.java and RightTriangle.java. You should use the Scanner class to allow reading of values through the keyboard when your program is executing. o You must see to it that your program begins with the statement import java.util.Scanner; Such statement allows you to use the Scanner class. o Your main method should include the statement Scanner kbd = new Scanner(System.in); kbd is an identifier so you may change it with an equally descriptive name. For example: Scanner keyboard = new Scanner(System.in); To assign an integer to the int variable radius, use the statement/s String readString=; readString = kbd.nextLine(); radius = Integer.parseInt(readString); OR radius = Integer.parseInt(kbd.nextLine()); OR radius = kbd.nextInt(); o To assign a value to the double variable radius, use the statement/s readString = kbd.nextLine(); radius = Double.parseDouble(readString); OR radius = Double.parseDouble(kbd.nextLine()); OR radius = kbd.nextDouble();

Required: 1. Modify your Circle.java program so that the radius of the circle will be read from the keyboard at run time through the Scanner class. (i.e. The value of radius will be entered when the program is executed.) An appropriate prompt message (e.g. Please enter the radius of the circle: ) should be provided. Save your program as Circle3.java

Expected Program:

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

------------------------------------------------------------------------------------------------------// The filename for the following source code must be Circle3.java /** Name: _____________________________ Programming Date: ___________________ Activity Name and Number: Prelim Activity 4 Problem: Write a program that computes and shows the area and the circumference of a circle with a given radius. Let the radius be entered through the keyboard at program runtime. Analysis: Input: Radius of a circle (radius) Processes: Read the radius of the circle Compute the circumference of the circle Compute the area of the circle Display results Output: circumference, area Algorithm: 1. Read/Accept the radius of the circle 2. Compute the circumference : circumference = 2*PI*radius 3. Compute the area: area = PI*radius* radius 4. Show the radius of the circle 5. Show the circumference of the circle 6. Show the area of the circle -----------------------------------------------------------------------------------------****/ import java.lang.*; import java.util.Scanner; public class Circle3{ public static void main (String [] args) { Scanner kbd = new Scanner(System.in); // Make an object of Scanner that represents the //keyboard int radius; // variable declaration double circumference; // variable declaration double areaOfCircle; // variable declaration // Read the radius. System.out.print(Type the value of radius then press the enter key: ); // Print a prompt // message radius= Integer.parseInt(kbd.nextLine()); //Assigns an integer entered through //the keyboard to radius circumference =2* 3.1416*radius; //A mathematical expression represents a value that // is assigned to the variable circumference areaOfCircle = 3.1416 * radius *radius; // A mathematical expression represents a value

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

// that is assigned to the variable areaOfCircle //Following are statements that prints strings on the output screen System.out.println( ); System.out.println( ); System.out.println(" *********************************************"); System.out.println(" * Radius of circle is " + radius +" *"); System.out.println(" * Circumference of circle is " + circumference+" *"); System.out.println(" * Area of circle is " + areaOfCircle +" *"); System.out.println(" *********************************************"); } // end of main method } // end of class 1. Modify your Rectangle.java program so that the values for the length and the width will be read from the keyboard at run time through the Scanner class. (i.e. The value of length and width will be entered when the program is executed.) Appropriate prompt messages(e.g. Enter the length of the rectangle: and Enter the width of the rectangle:) should be provided. Save the class as Rectangle2.java. 2. Modify your Square.java program so that the measurement of the side of the square will be read from the keyboard at run time through the Scanner class. (i.e. The value of side will be entered when the program is executed.) An appropriate prompt message(e.g. Please enter the measure of a side of the square:) should be provided. Save the class as Square2.java. 3. Modify your RightTriangle.java program so that the values for the base and the height will be read from the keyboard at run time through the Scanner class. (i.e. The value of base and height will be entered when the program is executed.) Appropriate prompt messages(e.g. Enter the base of the triangle: and Enter the height of the triangle:) should be provided . Save the class as RightTriangle3.java.

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

IT 112L Programming Fundamentals I Laboratory Prelim Activity Number 5

Required: Compile, edit if necessary, and run the program given below. Then, insert Java statements that will make the program do the tasks indicated in the numbered comments. Try to accomplish one task at a time, that is, compile and check if your program runs correctly after each insertion. import java.util.*; public class Exercise5 { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); // get keyboard input for three integers System.out.print("First Number: "); int n1 = Integer.parseInt(keyboard.nextLine()); System.out.print("Second Number: "); int n2 = Integer.parseInt(keyboard.nextLine()); System.out.print("Third Number: "); int n3 = Integer.parseInt(keyboard.nextLine()); // display the three numbers System.out.println ("You entered the numbers " + n1 + ", " + n2 + " and " + n3); // add the three numbers and store it in another int variable named sum int sum = n1 + n2 + n3; // display the sum System.out.println("\nThe sum of the three numbers is " + sum); // divide the first number by the second and display the value int q1 = n1/n2; System.out.println("\nThe expression used computed the integer quotient : " + q1); double q2 = (double) n1/n2; System.out.println("\nThe expression used computed the actual quotient: " + q2); /*#1. Compute the product of the three numbers, store it in another integer variable and display this value. INSERT THE CODES BELOW... */ /* #2. Get the sum of the first two numbers and divide it by the third number, compute only for the integer quotient and display the value. INSERT THE CODES BELOW... */ /* #3. Get the sum of the first two numbers and divide it by the third number, compute for the exact quotient and display the value. INSERT THE CODES BELOW... */

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

/* #4. Compute the average of the three numbers and display the value. INSERT CODE BELOW... */ /* #5. Compute the square of each number and display the results INSERT CODE BELOW... */ } // End of the main method } // End of class Exercise5

------------------------------------------------------------------------------------------------------------------------------Guide for further reading. The Java programming language supports various arithmetic operators for all floating-point and integer numbers. These operators are + (addition), - (subtraction), * (multiplication), / (division) % (modulo).

When an integer (byte, short, int, long) and a floating-point (float, double) number are used as operands to a single arithmetic operator, the result is floating point. The integer is implicitly converted to a floating-point number before the operation takes place. Other ways of writing operators Operator Use += op1 += op2 -= *= /= %= op1 -= op2 op1 *= op2 op1 /= op2 op1 %= op2

Equivalent to op1 = op1 + op2 op1 = op1 - op2 op1 = op1 * op2 op1 = op1 / op2 op1 = op1 % op2

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

Other operators Operator ++

Use op++

Description Postfix ++ Increments op by 1; evaluates to the value of op before it was incremented Prefix ++ Increments op by 1; evaluates to the value of op after it was incremented Postfix -Decrements op by 1; evaluates to the value of op before it was decremented Prefix -Decrements op by 1; evaluates to the value of op after it was decremented

++

++op

--

op--

--

--op

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

IT 112L Programming Fundamentals I Laboratory Prelim Activity Number 6 Required: Write a Java program that will be used at the check-out counter of Aling Nena's Sari-Sari Store with the following assumptions. Aling Nena's customers always buy only one type of product, but may buy one or more pieces of the said product. For example, a customer may buy a dozen eggs. Depending on the customer, Aling Nena may decide to give the customer a discount, expressed as an integer value from 1 to 100, which indicates the percentage deducted from the total amount of the customer's purchase. For example, assuming that eggs cost P5.00 a piece, a dozen eggs would cost a total of P60.00, and if the customer is then given a 10 percent discount, then the customer will have to pay only P54.00 for one dozen of eggs. Customers who are not entitled to discounts are given zero (0) percent discount. Aling Nena's customers always pay in cash, and the cash amount tendered is always greater than or equal to the total purchase amount. Your program must calculate the change given to the customer. The filename of your source code for this requirement should be Exercise6.java. Depicted below are sample input and outputs when the program is executed: 1. Sample Input: Product: eggs Quantity: 12 Unit Price: 5.00 Discount: 10 Cash Tendered: 100.00 Sample Output: Total Purchase Amount: 60.00 Total Discount: 6.00 Amount To Be Paid: 54.00 Change: 46.00 2. Sample Input: Product: milk Quantity: 3 Unit Price: 18.75 Discount: 0 Cash Tendered: 60.00 Sample Output: Total Purchase Amount: 56.25 Total Discount: 0.00 Amount To Be Paid: 56.25 Change: 3.75

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

3. Sample Input: Product: sardines Quantity: 2 Unit Price: 23.50 Discount: 25 Cash Tendered: 35.25 Sample Output: Total Purchase Amount: 47.00 Total Discount: 11.75 Amount To Be Paid: 35.25 Change: 0.00

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

IT 112L Programming Fundamentals I Laboratory Prelim Activity Number 7 Notes: You need to take note of the integer division rule in Java programming. ( An integer divided by an integer always results to an integer.) A remainder operator is available in Java programming. (amount % 1000 results to the remainder when amount is divided by 1000.)

Required: Write a program that will read the amount of money that will be withdrawn from an ATM (e.g. P500 or P1200) then compute and output the least number of peso bills( P100 peso bills, P500 peso bills, P1000 peso bills) that will be dispensed by the machine for the requested amount. Determine also the amount of money corresponding to each peso bill dispensed, the sum total of number of bills dispensed, and sum total of amounts per denomination as shown below. Assume that enough bills are always available from the machine. Assume further that the machine can only dispense P100 peso bills, P500 peso bills, and P1000 peso bills. Save your file using the filename:<your name>Dispenser.java. For example, if your name is Justine Bieber, your filename should be JustineBieberDispenser.java Include appropriate comments in your program. Sample Run: Enter amount to be withdrawn, whole numbers only: 3700 PESO BILLS QUANTITY DISPENSED ============ ================== P1000 3 P500 1 P100 2 ---------------TOTAL No Of Bills 6 AMOUNT ======== 3000.00 500.00 200.00 ---------------3700.00

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

IT 112L Programming Fundamentals I Laboratory Prelim Activity Number 8

Required: Complete the program with missing parts given below. /** Problem: Write a program for determining the roots of a quadratic equation. A quadratic equation has the form ax^2 + bx + c = 0. The numerical coefficients a, b and c should be entered at run time. The literal coefficient is assumed to be x (i.e. There is no need to read the literal coefficient). Notes: Quadratic Formula first root = (-b + Math.sqrt(b*b-4*a*c))/(2*a) second root = (-b - Math.sqrt(b*b - 4*a*c))/(2*a) Sample run: -----------------------------------------------------------Enter the coefficient of x squared (a):1 Enter the coefficient of x (b): -4 Enter the constant (c): 4 The roots of (1)x^2 + (-4)x + (4) = 0 are 2.00 and 2.00. ------------------------------------------------------------------------Analysis Inputs: Coefficients a, b and c Processes: Read the coefficients Compute the roots Show the roots Outputs: First root and second root Algorithm 1. Let a represent the coefficient of x squared 2. Let b represent the coefficient of x 3. Let c represent in constant 4. Let root1 represent the first root 5. Let root2 represent the second root 6. Show an introduction of the application/program 7. Read the value of a 8. Read the value of b 9. Read the value of c

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

10. Compute root1: root1 =( -b + Math.sqrt(b*b - 4*a*c))/(2*a) 11. Compute root2: root2 =( -b - Math.sqrt(b*b - 4*a*c))/(2*a) 12. Display the roots. ******/ import java.util.Scanner; import java.lang.*; public class QuadraticSolver{ public static void main(String[] args){ Scanner keyboard = new Scanner(System.in); double a=0, b=0, c=0; double root1=0, root2=0; System.out.println("This program determines the roots of a quadratic equation\n of the form ax^2 +bx +c = 0."); System.out.print("Enter the coefficient of x^2, a= "); _________________________________________; System.out.print("Enter the coefficient of x, b= "); _________________________________________; System.out.print("Enter the constant, c= "); _________________________________________; root1= (-b + Math.sqrt(b*b-4*a*c))/(2*a); _________________________________________; System.out.printf("%c%.2f%s%.2f%s%.2f%s%.2f%s%.2f%c%n",'(',a,") + (",b,") + (",c,") = 0 are ", root1, " and ", root2, '.'); System.exit(0); } //. End of the main method } // End of QuadraticSolver class

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

IT 112L Programming Fundamentals I Laboratory Prelim Activity Number 9 Introduction of the if statement/ The if-statement specifies that a statement (or block of code) will be executed if and only if a certain boolean statement is true. Syntax: if( boolean_expression ) statement; or if( boolean_expression ){ statement1; statement2; ... }

Problem: To determine if a student belongs to the deans list, the students average is computed. If the average is at least 85, the student belongs to the deans list. Assume that a student has earned grades for his/her 10 subjects for one semester. Each subject is with a corresponding number of units. The average grade should be computed with respect to the total number of units. Hence, to compute the average grade of a student, the products of subject grades and the corresponding units are added and the result is divided by the total number of units. Write a program that will compute the average grade of a student for a semester. The computer will then give the message Congratulations! You belong to the deans list or the message Sorry! You did not make it to the deans list. Do Better next term. whichever is appropriate. Since, the 10 grades and the corresponding number of units need not be printed as part of the required output (i.e. they are just input values), the program may be written using only one variable for the grades and one variable for the units. When the program is executed, the computer will ask the user to enter 10 pairs of subject grades and units. The computer will display the average grade of the student on the 10 subjects followed by an appropriate message. The following is a sample run of the required program. ----------------------------------------------------------------------------Enter the grade of the student for the 1st subject: 80 Enter the number of units for the 1st subject: 2 Enter the grade of the student for the 2nd subject: 85 Enter the number of units for the 2nd subject: 1 Enter the grade of the student for the 3rd subject: 88 Enter the number of units for the 3rd subject: 2 Enter the grade of the student for the 4th subject: 90 Enter the number of units for the 4th subject: 1

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

Enter the grade of the student for the 5th subject: 85 Enter the number of units for the 5th subject: 3 Enter the grade of the student for the 6th subject: 87 Enter the number of units for the 6th subject: 3 Enter the grade of the student for the 7th subject: 90 Enter the number of units for the 7th subject: 3 Enter the grade of the student for the 8th subject: 88 Enter the number of units for the 8th subject: 3 Enter the grade of the student for the 9th subject: 92 Enter the number of units for the 9th subject: 3 Enter the grade of the student for the 10th subject: 89 Enter the number of units for the 10th subject: 3 Your Average Grade = 87.66666666666667. Congratulations! You belong to the deans list. ------------------------------------------------------------------------------------------------------------Analysis : Input : 10 pairs of grades and units Processes: Read the grades and units Compute the sum of the products of grades and units Compute the total of the units Compute the average : (sum of products of grades and units)/total_units Show the average Give an appropriate message Output: Average, Message

Algorithm: 1. Let grade represent a grade for a subject 2. Let units represent number of units for a subject 3. Let totalGrade=0 where totalGrade represent the sum of the products of grades and corresponding units 4. Let totalUnits=0 where totalUnits represent the total number of units 5. Let average represent the average grade of the student 6. Read the first grade 7. Read the number of units for the first grade 8. Add the product of first grade and the corresponding units to totalGrade 9. Add the units for the first grade to totalUnits 10. Repeat steps 6, 7, 8 and 9 for the 2nd to the 10th grade 11. Compute the average where average = totalGrades/totalUnits 12. Display the average 13. If (average >= 85) print Congratulations! You belong to the dean's list." 14. If (average < 85) print Sorry! You did not make it to the dean's list. Do better next term." */

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

import java.lang.*; import java.util.Scanner; public class GradeAverage1 { public static void main(String[] args){ Scanner kbd = new Scanner(System.in); int grade=50; int units=0; int totalGrade=0; int totalUnits=0; double average=0.0; System.out.print("Enter the grade of the student for the 1st subject: "); grade = Integer.parseInt(kbd.nextLine()); System.out.print("Enter the number of units for the 1st subject: "); units = Integer.parseInt(kbd.nextLine()); totalGrade = totalGrade + grade * units; // OR totalGrade += grade* units; totalUnits = totalUnits + units; System.out.print("Enter the grade of the student for the 2nd subject: "); grade = Integer.parseInt(kbd.nextLine()); System.out.print("Enter the number of units for the 2nd subject: "); units = Integer.parseInt(kbd.nextLine()); totalGrade = totalGrade + grade * units; // totalGrade += grade* units; totalUnits = totalUnits + units; // continue } // end of main } // end of class

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

IT 112L Programming Fundamentals I Laboratory Additional Prelim Exercises I. Simple Application Suppose the expenses of a fulltime student for one semester fall under only three items: Tuition Fees, Basic Board and Lodging(e.g. Food and Accommodation), and Living Allowance. Suppose further that the amount to be spent by a fulltime student for one summer term is 35% of the student's total expense for one semester. Write a program that will let the computer asks the user to enter the estimated amount needed by a student for Tuition Fees for one semester, estimated amount needed by a fulltime student for Basic Board and Lodging for one month, and the estimated amount needed by a fulltime student for his/her Living Allowance for one month. The computer will then compute and display the following: a. The amount needed by a fulltime student for one semester. It must be noted that one semester corresponds to 5 months. b. The amount needed by a fulltime student for one summer term c. The amount needed by a fulltime student for the whole duration of his/her studies in college assuming that the student needs to enroll for 8 semesters and 3 summer terms. The following is a sample run of the required program ____________________________________________________________________ How much is your estimated tuition fee for one semester? 27200.00 Approximately, how much does your board and lodging for one month cost? 5000.00 How much is your estimated living allowance for one month? 3000.00 ------------------------------------------------------------------- ---------------Estimated Tuition Fee per Semester 27200.00 Estimated Board and Lodging cost per Semester 25000.00 Estimated living Allowance per Semester 15000.00 --------------------------------------------------------------------------------Estimated Amount Needed by a Student for one Semester 67200.00 Estimated Amount Needed by a Student for one Summer term 23520.00 Estimated Amount Needed by a Student to graduate 608160.00 Process completed. Algorithm: 1. Let tuitionFee represent the estimated tuition fee of a fulltime student for one semester 2. Let boardAndLodging represent the estimated cost for one month of basic board and lodging 3. Let livingAllowance represent the estimated living allowance needed by a fulltime student for one month 4. Let semesterExpense represent the estimated amount needed by a fulltime student for one semester 5. Let summerExpense represent the estimated amount needed by a fulltime student for one summer term

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

6. Let totalEstimatedExpense represent the amount needed by a fulltime student in order to finish his/her course for 8 semesters and 3 summer terms. 7. Read the value for tuitionFee 8. Read the value for boardAndLodging 9. Read the value for livingAllowance 10. Compute the value for semesterExpense 11. Compute the value for summerExpense 12. Compute the value for totalEstimatedExpense 13. Display the values **/ II. Simple Application Problem: Suppose a student spends on only four necessities every school week. The four necessities are fare, food, hygiene and gadget maintenance (e.g. load). Develop a program that will compute the possible savings that a student can make from his/her weekly allowance. The program should how the expected savings for: a. Six school days out of a 6-day allowance b. 16 school weeks assuming 1 school week is corresponding to six school days c. Eight semesters assuming that one semester is corresponding to 16 school weeks. When the program is executed, the computer will ask for the 6-day allowance together with the student's expected daily expense on four necessities; transportation, food, hygiene, and gadget. The computer should then compute and display the expected expense for 6 days (1 week) as well as the expected savings for 16 weeks, one semester and for eight semesters. Below is a sample output of the program execution. ------------------------------------------------------------------------------------------How much is your 6-day allowance? 1000.00 How much is your daily budget for transportation? 20.00 How much is your daily budget for food? 100.00 How much is your daily budget for personal hygiene? 10.00 How much is your daily budget for cell phone load? 10.00 Expected Total Expenses for 6 days: Expected Savings for 6 days: Expected Savings for one semester: Expected Savings for eight semesters: 840.00 160.00 2560.00 20480.00

Inputs: Students 6-day allowance, students daily budget for transportation, students daily budget for food, students daily budget for hygiene, students daily budget for load. Processes: Read the students 6-day Allowance (allowance)

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

Read the students daily budget for transportation (tExpense) Read the students daily budget for food (fExpense) Read the students daily budget for hygiene (hExpense) Read the students daily budget for load (lExpense) Compute the expected expense for 6 days (weekExpense) weekExpense = 6*( tExpense + fExpense + hExpense + lExpense) Compute the expected savings for 6 days (weekSavings) weekSavings = allowance - weekExpense Compute the expected savings for 1 semester (semSavings) semSavings =16 * weekSavings Compute the expected savings for 8 semesters (totalSavings) totalSavings = 8*semSavings Display the computed amounts Outputs: Expected expense for 6 days, Expected savings for 6 days, Expected savings for one semester or 16 weeks, Expected savings for 8 semesters.

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

Below are programs that involve the conditional statement (i.e. if statement). Some parts program are not given (i.e. the Boolean Expressions of the if statements). Provide the expressions for each program. After providing the missing expressions in each program, program and be able to trace the output based on your test data. (i.e. Understand the execution.)

of each missing test the flow of

III.

Program for getting the roots of a quadratic equation /** *Write a program for determining the roots of a quadratic equation. A quadratic equation has the form ax^2 + bx + c = 0. The numerical coefficients a, b and c should be entered at run time. The literal coefficient is assumed to be x (i.e. There is no need to read the literal coefficient. *Sample run: -----------------------------------------------------------Enter the coefficient of x squared (a):1 Enter the coefficient of x (b): -4 Enter the constant (c): 4 The roots of (1.0)x^2 + (-4.0)x + (4.0) = 0 are 2.00 and 2.00. ------------------------------------------------------------*Note: Quadratic Formula first root = (-b + Math.sqrt(b*b-4*a*c))/(2*a) second root = (-b - Math.sqrt(b*b - 4*a*c))/(2*a) *Analysis Inputs: Coefficients a, b and c Processes: Read the coefficients Compute the roots Show the roots Outputs: First root and second root * Algorithm 1. Let a represent the coefficient of x squared 2. Let b represent the coefficient of x 3. Let c represent in constant 4. Let root1 represent the first root 5. Let root2 represent the second root 6. Show an introduction of the application/program 7. Read the value of a

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

8. Read the value of b 9. Read the value of c 10. If (b*b - 4*a*c) is greater than or equal to 0 Compute root1: root1 =( -b + Math.sqrt(b*b - 4*a*c))/(2*a) Compute root2: root2 =( -b - Math.sqrt(b*b - 4*a*c))/(2*a) Display the equation and the roots. 11. If (b*b - 4*a*c) is less than 0 Display the equation and say that the roots are imaginary **/ import java.util.Scanner; import java.lang.*; public class Quadratic2{ public static void main(String[] args){ Scanner keyboard = new Scanner(System.in); double a=0, b=0, c=0; double root1=0, root2=0; System.out.println("This program determines the roots of a quadratic equation\n of the form ax^2 +bx +c = 0."); System.out.print("Enter the coefficient of x^2, a= "); a=Double.parseDouble(keyboard.nextLine()); System.out.print("Enter the coefficient of x, b= "); b=Double.parseDouble(keyboard.nextLine()); System.out.print("Enter the constant, c= "); c=Double.parseDouble(keyboard.nextLine()); if ( ___________________ ) { // missing Boolean Expression root1= (-b + Math.sqrt(b*b-4*a*c))/(2*a); root2= (-b - Math.sqrt(b*b-4*a*c))/(2*a); System.out.printf("%c%f%s%f%s%f%s%f%s%f%c%n",'(',a,") + (",b,") + (",c,") = 0 are ", root1, " and ", root2, '.'); } if (_______________________){ // missing Boolean expression System.out.print("The roots of "); System.out.printf("%s%f%s%f%s%f%s","(",a,")x^2 + (",b, ")x + (", c, ") = 0" ); System.out.println(" are imaginary."); // are imaginary"); } System.exit(0); } }

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

IV.

Program for conversion of temperatures /** *Problem: Write a program that will make the computer read a temperature in Degrees Fahrenheit or Degrees Celsius. Then, the computer prints the equivalent temperature in Degrees Celsius or Degrees Fahrenheit. *Analysis Input: Temperature in Fahrenheit or Celsius Processes: Input temperature Convert the temperature entered Display temperatures Output: Temperature in Celsius or Fahrenheit *Algorithm: 1. Declare needed variables 2. Print introductory messages 3. Show choices Menu: a. Convert from Fahrenheit to Celsius b. Convert from Celsius to Fahrenheit c. Quit 4. Read choice 5. If choice is a, Read temperature in Fahrenheit (fahrenheit) Convert the temperature:celsius = 5.0/9*(fahrenheit - 32) Show temperatures 6. If choice is b, Read temperature in Celsius ( celsius) Convert the temperature: fahrenheit = 9.0/5*celsius + 32 show temperatures 7. If choice is c Print parting message 8. If choice is not a, not b and not c

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

Show an error message 9. Exit ****/ import java.util.Scanner; import java.lang.*; public class TemperatureConverterB { public static void main(String[] args){ Scanner kbd = new Scanner(System.in); double celsius; // to hold temperature in degrees celsius double fahrenheit; // to hold temperature in degrees fahrenheit char choice; double convertedValue; System.out.println("This program helps you convert temperature measures."); System.out.println("----------------Menu----------------------"); System.out.println("a: Convert from Farenheit to Celsius"); System.out.println("b: Convert from celsius to Fahrenheit"); System.out.println("c: Quit"); System.out.println("----------------Menu----------------------"); System.out.print("Enter your choice<a/b/c>: "); choice = kbd.nextLine().charAt(0); if (__________________________) { // missing Boolean Expression System.out.print("Enter the temperature in Fahrenheit: "); fahrenheit = Float.parseFloat(kbd.nextLine()); //Compute then display the equivalent temperature in Celsius celsius = 5.0/9.0*(fahrenheit-32); System.out.println(fahrenheit + " degrees Fahrenheit equals " + celsius + " degrees Celsius "); } if ( ________________________) { // missing Boolean Expression System.out.print("Enter the temperature in celsius: "); celsius = Float.parseFloat(kbd.nextLine()); //Compute then display the equivalent temperature in Celsius fahrenheit = 9.0/5.0*celsius+32; System.out.println(celsius + " degrees celsius equals " + fahrenheit + " degrees farenheit."); } if ( _______________________){ // missing Boolean Expression System.out.println("Thank you for using the program."); }

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

if (choice != 'a' && choice != 'b' && choice != 'c') { System.out.println("Your choice is not valid."); System.out.println("Thank you!"); } System.out.println("Thank you."); System.exit(0); } // End of main } // End of class

V.

Program for conversion of temperatures /** * Problem: Write a program that will make the computer read a temperature in Degrees Fahrenheit or Degrees Celsius. Then, the computer prints the equivalent temperature in Degrees Celsius or Degrees Fahrenheit. *Analysis Input: Temperature in Fahrenheit or Celsius Processes: Input temperature convert the temperature entered Display temperatures Output: Temperature in Celsius or Fahrenheit *Algorithm: 1. Declare needed variables 2. Print introductory messages 3. Show choices Menu: 1. Convert from Fahrenheit to Celsius 2. Convert from Celsius to Fahrenheit 3. Quit 4. Read choice 5. If choice is 1, Read temperature in Fahrenheit (fahrenheit) Convert the temperature:celsius = 5.0/9*(fahrenheit - 32)

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

Show temperatures 6. If choice is 2, Read temperature in Celsius ( celsius) Convert the temperature: fahrenheit = 9.0/5*celsius + 32 show temperatures 7. If choice is 3 Print parting message 8. If choice is not 1, not 2 and not 3 Show an error message 9. Exit ***/ import java.util.Scanner; import java.lang.*; public class TemperatureConverterC { public static void main(String[] args){ Scanner kbd = new Scanner(System.in); double celsius; // to hold temperature in degrees celsius double fahrenheit; // to hold temperature in degrees fahrenheit int choice; double convertedValue; System.out.println("This program helps you convert temperature measures."); System.out.println("----------------Menu----------------------"); System.out.println("1: Convert from Farenheit to Celsius"); System.out.println("2: Convert from celsius to Fahrenheit"); System.out.println("3: Quit"); System.out.println("----------------Menu----------------------"); System.out.print("Enter your choice<1/2/3>: "); choice = Integer.parseInt(kbd.nextLine()); if (_______________________) { // missing Boolean Expression System.out.print("Enter the temperature in Fahrenheit: "); fahrenheit = Float.parseFloat(kbd.nextLine()); //Compute then display the equivalent temperature in Celsius celsius = 5.0/9.0*(fahrenheit-32); System.out.println(fahrenheit + " degrees Fahrenheit equals " + celsius + " degrees Celsius "); } if ( ________________________) { // missing Boolean Expression

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

System.out.print("Enter the temperature in celsius: "); celsius = Float.parseFloat(kbd.nextLine()); //Compute then display the equivalent temperature in Celsius fahrenheit = 9.0/5.0*celsius+32; System.out.println(celsius + " degrees celsius equals " + fahrenheit + " degrees farenheit."); } if ( ______________________){ // missing Boolean Expression System.out.println("Thank you for using the program."); } if (choice < 1 || choice > 3) { System.out.println("Your choice is not valid."); System.out.println("Thank you!"); } System.out.println("Thank you."); System.exit(0); } // end of main } // end of class

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

Points for further readings: Decision control structures are Java statements that allow us to select and execute specific blocks of code while skipping other sections. o Selection Constructs if, if-else, switch case o Loop Constructs while, do while, for The if-statement specifies that a statement (or block of code) will be executed if and only if a certain boolean statement is true. Syntax: if( boolean_expression ) statement; or if( boolean_expression ){ statement1; statement2; ... } The boolean_expression part of a statement should evaluate to a boolean value. That means that the execution of the condition should either result to the value true or false. A relational operator compares two values and determines if a relationship between the values holds or not (true or false). For example, n1 != n2 returns true if n1 and n2 are unequal n1 == n2 returns true if n1 is equal to n2 n1 > n2 returns true if n2 is greater than n2

The following are Java Relational Operators Use op1 > op2 op1 >= op2 op1 < op2 op1 <= op2 op1 == op2 op1 != op2 Description Returns true if op1 is greater than op2 Returns true if op1 is greater than or equal to op2 Returns true if op1 is less than op2 Returns true if op1 is less than or equal to op2 Returns true if op1 and op2 are equal Returns true if op1 and op2 are not equal

Operator > >= < <= == !=

Relational operators are usually used in conditional and loop statements. Examples : if (principal >= 5000.00) { interest = principal*rate; }

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

if (principal < 5000 ) { interest = 0.0; } while ( counter <=12) { System.out.println(month: + counter) counter++; } Relational operators often are used with conditional operators to construct more complex decision-making expressions. The Java programming language supports the following six conditional operatorsfive binary and one unary.

Operator &&

Use op1 && op2

Description Returns true if op1 and op2 are both true; conditionally evaluates op2 Returns true if either op1 or op2 is true; conditionally evaluates op2 Returns true if op is false Returns true if op1 and op2 are both boolean and both true; always evaluates op1 and op2; if both operands are numbers, performs bitwise AND operation Returns true if both op1 and op2 are boolean and either op1 or op2 is true; always evaluates op1 and op2; if both operands are numbers, performs bitwise inclusive OR operation Returns true if op1 and op2 are different that is, if one or the other of the operands, but not both, is true

||

op1 || op2

! &

!op op1 & op2

op1 | op2

op1 ^ op2

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

Examples: if (type == r && kWUsed >10 ) { amountDue = 200 + (kWused-10)*rate; } if (type !=r || type != c) { System.out.println(Invalid type!); }

The following illusrtates the meaning (semantics) of the statement if ( boolean_expr ) statement;

Below are examples of Boolean expressions that involve relational and conditional operators. a. ( score <0 || score > 100) where, score is a number variable b. ( choice == y || choice == Y ) where, choice is a char variable c. ( answer != a ) where, answer is char variable d. ( ! isLeapYear ) where, isLeapYear is a boolean variable e. ( c != y && c != n ) where, c is a char variable

A Boolean expression that involves the AND (&&) operator is evaluated based on the following truth table

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

A true true false false

B true false true false

A && B true false false false

A Boolean expression that involves the OR (||) operator is evaluated based on the following truth table A true true B true false A || B true true

false

true

true

false

false

false

A Boolean expression that involves the NOT (!) operator is evaluated based on the following truth table. A true false !A false true

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

The if-else statement is used when we want to execute a certain statement if a condition is true, and a different statement if the condition is false. The if-else statement has the form, if( boolean_expression ) statement; else statement;

The if-else statement can also have the form, if( boolean_expression ){ statement1; statement2; ... } else{ statement1; statement2; ... } The semantics (meaning) of an if-else statement is described by the following figure. if( boolean_expr) statement; else statement;

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

You can have nested if-else blocks. This means that you can have other if-else blocks inside another if-else block. For example, if( boolean_expr1 ) statement1; else if( boolean_exp2 ) statement2; else statement3;

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

Common Errors when using the if-else statement a. The condition inside the if-statement does not evaluate to a boolean value. For example, int number = 0; if( number ){ // WRONG! The variable number does not hold a Boolean value. //some statements here } b. Using = instead of == for comparison. For example, int number = 0; if( number = 0 ){ // WRONG! //some statements here } int number = 0; if( number == 0 ){ // CORRECT! //some statements here } c. Writing elseif instead of else if.

The switch statement has the form, switch( switch_expression ){ case case_selector1: statement1; // statement2; //block 1 ... // break; case case_selector2: statement1; // statement2; //block 2 ... // break;

... default: statement1; statement2; ... break; } // //block n //

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

The switch_expression is an integer, character or String expression and, case_selector1, case_selector2 and so on, are unique integers, characters or String constants that are possible results of the switch_expression When a switch is encountered, Java first evaluates the switch_expression, and jumps to the case whose selector matches the value of the expression. The program executes the statements in order from that point on until a break statement is encountered, skipping then to the first statement after the end of the switch structure. If none of the cases are satisfied, the default block is executed. Take note, however, that the default part is optional. A switch statement can have no default block. Unlike the if statement, the multiple statements are executed in the switch statement without needing the curly braces. When a case in a switch statement has been matched, all the statements associated with that case are executed and the statements associated with the succeeding cases are also sequentially executed. To prevent the program from executing statements in the subsequent cases, a break statement is used.

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

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. 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. Repetition control structures are Java statements that allow the execution of specific blocks of code a number of times. There are three types of repetition control structures, the while, do-while and for loops. The while loop allows the repetitive execution of a statement or block of statements as long as a condition is satisfied. The while statement has the form, while( boolean_expression ){

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

statement1; statement2; ... } The statements inside the while loop are executed as long as the boolean_expression evaluates to true. Example: int i = 4; while ( i > 0 ){ System.out.print(i); i--; } The sample code shown will print 4321 on the screen. Take note that if the line containing the statement i--; is removed, this will result to an infinite loop, or a loop that does not terminate.

When using while loops or any kind of repetition control structures, make sure that you add some statements that will allow your loop to terminate at some point. The do-while loop is similar to the while-loop and that the statements inside a do-while loop are executed several times as long as the condition is satisfied. The main difference between a while and do-while loop is that, the statements inside a do-while loop are executed at least once. The do-while statement has the form, do{ statement1; statement2; ... }while( boolean_expression ); The statements inside the do-while loop are first executed, and then the condition in the boolean_expression part is evaluated. If boolean_expression evaluates to true, the statements inside the do-while loop are executed again. int x = 0; do { System.out.print(x); x++; }while (x<10); The above example will output 0123456789 on the screen.

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

Just like in a while loop, make sure that your do-while loop will terminate at some point. The common programming mistake when using the do-while loop is forgetting to write the semicolon after the while expression. do{ ... }while(boolean_expression); //semicolon is required here The for loop, like the previous loops, allows execution of the same code a number of times. The for loop has the form, for (InitializationExpression; LoopCondition; StepExpression){ statement1; statement2; ... } where, InitializationExpression -initializes the loop control variable. LoopCondition - compares the loop control variable to some limit value. StepExpression - updates the loop control variable

In the following example, the statement i=0, initializes first the control variable i. After that, the condition expression i<10 is evaluated. If this evaluates to true, then the statement inside the for loop is executed. Next, the expression i++ is executed, and then the condition expression is again evaluated. This goes on and on, until the condition expression (i<10) evaluates to false. int i; for( i = 0; i < 10; i++ ){ System.out.print(i); }

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

IT 112L Programming Fundamentals I Laboratory Midterm Activity Number 1 /** Problem: Given a students Total Quiz Score, the students Examination Score, the Perfect Quiz score, and the Perfect Examination Score, the Prelim Grade is computed by using the following formulas: Quiz Grade = ( Total Quiz Score )/ (Perfect Quiz Score) * 50 + 50. Exam Grade = (Examination Score) / (Perfect Examination Score) * 50 + 50. Prelim Grade = (Quiz Grade + Exam Grade)/2 and if the computed Prelim Grade is more than 99, the Prelim Grade is set to 99 but if the computed Prelim Grade is less than 65, the Prelim Grade is set to 65. Develop a computer program for the computation of a Prelim Grade based on the above formulas. The program will allow the computer to accept a students Total Quiz Score, a students Examination Score, the Perfect Total Quiz Score and the Perfect Examination Score. The computer will then show the corresponding grade. In addition, the remark PASSED will be given if the grade is at least 75 and the remark FAILED will be given if the grade is less than 75. Sample run1 Enter the Perfect Quiz Score : 100 Enter the Perfect Examination Score: 100 Enter a students quiz score: 100 Enter a students examination score: 100 Grade = 99 Remark: PASSED Sample run 2 Enter the Perfect Quiz Score : 200 Enter the Perfect Examination Score: 10 Enter a students quiz score: 10 Enter a students examination score: 1 Grade = 65 Remark: FAILED Analysis of the Programming Problem Inputs: Total Quiz Score, Examination Score, Perfect Quiz Score, Perfect Exam Score Processes: 1. Read the scores 2. Compute the grade for the quiz 3. Compute the grade for the exam 4. Compute the Prelim Grade 5. Display the grades and a remark Outputs: Prelim Grade, Remark Algorithm for the program. a. Let quizScore be a variable to hold the Total Quiz Score b. Let examScore be a variable to hold the Examination Score c. Let perfectQuizScore be a variable to hold the Perfect Quiz Score d. Let perfectExamScore a variable to hold the Perfect Exam Score e. Let quizGrade be a variable to hold the Quiz Grade.

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

f. g. h. i. j. k. l. m. n. o. p. q. r.

Let examGrade be a variable to hold the Exam Grade Let prelimGrade be a variable to hold the Prelim Grade Read the value of perfectQuizScore Read the value of perfectExamScore Read the value of quizScore Read the score for the examScore quizGrade = quizScore/perfectQuizScore*50 + 50 examGrade = examScore/perfectExamScore*50 +50 prelimGrade = (quizGrade + examGrade)/2 If prelimGrade is greater than 99 then set prelimGrade to 99 If prelimGrade is less than 65 then set prelimGrade to 65 If prelimGrade is greater than or equal to 75 then display the grade together with the remark PASSED. If prelimGrade is less than 75 then display the grade together with the remark FAILED

Required: 1. Complete the following Java program for the programming problem by replacing each blank line by the appropriate keyword, expression or statement. (Filename: <YourName>MidtermActivity1A. Do not save your program in your personal memory device. Upload the source code for your completed program through the upload site shown on the board. ([192.168.92.1]>) 2. Modify your completed program such that the following are enforced. (Filename: <YourName>MidtermActivity1B. a) while statements are used instead of do-while statements b) Aside from being no greater than the perfect quiz score, the quiz score to be entered should not be a negative value. An appropriate message should be displayed in case the user enters a negative quiz score and the user should be allowed to enter a new value. c) Aside from being no greater than the perfect exam score, the exam score to be entered should not be a negative value. An appropriate message should be displayed in case the user enters a negative exam score and the user should be allowed to enter a new value. d) if-else statements should be used where appropriate. Do not save your program in your personal memory device. Upload the source code for your completed program through the upload site shown on the board. ([192.168.92.1]) Delete your program from the hard drive of your workstation after uploading. **/

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

import java.lang.*; import java.util.Scanner; public class YourNameMidtermActivity1A { public static void main(String[] args) { Scanner reader = new Scanner(System.in); int quizScore; // declare an int variable to hold total quiz score int examScore; // declare an int variable to hold exam score int perfectQuizScore; // declare an int variable to hold perfect total quiz score int perfectExamScore; // declare an int variable to hold perfect exam score ________________ quizGrade; // 1. declare a double variable to hold quiz grade. ________________ examGrade; //2. declare a double variable to hold examination grade ________________ prelimGrade; //3. declare a double variable to hold the prelim grade /**Accept the perfect total quiz score. The perfect score must be greater than 0. The do while construct enables the computer to let the user re-enter a perfect score in case the value entered is invalid. **/ do { System.out.print("Enter the Perfect Total Quiz Score : "); perfectQuizScore = ___________________________________________________; //4 if (perfectQuizScore <= 0){ System.out.println("Invalid value! Value must be greater than 0."); } } while (perfectQuizScore <= 0); /** Accept the perfect exam score. The perfect score must be greater than 0. The do while construct enables the computer to let the user re-enter a perfect score in case the value entered is invalid. **/ do { System.out.print("Enter the Perfect Examination Score : "); perfectExamScore = _____________________________________________________; //5 if (perfectExamScore <= 0){ System.out.println("Invalid value! Value must be greater than 0."); } } while (perfectExamScore <= 0); /** Accept the total quiz score. The total quiz score must not be greater than the perfect quiz score. The do while construct enables the computer to let the user re-enter a score in case the value entered is invalid.**/ do { System.out.print("Enter a student's total quiz score : "); quizScore = ___________________________________________________________; //6 if (quizScore > perfectQuizScore){ System.out.println("Invalid value! Score must not be greater than perfect score."); } } while (quizScore > perfectQuizScore); /** Accept the exam score. The exam score must not be greater than the perfect exam score. The do while construct enables the computer to let the user re-enter a score in case the value entered is invalid.**/ do { System.out.print("Enter a student's examination score : "); examScore = __________________________________________________________; //7 if (examScore > perfectExamScore){ System.out.println("Invalid value! Score must not be greater than perfect score."); } } while (examScore > perfectExamScore); // Compute the quiz grade quizGrade = ________________________________________________________________; //8

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

// Compute the exam grade examGrade = ________________________________________________________________;//9 // Compute the subject grade prelimGrade = _______________________________________________________________;//10 // Check if prelim grade is greater than 99 then reset it to 99 if (prelimGrade>99) { prelimGrade = _________________________________________________ //11 } //Check if prelim grade is less than 65 then reset it to 65 if (prelimGrade < 65) { ________________________________________________________________ //12 } // Check if prelim grade is passing then display the grade together with a remark if (__________________________________________){ //13 System.out.print(______________________________________________); //14 System.out.println(" Remark : PASSED"); } // Check if prelim grade is failing then display the grade together with a remark _____________________________________________________________________//15 ______________________________________________________________________ _____________________________________________________________________ } System.exit(0); } // end of the main method } // end of class

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

IT 112L Programming Fundamentals I Laboratory Midterm Activity Number 2 /*** Grading Program Problem The numeric prelim grade of a student for a subject is computed by the expression ((student's grade for the quizzes) + (student's grade for the examination))/2 The grade for the quizzes is computed by the expression (student's total quiz scores)/(perfect total quiz score) * 50 + 50. The grade for the examination is computed by the expression (student's examination score)/(perfect examination score) * 50 +50. A corresponding letter grade is given to the student based on the following rules. If NUMERIC GRADE is then LETTER GRADE is =================== ========================= >=50 but <75 D >=75 but <80 C >=80 but <90 B >=90 but <=100 A Activities: 1.Based on the following algorithm for the above programming problem, provide the statements or expressions that should replace the blank lines in the incomplete program given below. The statements or expressions should be based on the given parts of the program. (You should not add any statement or expression aside from those that should replace the blank lines.) One blank line corresponds to one statement or one expression. (Filename: <YourName>MidtermActivity2A) Do not save your program in your personal memory device. Upload the source code for your completed program ( through <192.168.92.1>) Delete your program from the hard drive of your workstation after uploading

2. Modify the program so that if-else statements are used where appropriate. (Filename: <YourName>MidtermActivity2B) Do not save your program in your personal memory device. Upload the source code for your completed program ( through <192.168.92.1>) Algorithm: 1. Declare and initialize the variable perfectTotalQuizScore that represents the perfect total quiz score. 2. Declare and initialize the variable totalQuizScore that represents the total quiz score of a student. 3. Declare and initialize the variable perfectExamScore that represents the perfect score for the examination. 4. Declare and initialize the variable examScore that represents the examination score of a student. 5. Declare and initialize the variable quizGrade that represents the grade of a student for his/her quiz scores. 6. Declare and initialize the variable examGrade that represents the grade of a student for his/her examination score. 7. Declare and initialize the variable numericGrade that represents the numeric prelim grade of a student.

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

8. Declare and initialize the variable letterGrade that represents the letter prelim grade of a student. 9. Declare and initialize the variable studentName that represents the name of a student. 10. Display a message that explains that the running program is a utility for computing the prelim grade of a student. 11. Read the name of a student 12. Read the perfect total quiz score from the keyboard. The perfect total quiz score read must be validated such that it cannot be less than or equal to zero. If the user enters an invalid perfect total quiz score, an appropriate error message should be displayed on the screen and the program execution should end. 13. Read the total quiz score of the student. The total quiz score read must be validated such that it should not be greater than the perfect total quiz score or the it must not be less than zero. If the user enters an invalid total quiz score, an appropriate error message should be displayed on the screen and the program execution should end. 14.Read the perfect score for the examination from the keyboard. The perfect score read must be validated such that it cannot be less than or equal to zero. If the user enters an invalid perfect score, an appropriate error message should be displayed on the screen and the program execution should end. 15. Read the examination score of the student. The score read must be validated such that the score should not be greater than the perfect score or the score must not be less than zero. If the user enters an invalid perfect score, an appropriate error message should be displayed on the screen and the program execution should end. 16.Compute grade of the student for the quizzes through the formula: quizGrade = (totalQuizScore/perfectQuizScore*50 +50 17. Compute grade of the student for the examination through the formula: examGrade = examScore/perfectExamScore*50 +50 18. Compute numerical prelim grade of the student through the formula: numericGrade = (quizGrade + examGrade)/2 19. Determine the letter grade of the student as follows if (numericGrade >=50 && numericGrade <75), let letterGrade= 'D'. if (numericGrade >=75 && numericGrade <80), let letterGrade= 'C'. if (numericGrade >=80 && numericGrade <90), let letterGrade= 'B'. if (numericGrade >=90 && numericGrade <=100), let letterGrade= 'A'. 20. Display a summary of the result of the computation ***/ // Incomplete Program
import java.util.Scanner; public class YourNameMidtermActivity2A{ public static void main(String[] args){ Scanner kbd = new Scanner(System.in); int perfectTotalQuizScore=0, totalQuizScore=0, examScore=0, perfectExamScore=0; double quizGrade=0, examGrade=0, numericGrade=0; char letterGrade='I'; String studentName = ""; System.out.println("This program helps you compute the prelim grade of a student."); System.out.println(); System.out.print("Enter the name of the student: "); __________________________________________; // 1.

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

System.out.print("Enter the perfect total quiz score: "); ___________________________________________;//2 if (perfectTotalQuizScore <=0){ System.out.println("Invalid perfect score! The perfect score should be greater than zero"); System.out.println("Sorry! The program needs to close. Run the program again and enter correct values."); System.exit(0); } System.out.print("Enter the total quiz score of " + studentName + " :"); totalQuizScore = Integer.parseInt(kbd.nextLine()); if (totalQuizScore < 0 || totalQuizScore > perfectTotalQuizScore){ System.out.println("Invalid score. The score should not exceed the perfect score "+ perfectTotalQuizScore + " and it should not be less than 0." ); System.out.println("Sorry! The program needs to close. Run the program again and enter correct values."); System.exit(0); } System.out.print("Enter the perfect examination score: "); ________________________________________________; // 3 if ( ______________________________________________________ ){ // 4 System.out.println("Invalid perfect score! The perfect score should be greater than zero"); System.out.println("Sorry! The program needs to close. Run the program again and enter correct values."); System.exit(0); } System.out.print("Enter the examination score of " + studentName + " :"); ___________________________________________________; // 5 if ( __________________________________________________________ ){ // 6 System.out.println("Invalid score. The exam score should not exceed the perfect score "+ perfectExamScore + " and it should not be less than 0." ); System.out.println("Sorry! The program needs to close. Run the program again and enter correct values."); System.exit(0); } quizGrade = (double) totalQuizScore / perfectTotalQuizScore * 50 + 50; examGrade = (double) examScore / perfectExamScore * 50 + 50; ___________________________________________________________; // 7 if (numericGrade >= 50 && numericGrade < 75) { letterGrade = 'D'; } if (_______________________________________________________ ) { // 8 letterGrade = 'C'; } if (_______________________________________________________ ) { // 9 letterGrade = 'B'; } if (numericGrade >= 90 && numericGrade <= 100) { ______________________________________________________; // 10 } System.out.println(); System.out.printf("%-30s%20s%n", "Name of Student", studentName); System.out.printf("%-30s%20d%n","Total Quiz Score = ", totalQuizScore); System.out.printf("%-30s%20d%n","Perfect Total Quiz Score = ", perfectTotalQuizScore); System.out.printf("%-30s%20.0f%n","Grade for the Quizzes = ", quizGrade);

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

System.out.printf("%-30s%20d%n","Examination Score = ", examScore); System.out.printf("%-30s%20d%n","Perfect Examination Score = ", perfectExamScore); System.out.printf("%-30s%20.0f%n","Grade for the Exam = ", examGrade); System.out.println(); System.out.printf("%-30s%20.0f%n","Numeric Grade = ", numericGrade); System.out.printf("%-30s%20c%n","Letter Grade = ", letterGrade); System.exit(0); } // end of main method } // end of class

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

IT 112L Programming Fundamentals I Laboratory Midterm Activity Number 3 Problem: Write a program for computing the amount of money in a bank account at the end of each quarter for a period of one year. A quarter is equivalent to 3 months. Assume that the account is created at the beginning of a year(i.e. January 1). The year will be entered at run time through the keyboard. The account has an initial principal that is entered at run time through the keyboard. No deposit or withdrawal is made within the one-year period. The interest is compounded quarterly which means that the interest earned for the first quarter will form part of the principal for the second quarter, the interest earned for the second quarter will form part of the principal for the third quarter and so on. The annual interest rate is 5%. The interest rate for a quarter is computed by dividing the annual interest rate by 4 since there are four quarters in a year. The computational procedure (see algorithm) and the output of the program (see sample run) are shown below. The output includes a table showing the year, quarter number, interest earned and the new principal. The new principal is the amount at the end of the quarter. ALGORITHM: Declare the necessary variables. Let annual interest rate be set to 0.05. ( Note 5.00% = 0.05). Accept the year. Accept the initial principal. Display principal formatted with two digits after decimal point. Display annual interest rate in percent form. Display the column headings for the table. Compute the interest rate for a quarter. Let quarter be 1. Compute the interest earned for the first quarter Compute the new amount (amount at the end of the first quarter) Display the year, quarter, interest earned and balance at the end of 1st quarter Let quarter be 2 Compute the interest earned for the second quarter Compute the new amount (amount at the end of the second quarter) Display the year, quarter, interest earned and balance at the end of 2nd quarter Let quarter be 3. Compute the interest earned for the third quarter Compute the new amount ( amount at the end of the third quarter) Display the year, quarter, interest earned and balance at the end of 3rd quarter Let quarter be 4. Compute the interest earned for the fourth quarter Compute the new amount (amount at the end of the fourth quarter) Display the year, quarter, interest earned and balance at the end of 4th quarter SAMPLE RUN: Enter the year: 2005 Enter the initial principal: 10000.00 Principal: = 10000.00

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

Annual Interest Rate: 5.00% Year Quarter 2005 1 2005 2 2005 3 2005 4

Interest Earned 125.00 126.56 128.14 129.75

Amount at end of quarter 10125.00 10251.56 10379.70 10509.45

Required: 1. Complete the program by replacing each blank line by the appropriate expression/statement. (Filename: <YourName>MidtermActivity3A) 2. Improve the program by introducing the for statement where appropriate. ( for quarter= 1 to 4) (filename:<YourName>MidtermActivity3B)

Incomplete Program(The Scanner class is used for data entry) import java.io.*; import java.util.*; public class YourNameMidtermActivity3 { public static void main(String[] args){ Scanner keyboard = new Scanner(System.in); float annualRate; float quarterlyRate; double principal; double interest; double finalAmount; byte quarter; int year; annualRate = 0.05F; // set annual interest to 5% System.out.print("Enter the year: "); year = __________________________; // item 1. System.out.print("Enter the initial principal: "); principal = ____________________________; //item 2 System.out.printf("%s%.2f%n", "Principal = ", ________________); // item 3 System.out.printf("%s%.2f%c%n", "Interest Rate = ", annualRate*100, '%'); System.out.printf("%6s%8s%16s%30s%n", "Year", "Quarter", "Interest Earned", "Amount at end of quarter"); quarterlyRate = _____________________; // item 4 quarter = 1; interest = __________________________; // item 5 finalAmount = principal + interest; System.out.printf("%6s%8d%16.2f%30.2f%n", year, quarter, interest, finalAmount); principal = finalAmount; quarter = _____________; // item 6 _____________________; // item 7 finalAmount = principal + interest;

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

System.out.printf("%6s%8d%16.2f%30.2f%n", year, quarter, interest, finalAmount); principal = finalAmount; ____________________; // item 8 ______________________; // item 9 finalAmount = ___________________________; // item 10 System.out.printf("%6s%8d%16.2f%30.2f%n", year, quarter, interest, finalAmount); ______________________________; // item 11 ______________________________; // item 12 _______________________________; // item 13 _______________________________; // item 14 System.out.printf("%6s%8d%16.2f%30.2f%n", year, quarter, interest, finalAmount); System.exit(0); } // end of the main method } // end of the class

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

IT 112L Programming Fundamentals I Laboratory Midterm Activity Number 4 Test the program given below with different possible input values. Note that the program allows the user to enter a invalid values( 0 or negative number for the quantity, 0 or negative number for the unit price, etc.) In addition the program allows the user to enter a Cash Tendered Amount that is lesser that the amount to be paid. Required: Write an improved version of the program that will provide validation processes for the input values. The following should be imposed: (Filename: YourNameMidtermActivity4) 9 The quantity cannot be a negative number. 9 The unit price must be greater than zero 9 The discount rate cannot be negative and it cannot be more than 100 percent. 9 The amount tendered cannot be lower than the amount to be paid. If an input value is invalid, the user should be given an appropriate error message and a directive to enter another value. The user may repeatedly supply an invalid value. The processing should continue only if the user enters a valid value. import java.util.Scanner; public class YourNameMidtermActivity4{ public static void main(String[] args){ Scanner kbd = new Scanner(System.in); String pName=""; double uPrice, totalCost, discount, discountedCost, amountTendered, change; int qty, dRate; System.out.print("Product: "); pName = kbd.nextLine(); System.out.print("Quantity: "); qty = Integer.parseInt(kbd.nextLine()); System.out.print("Unit Price: "); uPrice = Double.parseDouble(kbd.nextLine()); System.out.print("Discount: "); dRate = Integer.parseInt(kbd.nextLine()); totalCost = uPrice * qty; discount = totalCost*(dRate/100.0); discountedCost = totalCost - discount; System.out.print("Cash Tendered: "); amountTendered = Double.parseDouble(kbd.nextLine()); change = amountTendered - discountedCost; System.out.printf("%-25s%12s%n","----------------------","--------------"); System.out.printf("%-25s%12.2f%n","Total Purchase Amount: ", totalCost); System.out.printf("%-25s%12.2f%n","Total Discount: ", discount); System.out.printf("%-25s%12.2f%n","Amount to be Paid: ", discountedCost); System.out.printf("%-25s%12.2f%n","change: ", change); System.exit(0); }}

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

IT 112L Programming Fundamentals I Laboratory Midterm Activity Number 5 Test the program given below with different possible input values. Note that the program requires the user to enter 10 pairs of grades and number of units. Note also that the program allows the user to enter invalid values. Note further that the computation process involved is repetitive and that the computation process can be handled by a loop construct. Required: Write another version of the program so that the following specifications are satisfied: The number of pairs of grades and units is an input value at run time. Hence, the program may be used to compute the average of 5 grades, 8 grades, 10 grades, etc. There are validation processes for the input values. Grades must be integers from 65 to 99. The number of units must be at least 1 but not more than 12. If an input value is invalid, the user should be given a directive to enter another value and that processing will continue after the user enters a valid value. The repetitive computation process is handled using an iteration construct. (while, do-while or for construct) The computer will display a running average after every pair of grades and units is entered. The running average is the average of the grades entered so far.

import java.lang.*; import java.util.Scanner; public class YourNameMidtermActivity5 { public static void main(String[] args){ Scanner kbd = new Scanner(System.in); int counter = 1; int grade = 0; int units = 0; int totalGrade = 0; int totalUnits = 0; double average = 0.0; System.out.print("Enter the grade of the student for the subject " + counter + " :"); grade = Integer.parseInt(kbd.nextLine()); System.out.print("Enter the number of units for the subject " + counter + " :" ); units = Integer.parseInt(kbd.nextLine()); totalGrade += grade*units; totalUnits += units;

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

counter += 1; System.out.print("Enter the grade of the student for the subject " + counter + " :"); grade = Integer.parseInt(kbd.nextLine()); System.out.print("Enter the number of units for the subject " + counter + " :" ); units = Integer.parseInt(kbd.nextLine()); totalGrade += grade*units; totalUnits += units; counter += 1; System.out.print("Enter the grade of the student for the subject " + counter + " :"); grade = Integer.parseInt(kbd.nextLine()); System.out.print("Enter the number of units for the subject " + counter + " :" ); units = Integer.parseInt(kbd.nextLine()); totalGrade += grade*units; totalUnits += units; counter += 1; System.out.print("Enter the grade of the student for the subject " + counter + " :"); grade = Integer.parseInt(kbd.nextLine()); System.out.print("Enter the number of units for the subject " + counter + " :" ); units = Integer.parseInt(kbd.nextLine()); totalGrade += grade*units; totalUnits += units; counter += 1; System.out.print("Enter the grade of the student for the subject " + counter + " :"); grade = Integer.parseInt(kbd.nextLine()); System.out.print("Enter the number of units for the subject " + counter + " :" ); units = Integer.parseInt(kbd.nextLine()); totalGrade += grade*units; totalUnits += units; counter += 1; System.out.print("Enter the grade of the student for the subject " + counter + " :"); grade = Integer.parseInt(kbd.nextLine()); System.out.print("Enter the number of units for the subject " + counter + " :" ); units = Integer.parseInt(kbd.nextLine()); totalGrade += grade*units; totalUnits += units; counter += 1; System.out.print("Enter the grade of the student for the subject " + counter + " :"); grade = Integer.parseInt(kbd.nextLine()); System.out.print("Enter the number of units for the subject " + counter + " :" ); units = Integer.parseInt(kbd.nextLine());

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

totalGrade += grade*units; totalUnits += units; counter += 1; System.out.print("Enter the grade of the student for the subject " + counter + " :"); grade = Integer.parseInt(kbd.nextLine()); System.out.print("Enter the number of units for the subject " + counter + " :" ); units = Integer.parseInt(kbd.nextLine()); totalGrade += grade*units; totalUnits += units; counter += 1; System.out.print("Enter the grade of the student for the subject " + counter + " :"); grade = Integer.parseInt(kbd.nextLine()); System.out.print("Enter the number of units for the subject " + counter + " :" ); units = Integer.parseInt(kbd.nextLine()); totalGrade += grade*units; totalUnits += units; counter += 1; System.out.print("Enter the grade of the student for the subject " + counter + " :"); grade = Integer.parseInt(kbd.nextLine()); System.out.print("Enter the number of units for the subject " + counter + " :" ); units = Integer.parseInt(kbd.nextLine()); totalGrade += grade*units; totalUnits += units; average = (double) totalGrade / totalUnits; System.out.printf("%s%.2f%n", "Average Grade = ", average); System.exit(0); } }

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

IT 112L Programming Fundamentals I Laboratory Midterm Activity Number 6 Activities 1. Encode, save, compile, execute and understand the program given below. 2. Modify the program so that the following specifications are satisfied (Filename: YourNameMidtermActivity6) a. Only valid values should allow the computer to continue the process b. The tax due should be determined based on the actual tax computation procedure for the Philippines. (Please do the necessary data gathering. Search for BIR information. Borrow income tax forms. ) c. Appropriate comments should be included in the source code d. Helpful error messages should be shown whenever and wherever appropriate. The Problem Write a program for the computation of the tax due corresponding to a given taxable income. The tax due is determined based on the following table: Taxable Income Tax Due <=25,000.00 4,000.00 >25,000.00 but <= 125,000.00 4,000.00 + 8%(taxable income - 25,000.00) >125,000.00 but <= 525,000.00 12,000.00+10%(taxable income - 125,000.00) >525,000.00 52,000.00+12%(taxable income - 525,000.00) The Program public class Taxation { public static void main(String[] args) { double taxableIncome; double taxDue=0.0; byte bracket=0; System.out.println("Income Tax Computation"); System.out.print("Enter the taxable income: "); taxableIncome = Keyboard.readDouble(); if (taxableIncome <= 25000.00) bracket = 1; if (taxableIncome > 25000.00 && taxableIncome <= 125000.00) bracket = 2; if (taxableIncome > 125000.00 && taxableIncome <= 525000.00) bracket = 3; if (taxableIncome > 525000.00) bracket = 4; switch (bracket){ case 1: taxDue = 4000.00; break; case 2: taxDue = 4000.00 + (taxableIncome-25000.00)*0.08; break;

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

case 3: taxDue = 12000.00 + (taxableIncome-125000.00)*0.10; break; case 4: taxDue = 62000.00 + (taxableIncome-525000.00)*0.12; break; default: taxDue = 0.00; } // end of switch-case System.out.printf("%s %.2f%n", "Tax Due = ", taxDue); System.exit(0); } // end of main method } // end of Taxation class

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

IT 112L Programming Fundamentals I Laboratory Midterm Activity Number 7


(Simplified Water Bill Computation) The bill for a water service subscriber is prepared as follows: 1. Read the name of the water consumer 2. Read the previous water meter reading in cubic meters (reading last month) from the consumers meter. The meter reading cannot be less than zero. 3. Read the present water meter reading in cubic meters (reading this month) from the consumers meter. The present water meter reading cannot be less than the previous water meter reading. 4. Compute the volume of water consumed (consumption) by subtracting the previous reading from the present reading. 5. Read the classification of the consumer( c for commercial or r for residential ) 6. Compute the amount due from the consumer is computed based on the following For residential consumers If Cubic Meters Consumed is ========================== Less than or equal to 12 More than 12

then Amount Due (pesos) ==================== 180.00 180.00 + (cubicMetersConsumed 12)*30.00

For commercial consumers If Cubic Meters Consumed is ========================== Less than or equal to 30 More than 30

then Amount Due (pesos) ==================== 600.00 600.00 + (cubicMetersConsumed 30)*50.00

7. Print a bill statement. The bill statement should show the name of the subscriber, the readings, the consumption and the amount due. Required: Complete the following program for the Water Bill problem described above. The program should provide validation of data entries so that the billing process will be constrained to dealing with valid values. import java.util.Scanner; public class <YourName>WaterBill{ public static void main(String[] args){ int presentReading=0, previousReading=0; Scanner kbd = new Scanner(System.in); String consumer=""; // to hold name of consumer char cType = 'x'; // to hold type of consumer int nCMUsed; // to hold number of cubic meters of water used int minCMResidential=12; // to hold cut-off for minimum Bill for residential consumers double minBillResidential=180.00; // minimum bill for <= 12 Cubic Meters used float rateResidential =30.00F; //cost of 1 Cubic Meter above the min. consumption int minCMCommercial=30; // to hold cut-off for minimum Bill for commercial consumers double minBillCommercial=600.00; // minimum bill for <= 20Cubic Meters used float rateCommercial =50.00F; //cost of 1 Cubic Meter above the min. consumption for commercial consumers

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

double amountDue=0.0; // to hold the amount due System.out.print("Enter the consumer's name: "); consumer = kbd.nextLine(); do { System.out.print("Enter the meter reading last month: "); previousReading = Integer.parseInt(kbd.nextLine()); if (previousReading < 0){ System.out.println("The meter reading cannot me negative."); } } while (previousReading < 0); // Insert statements here.. } // end of class

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

IT 112L Programming Fundamentals I Laboratory Midterm Activity Number 8 Test the program given below with different possible input values. Note that the program allows the computer to determine and show the roots of a quadratic equation after the computer is given the numerical coefficients of the quadratic equation. Note further that if the roots of the quadratic equation are imaginary, the program gives a String representation of the imaginary roots. The given program is written such that aside from the main method, other methods are included. However, you may not mind the other methods at this point. Focus on seeing and understanding sample runs of the program. Required: Write a program that has only the main method that will have similar result/output as the given program. (Filename: <YourName>MidtermActivity8)
import java.util.Scanner; public class YourNameMidtermActivity7{ public static void main(String[] args){ Scanner kbd = new Scanner(System.in); double a,b,c,root1,root2; printHeading(); // Invoke printHeading method System.out.print("Enter a: "); a = Double.parseDouble(kbd.nextLine()); System.out.print("Enter b: "); b = Double.parseDouble(kbd.nextLine()); System.out.print("Enter c: "); c = Double.parseDouble(kbd.nextLine()); if (b*b-4*a*c>=0) determineAndShowTheRealRoots(a,b,c); else determineAndShowTheImaginaryRoots(a,b,c); System.exit(0); } public static void printHeading(){ System.out.println("This program helps you solve for the roots of a Quadratic Equation."); System.out.println("You should enter the coefficients of the quadratic equation"); return; } public static double computeFirstRoot(double a, double b, double c){ double root=0.0; // local variable with initial value root = (-b + Math.sqrt(b*b-4*a*c))/(2*a); return root; } public static double computeSecondRoot(double a, double b, double c){ double root=0.0; // local variable with initial value root = (-b - Math.sqrt(b*b-4*a*c))/(2*a);

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

return root; } public static void showRealRoots(double r1, double r2){ System.out.println("The roots are: " + r1 + " and " + r2 + "."); return; } public static String representFirstImaginaryRoot(double a, double b, double c){ String root=""; root += -b/(2*a)+" + (square root of ("+(-1)*(b*b-4*a*c)+")* i)/"+(2*a); return root; } public static String representSecondImaginaryRoot(double a, double b, double c){ String root=""; root += -b/(2*a)+" - (square root of ("+(-1)*(b*b-4*a*c)+")*i)/"+(2*a); return root; } public static void showImaginaryRoots(String r1, String r2){ System.out.println("The imaginary roots are: " + r1 + " and " + r2 + "."); return; } public static void determineAndShowTheRealRoots(double a, double b, double c){ double root1 = computeFirstRoot(a,b,c); // Invoke computeFirstRoot method double root2 = computeSecondRoot(a,b,c); // Invoke computeSecondRoot method showRealRoots(root1, root2); // Invoke showRoots method return; } public static void determineAndShowTheImaginaryRoots(double a, double b, double c){ String root1 = representFirstImaginaryRoot(a,b,c); // Invoke representFirstImaginaryRoot method String root2 = representSecondImaginaryRoot(a,b,c); // Invoke representSecondImaginaryRoot method showImaginaryRoots(root1, root2); // Invoke showImaginaryRoots method return; } } // end of class

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

IT 112L Additional Midterm Programming Exercises 1. Create a program that generates a typical multiplication table. Develop another version of the following program public class MTable { public static void main(String[] args){ for (int r=1; r<=10; r++){ for (int c=1; c<=10; c++){ System.out.printf("%10d", r*c); } System.out.println(); } System.exit(0); } } 2. Study the following program. (Check how the Random class is used.) /* This program allows the user to guess a randomly generated integer between 1 and 100 (inclusive). The user is given 3 chances to guess the number. For every guess that is not correct, the program tells the user to try something higher or lower, whichever is appropriate. */ import java.util.*; public class SimpleGame { public static void main(String[] args) { Scanner scan = new Scanner(System.in); Random rndNoGen = new Random(); //The Random class is in java.util package int secretNo = rndNoGen.nextInt(100) + 1; // generate a random number System.out.println("I have an integer from 1 to 100."); System.out.println("You have 3 chances to guess it."); int guessNo = 0; int guess; boolean gotIt = false; do { System.out.print("\nGuess #" + (guessNo+1) + ": "); guess = Integer.parseInt(scan.nextLine()); if (guess == secretNo) { gotIt = true; break; // terminate the loop immediately } else { if (guess > secretNo) System.out.println("Try something lower.");

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

else System.out.println("Try something higher."); guessNo++; } } while (guessNo < 3); if (gotIt) { System.out.println("\nCongratulations!!!"); System.out.println("Got it in " + guessNo + " trial(s)!"); } else { System.out.println("\nSorry. No more guesses left."); System.out.println("The number is " + secretNo + "."); System.out.println("Better luck next time."); } System.out.println("\nThanks for playing!!!"); System.out.println("Have a nice day :)!"); }// end of main method 3. Study the following program. (Check how the JOptionPane class is used)
import javax.swing.JOptionPane; import java.util.Scanner; public class ModularizedQuadraticSolverG2{ public static void main(String[] args){ Scanner kbd = new Scanner(System.in); double a,b,c,root1,root2; String input=""; showIntroduction(); // Invoke showIntroduction method method input = JOptionPane.showInputDialog("Please enter the coefficient of x^2, (a in ax^2+bx+c=0): "); a = Double.parseDouble(input); input = JOptionPane.showInputDialog("Please enter the coefficient of x, (b in ax^2+bx+c=0): "); b = Double.parseDouble(input); input = JOptionPane.showInputDialog("Please enter the constant, (c in ax^2+bx+c=0): "); c = Double.parseDouble(input); if (b*b-4*a*c>=0) determineAndShowTheRealRoots(a,b,c); // ITEM 1 else determineAndShowTheImaginaryRoots(a,b,c); // ITEM 2 System.exit(0); } public static void showIntroduction(){ JOptionPane.showMessageDialog(null, "This program helps you solve for the roots of a quadratic equation.\nThe quadratic equation should be written in the form ax^2 + bx+ c = 0 \nYou will be asked to enter the coefficients of the quadratic equation"); return; } public static double computeFirstRoot(double a, double b, double c){ double root=0.0; // local variable with initial value root = (-b + Math.sqrt(b*b-4*a*c))/(2*a); return root; } public static double computeSecondRoot(double a, double b, double c){ double root=0.0; // local variable with initial value root = (-b - Math.sqrt(b*b-4*a*c))/(2*a);

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

return root; } public static String representFirstImaginaryRoot(double a, double b, double c){ String root=""; root += -b/(2*a)+" + (square root of ("+(-1)*(b*b-4*a*c)+")* i)/"+(2*a); return root; }

public static String representSecondImaginaryRoot(double a, double b, double c){ String root=""; root += -b/(2*a)+" - (square root of ("+(-1)*(b*b-4*a*c)+")*i)/"+(2*a); return root; }

public static void determineAndShowTheRealRoots(double a, double b, double c){ double root1 = computeFirstRoot(a,b,c); // Invoke computeFirstRoot method double root2 = computeSecondRoot(a,b,c); // Invoke computeSecondRoot method JOptionPane.showMessageDialog(null, "The roots of ("+a+")x^2+("+b+")x+("+c+")=0"+ " are "+root1+ " and " + root2+"."); return; } public static void determineAndShowTheImaginaryRoots(double a, double b, double c){ String root1 = representFirstImaginaryRoot(a,b,c); // Invoke representFirstImaginaryRoot method String root2 = representSecondImaginaryRoot(a,b,c); // Invoke representSecondImaginaryRoot method JOptionPane.showMessageDialog(null, "The roots of ("+a+")x^2+("+b+")x+("+c+")=0"+ " are "+root1+ " and " + root2+"."); return; } }

4. Study the following programs. (Check on some methods of the String class used.) /** *The following programs used some methods of the *String class. **/ import java.util.Scanner; import java.util.Random; import java.lang.*; public class NameGenerator { public static void main(String[] args){ Scanner scan = new Scanner(System.in); String s1="", s2=""; System.out.print("Enter your first name: "); s1 = scan.nextLine(); System.out.print("Enter someone's first name: "); s2 = scan.nextLine(); System.out.println("Possible names of your proteges"); System.out.println("1. " + formName3(s1,s2)); System.out.println("2. " + formName3(s2,s1)); System.out.println("3. " + formName1(s2,s1)); System.out.println("4. " + formName1(s1,s2)); System.out.println("5. " + formName5(s1,s2,5));

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

System.out.println("5. " + formName5(s2,s1,5)); System.exit(0); } // end of main method /** *Returns the string formed by concatenating the first 2 characters *of a String called name1 to and the last two charcaters of another *String called name2. **/ public static String formName1(String name1, String name2){ String result=""; result = name1.substring(0,2).concat(name2.substring(name2.length()-2)); return result; } /** *Returns the string formed by concatenating the two strings name1 and name 2 **/ public static String formName3(String name1, String name2){ String result=""; result = name1.concat(name2); return result; } /** *Returns a string with length n formed by concatenating characters that are alternately *taken from random positions of the two strings name1 and name 2. **/ public static String formName5(String name1, String name2, int n){ String result=""; Random generate = new Random(); int location = 0; for (int x=0; x<n; x++){ if (x%2 == 0){ location = generate.nextInt(name1.length()); result = result + name1.charAt(location); } else { location = generate.nextInt(name2.length()); result = result + name2.charAt(location); } } // end of for return result; } // end of formName5 method } // end of class

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

Pointers for reading Program Decomposition = Topdown Programming Approach o Because a problem is an integration of smaller problems (subproblems), the programmer needs to determine the subproblems composing a given problem. The programmer develops a program (subprogram/procedure/function/method) for each subproblem. Then, the programmer integrates the subprograms(by utilizing procedure/function/method invocation principles) A method is a group of program statements that is given a name A method is a member of a particular class A method declaration/definition specifies the code that is executed when the method is invoked. A method is defined by optional MODIFERS( public, static), followed by a RETURN TYPE( int, float, double, String, etc.), followed by an identifier that determines the METHOD NAME, followed by a list of PARAMETERS, followed by the METHOD BODY. Example public static double computeArea(double radius) { int area = Math.PI*radius*radius; return area; } Example public static double computeSubjectGrade(int pQS, int qS, int pES, int eS) { double sGrade=65; double qGrade=50, eGrade=50; qGrade = computeGrade(qS, pQS); eGrade = computeGrade(eS, pES); sGrade = (qGrade + eGrade)/ 2; return sGrade; } Example public static void showArea(double area) { System.out.println(\nArea = + area + square units); return; } To handle possible problems (e.g. errors), a method may be designed so that it throws an exception whenever a problem is encountered. The throw and catch style of handling exceptions, unusual occurrences (e.g. errors), may be studied later( IT 122).

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

The return type indicates the type of the value that will be returned by the method. The return type may be void. A method may call/invoke another method. When a method is called, the flow of control transfers to that method. Hence, the statements in the body of the called method are executed. When the method is done ( the end of the body is reached or a return statement is executed), control returns to the location where the call was made and execution continues there. The called method may be a part of the same class that is invoking it or it may be in another class. Recall how you used the methods of the Math.java program. When you had Math.sqrt(number_value) in your program, you are invoking a method of Math.java (class) in your program. If the invoked method is a part of the same class that is calling it, only the name of the method is needed to invoke it. If the invoked method is static and is in another class, the method is invoked by specifying the name of the class, the method access operator(.) and the method. (i.e. Double.parseDouble(String_value)) If the invoked method is a part of another class, a reference to an object of that class is needed. (Example: kbd.nextInt()) The return type specified in the method header can be a primitive type, class name, or the reserved word void. When a method does not return a value, void used as the return type A method that returns a value must have a return statement. When a return statement is executed, control is immediately returned to the statement in the calling method (method that made an invocation) and processing continues there. A return statement consists of the reserved word return followed by an expression that dictates the value to be returned. The expression following the return must be consistent with the return type specified in the method header. A method that does not return a value does not usually contain a return statement. The method automatically returns to the calling method when the end of the method is reached. public static void showMainMenu(){ System.out.println("Main Menu ");

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

System.out.println("----------------------------"); System.out.println("1. Math Routines"); System.out.println("2. Recording Routines"); System.out.println("3. Miscellaneous Routines"); System.out.println("4. Exit"); System.out.println("------------------------------"); Return; // OPTIONAL } The method declaration specifies the number and type of parameters that a method will accept. Parameters provide data to a method. Parameters allow the method to do its job. The parameter list in the header of a method declaration specifies the type of each value that is passed into the method and the name by which the called method will refer to each value. The parameter list in the header of a method declaration specifies the type of each value that is passed into the method and the name by which the called method will refer to each value. public static double computeFirstRootQ( double a, double b, double c ){ double root=0.0; root = (-b + Math.sqrt(b*b - 4*a*c))/ 2*a; return root; } The names of the parameters in the header of the method declaration are called formal parameters public static double computeFirstRootQ( double a, double b, double c ){ . The values passed into a method when it is invoked are called actual parameters or arguments public static void quadraticSolver(){ Scanner kbd= new Scanner(System.in); double x,y,z, root1, root2; System.out.println("You want to determine ther roots of a quadratic equation.\n"); System.out.println("Let the quadratic equation follow the form ax^2 + bx + c = 0. "); System.out.print("Enter the value of coefficient a: "); x = kbd.nextDouble(); System.out.print("Enter the value of coefficient b: "); y = kbd.nextDouble(); System.out.print("Enter the value of coefficient c: "); z = kbd.nextDouble(); root1 = computeFirstRootQ(x,y,z); root2 = computeSecondRootQ(x,y,z); System.out.println("The roots are: " + root1 + " and " + root2 + "."); } // end of quadraticSolver method

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

The parameter list in both the declaration (formal) and the invocation (actual) is enclosed by a parentheses after the method name. If there are no parameters, an empty parentheses is used The parameter list in both the declaration (formal) and the invocation (actual) is enclosed by a parentheses after the method name. FORMAL PARAMETERS public static double computeSecondRootQ (double a, double b, double c){ ACTUAL PARAMETERS root1 = computeFirstRootQ(x,y,z); root2 = computeSecondRootQ(x,y,z);

Scope of a variable The scope of a variable in a program refers to the portion of the program where the variable can be referenced. Local Variable A variable declared inside a method. The scope of a local variable is limited to the method in which it is declared. Hence, a local variable is not accessible (does not exist) outside the method in which it is declared. i.e. the scope of a local variable is the block/body of the method. Class variables (instance variables) A variable declared in a class but not inside any particular method. The scope of an instance variable is the whole class. i.e. the scope of a class variable is the block/body of the class.

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

IT 112L Programming Fundamentals I Laboratory Final Activity Number 1 General instruction: Complete the following program by providing the missing parts so that it will do what it is supposed to do as indicated in the comments. There is a missing keyword, expression, or statement where there is a blank line. The missed keywords, expressions or statements are identified as ITEM 1, ITEM 2, , ITEM 7. Verify the correctness of your answer by encoding and testing the completed program. /** If the sum of the factors that are less than n of the integer n is equal to n, n is a perfect number. For example, 6 is a perfect number because the factors of 6 that are less than 6 are 1,2 and 3 and the sum of these factors (1+2+3) is equal to 6. Also, because the factors of 28 that are less than 28 are 1,2,4,7 and 14 and that 1+2+4+7+14 is 28, 28 is a perfect number. When completed, the following program allows the user to enter a positive integer in the range 1 to 32000. The computer will then state whether the number is perfect number or not. */ import java.util.Scanner; public class PerfectNumber { // Method that returns true if a number f is a factor of a number n public static ___________________ isFactor(int f, int n){ // ITEM 1 if (n%f == 0) // n divided by f yields a 0 remainder return true; else return false; } // Method that returns the sum of the factors that are less than n of an integer n. public static int sumFactors(int n) { int sum=0; // initialize sum of factors to 0 for (int x=1; x<n; x++) { if (isFactor(x,n)) // Invoke the isFactor method sum = _____________________ ; // ITEM 2 } return sum; } // Method that returns true if an integer n is a perfect number. public static boolean isPerfect (int n) { if ( sumFactors(n) == n ) // Invoke sumFactors method return __________________; // ITEM 3 else

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

return false; } //Method that reads an returns an integer in the range 1 to a specified limit. static public int readNumber(int limit){ Scanner keyboard = new Scanner(System.in); int n; do { System.out.print("Input an integer between 1 and " + limit + " : "); n = _______________________________________________; // ITEM 4 if (n<1 || n>=limit) { System.out.println("You did not enter a number between 1 and "+ limit + "."); } } ____________________________________; // ITEM 5 return n; } // The main method reads and evaluate if a number is perfect public static void main(_________________________________________) { // ITEM 6 Scanner keyboard = new Scanner(System.in); int n=0; n = readNumber(32000); if (____________________________){//ITEM 7 invoke isPerfect method and pass n to it System.out.println(n + " is a perfect number."); } else { System.out.println(n + " is not a perfect number."); } }// end of main method } // end of class Prime

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

IT 112L Programming Fundamentals I Laboratory Final Activity Number 2 Complete the following program by providing the missing keywords, expressions or statements so that the program will solve the given problem. The missed keywords, expressions or statements are identified as No. 1, No. 2, , No. 5. . Verify the correctness of your answers by encoding and testing the completed program. /** The final grade to be given to a student of Saint Louis University is computed by the formula: finalGrade = (prelimGrade + midtermGrade + tentativeFinalGrade)/3; Suppose the prelims and midterms are finished and that the prelim and the midterm grades are already known. What tentative final grade should a student earn so that the student will get the final grade that he/she desires. When completed, the following program computes the tentative final grade that should be earned after reading a prelim grade, midterm grade and desired final grade. */ import java.util.*; public class TentativeFinalGrade { /** * A method that returns a name read from the keyboard. */ public static String readName(String promptMessage){ Scanner keyboard= new Scanner(System.in); String name=""; System.out.print(promptMessage + " : "); name = ______________________________________________________________;// No. 1 return name; } /** * A method that returns a whole number read from the keyboard. */ public static int readInt(String promptMessage){ Scanner keyboard= new Scanner(System.in); int value=0; String input=""; System.out.print(promptMessage + " : "); input = keyboard.nextLine(); value = _________________________________________________________ // No. 2 return value; } /** * A method that returns the t that satisfies f=(p+m+t)/3 when f, p and m are given */ public static int computeRequiredTFG(int p, int m, int f){

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

int t =50; t = 3*f - (p+m) ; __________________________________________________; // No. 3 } /** *A method that shows on screen the student name and the student's grades */ public static void showStudent(String n, int p, int m, int t, int f){ System.out.printf("%35s%s%n","Name ................: ", n); System.out.printf("%35s%d%n","Prelim Grade ........: ", p); System.out.printf("%35s%d%n","Midterm Grade .......: ", m); System.out.printf("%35s%d%n","Desired Final Grade : ", f); System.out.printf("%35s%d%n","Required Tentative Final Grade: ", t); if (___________________________________) { // No. 4 Check if it exceeds 100 System.out.println(" Sorry! It is impossible to get your desired final grade."); System.out.println("The highest grade that you can get if you get perfect scores in all final requirements is " + (p+m+100)/3+"."); } else { System.out.println(" Good luck! Your goal is not impossible."); } } // The main method of the program __________________________________________________________{ //No. 5 main method header Scanner keyboard = new Scanner(System.in); String studName=""; char wantToCompute='y'; int prelimGrade=50, midtermGrade=50, desiredFinalGrade=50, neededTentativeFinalGrade=50; while (wantToCompute=='y' || wantToCompute == 'Y'){ studName = readName("Enter the name of the student"); prelimGrade = readInt("Enter your prelim grade"); midtermGrade = readInt("Enter your midterm grade"); desiredFinalGrade = readInt("Enter your desired final grade"); neededTentativeFinalGrade=computeRequiredTFG(prelimGrade,midtermGrade, desiredFinalGrade); showStudent(studName, prelimGrade, midtermGrade, neededTentativeFinalGrade, desiredFinalGrade); System.out.print("\nDo you want to compute again <y/n>? "); wantToCompute = keyboard.nextLine().charAt(0); } System.exit(0); } // end of main method } // end of class

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

IT 112L Programming Fundamentals I Laboratory Final Activity Number 3 Complete the following program by providing the missing keywords, expressions or statements so that the program solves the given problem. The missed keywords, expressions or statements are identified as ITEM 1, ITEM 2, , ITEM 7. Encode and test the completed program. /** When completed, the following program computes the tax amount corresponding to a given taxable income. The tax due is determined based on the following table: If taxable income is then tax due is <=25,000.00 4,000.00 >25,000.00 but <= 125,000.00 4,000.00 + 8%(taxable income - 25,000.00) >125,000.00 but <= 525,000.00 12,000.00+10%(taxable income - 125,000.00) >525,000.00 52,000.00+12%(taxable income - 525,000.00) */ import java.util.*; public class ModularizedTaxationProgram{ public static void main(String[] args){ double taxableIncome; double taxDue; // Introduce the program by invoking the showIntroduction method showIntroduction();
// Read the taxable income from the keyboard by invoking the readTaxableIncome method

taxableIncome = readTaxableIncome(); // Compute the tax due by invoking the computeTaxDue method taxDue = computeTaxDue(determineBracket(taxableIncome), taxableIncome ); // Show the taxable income by invoking the showResults method showResults(taxableIncome, taxDue); System.exit(0); } // end of main method /** *shows statements that introduce the application on the output screen */ public static ______________________ showIntroduction(){ // ITEM 1 System.out.println("Hypothetical Tax Computation Program"); System.out.println("------------------------------------"); System.out.println("This program is for the computation of the tax due from a taxpayer with a known taxable income."); System.out.println(); } // end of showIntroduction method /** * returns a taxable income amount read from the keyboard] */

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

public static _______________________ readTaxableIncome(){ // ITEM 2 Scanner input=new Scanner(System.in); double income=0.0; do { System.out.print("Enter the taxable income: "); income = Double.parseDouble(input.nextLine()); } while (income < 0); _____________________________________________; // ITEM 3 } // end of readTaxableIncome method

/** * returns the bracket corresponding to a given taxable income based on the following rule If taxable income is then bracket is <=25,000.00 1 >25,000.00 but <= 125,000.00 2 >125,000.00 but <= 525,000.00 3 >525,000.00 4 */ public static int determineBracket(_________________________________){ // ITEM 4 int bracket=0; if (taxableIncome <= 25000.00) bracket = 1; else if (taxableIncome <= 125000.00) bracket = 2; else if (taxableIncome <= 525000.00) bracket = 3; else bracket = 4; return bracket; } // end of determineBracket method /** * returns the tax amount due corresponding to a given pair of bracket and taxable income based * on the following rule If bracket of income is then tax due is 1 4,000.00 2 4,000.00 + 8%(taxable income - 25,000.00) 3 12,000.00+10%(taxable income - 125,000.00) 4 52,000.00+12%(taxable income - 525,000.00) */ public static _______________ computeTaxDue(int bracket, double taxableIncome){ // ITEM 5 double taxDue=0.0;

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

switch (bracket){ case 1: taxDue = 4000.00; break; case 2: taxDue = 4000.00 + (taxableIncome-25000.00)*0.08; break; case 3: taxDue = 12000.00 + (taxableIncome-125000.00)*0.10; break; case 4: taxDue = 52000.00 + (taxableIncome-525000.00)*0.12; break; default: taxDue = 0.00; } ______________________________________________; // ITEM 6 } // end of computeTaxDue method /** * displays a given taxable income and the corresponding tax amount on the output screen */ public static ________________ showResults(double taxableIncome, double taxDue){ // ITEM 7 System.out.println(); System.out.printf("%-20s%15.2f%n","Taxable Income: ",taxableIncome); System.out.printf("%-20s%15.2f%n", "Tax Due = ", taxDue); }// end of showResults method } //end of ModularizedTaxationProgram class

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

Pointers for reading:

In Java as well as in other programming languages, there is a facility that allows one variable name to store a list of data. The facility 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. An array may be imagined as a stretched variable a location that has one identifier name but the location is capable of holding more than one value.

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

Arrays must be declared like all variables. When declaring an array, we list the data type, followed by a set of square brackets[], followed by the identifier name. For example,
int []ages;

or we can place the brackets after the identifier. For example,


int ages[];

After declaring, we must create the array and specify its length with a constructor statement. This process in Java is called instantiation (the Java word for creates). For example,
//declaration int ages[]; //instantiate object ages = new int[100];

or, can also be written as,


//declare and instantiate object int ages[] = new int[100];

In the example, the declaration tells the Java Compiler that the identifier ages will be used as the name of an array containing integers. The instantiation tells the computer that the array will hold 100 elements, hence, enough memory slots should be allocated to the array.

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

The size of an array cannot be changed once initialized. Instead of using the new keyword to instantiate an array, you can also automatically declare, construct and assign values at once. This approach is used when the elements of the array are known during programming time. For example. int[] year = {1,2,3,4,5};
String days[] = {Mon, Tue, Wed,Thu,Fri,Sat,Sun};

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

To access an array element, or a part of the array, we use a number called an index or a subscript. An index (a.k.a. subscript) is assigned to each member of the array, allowing the program and the programmer to access individual values when necessary. In Java, index is an integer that begins with zero. Hence, the elements inside an array are associated with indices from 0 to (sizeOfArray-1). The index of the first element is 0, the index of the second element is 1 and so on. Consequently, the index of the last element is equal to the (sizeOfArray 1).

Elements of an arry may be arranged (i.e. sorted). Algorithms for sorting such as Balloon Sort, Bubble Sort, Selection Sort, Insertion Sort and Quick Sort may be implemented.

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

IT 112L Programming Fundamentals I Laboratory Final Activity Number 4 (Using a 1-dimensional array) Required: 1. Develop a program that will allow the computer to accept some numbers that are not sorted. The numbers should be stored in a one-dimensional array. The computer will then display the numbers following descending order and ascending order. 2. Develop a program that will allow the computer to accept some names that are not necessarily in alphabetical ordering. The names should be stored in a one-dimensional array. The computer will then display the names following lexicographic ordering (i.e. alphabetical ordering).

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

IT 112L Programming Fundamentals I Laboratory Final Activity Number 5 (Using parallel arrays) Required: Encode, test and understand the following programs (Program A and Program B). Modify Program B by implementing the Selection Sort algorithm instead of the Balloon Sort algorithm. Program A: Program with only the main methods
/** *A program that creates a class record. The names, quiz scores, exam scores, *quiz grades, exam grades and subject grades are stored by parallel arrays. **/ import java.util.Scanner; public class GradeCalculatorUsingArrays { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); int[] quizScore; // array to hold quiz scores of students int[] examScore; // array to hold exam scores of students String[] names; // array to hold names of students int perfectQuizScore; // variable to hold perfect quiz score int perfectExamScore; // variable to hold perfect exam score double[] quizGrade; // array to hold quiz grades of students. double[] examGrade; // array to hold examination grades of students double[] subjectGrade; // array to hold subject grades of students int size; /*Accept the number of students( class size). The class size must be greater than 0.*/ do { System.out.print("Enter the number of students: "); size = Integer.parseInt(keyboard.nextLine()); if (size <0) System.out.println("The number of students must be greater than 0."); } while (size < 0); // Instantiate arrays, the number of cells for each array must be equal to size quizScore = new int[size]; examScore = new int[size]; names = new String[size]; quizGrade = new double[size]; examGrade = new double[size]; subjectGrade = new double[size]; /* Accept the perfect quiz score: The perfect score must be greater than 0. The computer lets the user re-enters a perfect score in case the value entered is invalid.*/ do { System.out.print("Enter the Perfect Quiz Score : ");

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

perfectQuizScore = Integer.parseInt(keyboard.nextLine()); if (perfectQuizScore <= 0){ System.out.println("Invalid value! The perfect score must be greater than 0."); } } while (perfectQuizScore <= 0); /* Accept the perfect exam score: The perfect score must be greater than 0. The computer lets the user re-enter a perfect score in case the value entered is invalid.*/ do { System.out.print("Enter the Perfect Examination Score : "); perfectExamScore = Integer.parseInt(keyboard.nextLine()); if (perfectExamScore <= 0){ System.out.println("Invalid value! Value must be greater than 0."); } } while (perfectExamScore <= 0);

// Accept names and scores and compute the grade of each student for (int x=0; x<size; x++) { System.out.print("Enter the name of student "+ (x+1) + ": "); names[x] = keyboard.nextLine(); /* Accept the quiz score of a student: The quiz score must not be greater than the perfect quiz score. The computer lets the user re-enter a score in case the value entered is invalid. */ do { System.out.print("Enter the quiz score of "+ names[x] +" : "); quizScore[x] = Integer.parseInt(keyboard.nextLine()); if (quizScore[x] > perfectQuizScore){ System.out.println("Invalid value! Score must not be greater than perfect score."); } } while (quizScore[x] > perfectQuizScore); /* Accept the exam score: The exam score must not be greater than the perfect exam score. The computer lets the user re-enter a score in case the value entered is invalid.*/ do { System.out.print("Enter the examination score of " + names[x] + " : "); examScore[x] = Integer.parseInt(keyboard.nextLine()) ; if (examScore[x] > perfectExamScore){ System.out.println("Invalid value! Score must not be greater than perfect score."); } } while (examScore[x] > perfectExamScore); quizGrade[x] = (double) quizScore[x]/perfectQuizScore*50 + 50; examGrade[x] = (double) examScore[x]/perfectExamScore*50 + 50; subjectGrade[x] = (quizGrade[x] + examGrade[x])/ 2; // Check if subject grade is 100 then reset it to 99 if (subjectGrade[x] > 99) subjectGrade[x] = 99; //Check if subject grade is lesst than 65 then reset it to 65 if (subjectGrade[x] < 65 )

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

subjectGrade[x] = 65; } // end of for // Display the scores and grades of students System.out.println("\n\nPerfect Quiz Score = " + perfectQuizScore); System.out.println("\nPerfect Exam Score = " + perfectExamScore); System.out.printf("%10s%10s%10s%10s%10s%10s\n","", "Quiz", "Exam", "Quiz", "Exam", ""); System.out.printf("%10s%10s%10s%10s%10s%10s\n","name", "Score", "Score", "Grade", "Grade", "Grade"); System.out.printf("%10s%10s%10s%10s%10s%10s\n","--------", "--------", "--------", "-------", "--------", "-------"); for (int y= 0; y < subjectGrade.length; y++){ System.out.printf("%10s%10d%10d%10.0f%10.0f%10.0f\n",names[y], quizScore[y], examScore[y], quizGrade[y], examGrade[y], subjectGrade[y]); } System.out.printf("%10s%10s%10s%10s%10s%10s\n","--------", "--------", "--------", "-------", "--------", "-------"); // Compute and show the average of the subject grades // get the total of all the subject grades double totalGrade=0; // variable to hold the sum of grades for (int g=0; g<subjectGrade.length; g++){ totalGrade += subjectGrade[g]; } double averageGrade = totalGrade/subjectGrade.length; System.out.printf("%n%25s%5.2f%n", "Average Grade =", averageGrade); // determine and show the lowest subject grade double lowestGrade= subjectGrade[0]; // first grade is the lowest grade initially for (int gr=1; gr<subjectGrade.length; gr++){ if (lowestGrade > subjectGrade[gr]) lowestGrade = subjectGrade[gr]; } System.out.printf("%n%25s%5.2f%n", "Lowest Grade =", lowestGrade); // determine and show the highest subject grade double highestGrade= subjectGrade[0]; // first grade is the highest grade initially for (int h=1; h<subjectGrade.length; h++){ if (highestGrade < subjectGrade[h]) highestGrade = subjectGrade[h]; } System.out.printf("%n%25s%5.2f%n", "Highest Grade =", highestGrade); System.exit(0); } // end of the main method } // end of class

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

Program B: Program with methods aside from the main method (With Program Decomposition)
/** *A program that creates a class record. The names, quiz scores, exam scores, *quiz grades, exam grades and subject grades are stored by parallel arrays. **/ import java.util.Scanner; public class GradeUsingArrays2 { static Scanner kbd = new Scanner(System.in); public static void main(String[] args) { int[] quizScore; // array to hold quiz scores of students int[] examScore; // array to hold exam scores of students String[] names; // array to hold names of students int perfectQuizScore; // variable to hold perfect quiz score int perfectExamScore; // variable to hold perfect exam score double[] quizGrade; // array to hold quiz grades of students. double[] examGrade; // array to hold examination grades of students double[] subjectGrade; // array to hold subject grades of students int size; //Accept the number of students( class size). The class size must be greater than 0 but less than 100. size = readInteger(0,100,"Enter number of students"); // Instantiate arrays, the number of cells for each array must be equal to size quizScore = new int[size]; examScore = new int[size]; names = new String[size]; quizGrade = new double[size]; examGrade = new double[size]; subjectGrade = new double[size]; //Accept the perfect quiz score. The perfect score must be greater than 0 but less than 1000. perfectQuizScore = readInteger(0,1000,"Enter the perfect quiz score"); //Accept the perfect exam score. The perfect score must be greater than 0 but less than 1000. perfectExamScore = readInteger(0,1000,"Enter the perfect exam score"); // Accept names and scores and compute the grade of each student for (int x=0; x<size; x++) { names[x] = readString("Enter the name of student "+(x+1)); /* Accept the quiz score of a student. The quiz score must be at least 0 and must not be greater than the perfect quiz score. */ quizScore[x] = readInteger(0,perfectQuizScore,"Enter the quiz score of "+ names[x]); /* Accept the exam score. The exam score must be at least 0 and must not be greater than the perfect exam score. */ examScore[x] = readInteger(0,perfectExamScore,"Enter the examination score of " + names[x]);

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

// Compute the grade for the quiz quizGrade[x] = computeGrade(quizScore[x],perfectQuizScore); // Compute the grade for the exam examGrade[x] = computeGrade(examScore[x],perfectExamScore); // Compute the grade for the subject subjectGrade[x] = (quizGrade[x] + examGrade[x])/ 2; } // end of for // Display the scores and grades of students System.out.println("\n\nPerfect Quiz Score = " + perfectQuizScore); System.out.println("\nPerfect Exam Score = " + perfectExamScore); showData(names, quizScore, examScore, quizGrade, examGrade, subjectGrade); // Compute and show the average of the subject grades double averageGrade = computeAverage(subjectGrade); System.out.printf("%n%25s%5.2f%n", "Average Grade =", averageGrade); // determine and show the lowest subject grade double lowestGrade = findLowest(subjectGrade); System.out.printf("%n%25s%5.2f%n", "Lowest Grade =", lowestGrade); // determine and show the highest subject grade double highestGrade = findHighest(subjectGrade); System.out.printf("%n%25s%5.2f%n", "Highest Grade =", highestGrade); // Arrange list from highest to lowest based on subject grade System.out.println(); System.out.println("Sorted Record"); parallelSortD(names, quizScore, examScore,quizGrade, examGrade, subjectGrade); showData(names,quizScore,examScore,quizGrade,examGrade,subjectGrade); System.exit(0); } // end of the main method

/** Reads and returns an integer from input device after seeing a prompt message. The value should be in the range lowLimit to upLimit. */ public static int readInteger(int lowLimit, int upLimit, String prompt){ int value=0; do{ System.out.print(prompt+ " : "); value = Integer.parseInt(kbd.nextLine()); if (value<lowLimit || value>upLimit){ System.out.println("You must enter an integer in the range "+lowLimit+ " to " + upLimit +"."); } } while ( value<lowLimit || value>upLimit);

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

return value; } /** Reads and returns a floating point number from input device after seeing a prompt message. The value should be in the range lowLimit to upLimit. */ public static double readDouble(double lowLimit, double upLimit, String prompt){ double value=0; do{ System.out.print(prompt + " : "); value = Double.parseDouble(kbd.nextLine()); if (value<lowLimit || value>upLimit){ System.out.println("You must enter a floating point number in the range "+lowLimit+ " to " + upLimit +"."); } } while ( value<lowLimit || value>upLimit); return value; } /** Reads and returns a string from input device after seeing a prompt message. The String must not be a null string. */ public static String readString(String prompt){ String value=""; do{ System.out.print(prompt + " : "); value = kbd.nextLine(); if (value.compareTo("")==1){ System.out.println("You must type a string that is not null."); } } while ( value.compareTo("")==0); return value; } /** Finds and returns the lowest value from an array of floating point numbers */ public static double findLowest(double[] values){ double result=values[0]; // let lowest be the first limit for (int x=1; x<values.length; x++) // find out if an element after the if (values[x] < result) // first is lower result = values[x]; // then set lowest to such element return result; } /** Finds and returns the highest value from an array of floating point numbers */ public static double findHighest(double[] values){ double result=values[0]; // let highest be the first limit

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

for (int x=1; x<values.length; x++) // find out if an element after the if (values[x] > result) // first is higher result = values[x]; // then set highest to such element return result; } /** Computes and returns the average of the elements an array of floating point numbers */ public static double computeAverage(double[] values){ double total=0; // to hold the total of all elements double average=0; // to hold the average for (int x=0; x<values.length; x++) // add the elements total = total + values[x]; //compute the average average = total/values.length ; // total divided by number of elements return average; } /** Computes and returns a grade corresponding to a score. The grade equals score/perfectScore*50 + 50. If computation yields more than 99, the grade is set to 99. If computation yields less than 65, the grade is set to 65, */ public static double computeGrade(int score, int perfect){ double result = 65; result = (double) score/perfect*50 + 50; if (result>99) result = 99.0; if (result <65) result = 65.0; return result; } /**The ff. method sorts the 2 arrays in parallel following the balloon sort algorithm.*/ public static void parallelSort(String[] c, double[] a){ for (int x=0; x<c.length-1; x++){ for (int y=x+1; y<c.length; y++){ if ( c[x].compareToIgnoreCase(c[y]) > 0 ) { String temp = c[x]; c[x] = c[y]; c[y] = temp; double dummy = a[x]; a[x] = a[y]; a[y] = dummy; } } } }

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

/**The ff. method sorts the 6 arrays in parallel following the balloon sort algorithm. Sorting is based on the string array c. */ public static void parallelSort(String[] c, int[] q, int[] e, double[] p, double[] a, double[] i){ for (int x=0; x<c.length-1; x++){ for (int y=x+1; y<c.length; y++){ if ( c[x].compareToIgnoreCase(c[y]) > 0 ) { String temp = c[x]; c[x] = c[y]; c[y] = temp; int t=q[x]; q[x] = q[y]; q[y] = t; t=e[x]; e[x] = e[y]; e[y] = t;

double dummy = p[x]; p[x] = p[y]; p[y] = dummy; dummy = a[x]; a[x] = a[y]; a[y] = dummy; dummy = i[x]; i[x] = i[y]; i[y] = dummy; } } } } /**The ff. method sorts the 6 arrays in parallel following the balloon sort algorithm. Sorting is based on the double array i. */ public static void parallelSortD(String[] c, int[] q, int[] e, double[] p, double[] a, double[] i){ for (int x=0; x<c.length-1; x++){ for (int y=x+1; y<c.length; y++){ if ( i[x]<(i[y]) ) { String temp = c[x]; c[x] = c[y]; c[y] = temp; int t=q[x]; q[x] = q[y]; q[y] = t; t=e[x];

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

e[x] = e[y]; e[y] = t;

double dummy = p[x]; p[x] = p[y]; p[y] = dummy; dummy = a[x]; a[x] = a[y]; a[y] = dummy; dummy = i[x]; i[x] = i[y]; i[y] = dummy; } } } }

/** Display the scores and grades of students. Displays elements of parallel arrays */ public static void showData(String[] names, int[] quizScore, int[] examScore, double[] quizGrade, double[] examGrade, double[] subjectGrade ){ System.out.printf("%10s%10s%10s%10s%10s%10s\n","", "Quiz", "Exam", "Quiz", "Exam", ""); System.out.printf("%10s%10s%10s%10s%10s%10s\n","name", "Score", "Score", "Grade", "Grade", "Grade"); System.out.printf("%10s%10s%10s%10s%10s%10s\n","--------", "--------", "--------", "-------", "--------", "-------"); for (int y= 0; y < subjectGrade.length; y++){ System.out.printf("%10s%10d%10d%10.0f%10.0f%10.0f\n",names[y], quizScore[y], examScore[y], quizGrade[y], examGrade[y], subjectGrade[y]); } System.out.printf("%10s%10s%10s%10s%10s%10s\n","--------", "--------", "--------", "-------", "--------", "-------"); } } // end of class

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

IT 112L Programming Fundamentals I Laboratory Final Activity Number 6 (Final Programming Project)

/** Complete and improve the following program. Change the opening screen such that your name is shown as the programmer. You may modify the given codes You may introduce additional menu items. Be guided by the following project Evaluation Form Major Final Project Evaluation Form (To be accomplished by the student programmer) Instruction Evaluate the program that you have written based on the following table of criteria(A) and checklist of requirements(B). Indicate your score for each criterion specified in the table(A). Write your scores (points awarded) on the spaces provided. In the checklist(B), put check marks on the program items that you have completed. In addition, specify additional items where appropriate. A hardcopy of an accomplished copy of this form should be submitted on the meeting when the final program will be uploaded(Week 1 of October). Use a long bond paper when printing the evaluation form. ___________________________________________ Programmers Name & Signature (A) Table Criteria ______________________ Class Code and Schedule Perfect Points 25 25 10 10 Points Awarded

Completeness (Every menu item that was required is working) Correctness (Every menu item corresponds to a correct output) Following of spacing Convention (Statements under the same block are always indented and aligned) Following naming convention and using descriptive identifiers (Every name of a method or variable is suggestive of what is represented and the camel case style of specifying identifiers is always followed.) Aesthetics (The layout of every output displayed is nice and informative) Add-ons and Overall Impression on the program (Some items that were not required are included in the program and these items added are working correctly. In addition, there are additional impressive features such as Graphical User Interface (GUI).) (B) Checklist Main Menu __ 1. Math routines __ 2. Recording routines __ 3.Miscellaneous routines __ 4. Other Routines Introduced (please specify)

5 25

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

________________________________, _________________________________, ________________________________ Math Routines (Please check if the item is complete not necessarily correct.) __1. Determine whether an integer is odd or even __2. Determine sum of a series __3. Determine the factors of a number ___4. Determine if a number is prime __5. Determine the area of a circle __6. Determine the area of a square __7. Determine the area of a triangle __8. Determine the area of a rectangle __9. Determine the area of a trapezoid __10. Determine the area of a parallelogram __11. Determine if an integer is a perfect number __12. Generate a multiplication table __13. Determine the roots of a quadratic equation __14. Generate a Fibonacci Sequence __15. Generate a Pascal's Triangle __16. Other choices added (Please specify) ____________________________________ , __________________________________ _____________________________________ , __________________________________ Recording Routines(Please check if the item is complete not necessarily correct.) __1. Accept and sort list of students __2. Accept and sort list of Salesmen __3. Accept pairs of names and grades and sort list according to name __4. Accept pairs of names and grades and sort list according to grade __5. Other choices added (Please Specify) _____________________________________, _____________________________________ ____________________________________, _____________________________________ Miscellaneous Routines (Please check if the item is complete not necessarily correct.) __1. Number Guessing Game __2. A(H1N1) Self-Diagnostic Procedure __3. Bills distribution of an amount of Money __4. Interest of Money Invested __5. Income Tax Computation __6. Insect Population Growth Rate __7. Water Bill computation. __8. Electric Bill computation. __9. Mobile Phone Load Balance Computation. __10. Other choices added (Please specify) _____________________________________, _____________________________________ **/

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

import java.util.Scanner; import java.util.Random; public class MyProgramming1Project{ // main method public static void main(String[] args){ Scanner kbd = new Scanner(System.in); int myChoice=0; showIntroduction(); kbd.nextLine(); do { showMainMenu(); myChoice=enterChoice(1,4); switch(myChoice){ case 1 : mathSolver(); break; case 2 : recordKeeping(); break; case 3 : miscellaneousProcesses(); break; case 4: System.out.println("Thank you for using my program."); System.out.println("Enjoy the rest of your day."); }//end switch } while (myChoice != 4); }//end main method public static void showIntroduction(){ System.out.println("\n\n\n"); System.out.println("College of Information and Computing Sciences"); System.out.println(" Saint Louis University"); System.out.println(" Baguio City "); System.out.println("---------------------------------------------"); System.out.println("\n"); System.out.println(" Kyle Gem Lene Michael "); System.out.println(" Programmer"); System.out.println("\n"); System.out.print("Please press a key to see Main Menu..."); }

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

public static void showMainMenu(){ System.out.println("Main Menu "); System.out.println("----------------------------"); System.out.println("1. Math Routines"); System.out.println("2. Recording Routines"); System.out.println("3. Miscellaneous Routines"); System.out.println("4. Exit"); System.out.println("------------------------------"); } public static void showMenu1(){ System.out.println("Math Routine Submenu "); System.out.println("-----------------------------------------------"); System.out.println("1. Determine whether an integer is odd or even"); System.out.println("2. Determine sum of a series"); System.out.println("3. Determine the factors of a number"); System.out.println("4. Determine if a number is prime"); System.out.println("5. Determine the area of a circle"); System.out.println("6. Determine the area of a square"); System.out.println("7. Determine the area of a triangle"); System.out.println("8. Determine the area of a rectangle"); System.out.println("9. Determine the area of a trapezoid"); System.out.println("10. Determine the area of a parallelogram"); System.out.println("11. Determine if an integer is a perfect number"); System.out.println("12. Generate a multiplication table"); System.out.println("13. Determine the roots of a quadratic equation"); System.out.println("14. Generate a Fibonacci Sequence"); System.out.println("15. Generate a Pascal's Triangle"); System.out.println("16. Back to Main Menu"); System.out.println("------------------------------------------------"); } public static void showMenu2(){ System.out.println("Recording Routine Submenu "); System.out.println("-----------------------------------------------"); System.out.println("1. Accept and sort list of students"); System.out.println("2. Accept and sort list of Salesmen"); System.out.println("3. Accept pairs of names and grades and sort list according to name"); System.out.println("4. Accept pairs of names and grades and sort list accroding to grade"); System.out.println("5. Back to Main Menu"); System.out.println("------------------------------------------------"); } public static void showMenu3(){ System.out.println("Miscellaneous Routine Submenu "); System.out.println("-----------------------------------------------");

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

System.out.println("1. Number Guessing Game"); System.out.println("2. A(H1N1) Self-Diagnostic Procedure "); System.out.println("3. Bills distribution of an amount of Money"); System.out.println("4. Interest of Money Invested "); System.out.println("5. Income Tax Computation"); System.out.println("6. Insect Population Growth Rate"); System.out.println("7. Water Bill computaion."); System.out.println("8. Electric Bill computation."); System.out.println("9. Mobile Phone Load Balance Computation."); System.out.println("10. Back to Main Menu"); System.out.println("------------------------------------------------"); } public static int enterChoice(int min, int max){ Scanner kbd= new Scanner(System.in); int choice=0; do{ System.out.print("Input the number corresponding to your choice: "); choice=kbd.nextInt(); if (choice<min || choice>max) System.out.println("Invalid choice. Please ensure that you enter a number from " + min + " to " + max + "."); } while (choice < min || choice > max); return(choice); } public static void mathSolver(){ Scanner kbd = new Scanner(System.in); int choice=0; do{ showMenu1(); choice= enterChoice(1,16); switch (choice){ case 1: int y; System.out.print("Enter an integer :"); y = kbd.nextInt(); System.out.println( detOddEven(y)); System.out.println(); System.out.print("press enter to continue..."); kbd.nextLine(); kbd.nextLine(); break;

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

case 2: int z; System.out.print("Enter an integer :"); z = kbd.nextInt(); System.out.println("The sum of the series is " +getSumOfSeries(z)); System.out.println(); System.out.print("press enter to continue..."); kbd.nextLine(); kbd.nextLine(); break; case 3: // TO DO break; case 4: // TO DO break; case 5: // TO DO break; case 6: // TO DO break; case 7: // TO DO break; case 8: // TO DO break; case 9: // TO DO break; case 10: // TO DO break; case 11: // TO DO break;

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

case 12: // TO DO break; case 13: // TO DO break; case 14: int t; System.out.print("\nHow many terms do you want? "); t = kbd.nextInt(); generateFibonacciSequence(t); System.out.print("Press enter to continue..."); kbd.nextLine(); kbd.nextLine(); break; case 15: // TO DO break; case 16 : // TO DO } // end of cases } while (choice != 16); } // end of mathSolver method public static void recordKeeping(){ Scanner kbd = new Scanner(System.in); int choice=0; do{ showMenu2(); choice = enterChoice(1,5); switch (choice){ case 1: acceptAndSortNames(); break; case 2: // TO DO break; case 3: // TO DO

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

break; case 4: // TO DO break; } // end of cases } while (choice != 5); } // end of recordKeeping method public static void acceptAndSortNames(){ Scanner kbd = new Scanner(System.in); String[] names; int n=0; System.out.print("How many names will be sorted? "); n = Integer.parseInt(kbd.nextLine()); names = new String[n]; //Populate array names for (int z=0; z<names.length; z++){ System.out.print("Enter name of student " + (z+1) + ": "); names[z] = kbd.nextLine(); } // Sort the names array balloonSortArray(names); //Show elements of names array showElements(names); } public static void miscellaneousProcesses(){ Scanner kbd = new Scanner(System.in); int choice=0; do{ showMenu3(); choice = enterChoice(1,10); switch (choice){ case 1: higherOrLower(); System.out.println(); System.out.print("press enter to continue..."); kbd.nextLine(); break; case 2: //TO DO break;

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

case 3: // TO DO break; case 4: // TO DO break; case 5: // TO DO break; case 6: insectPopulationGrowthRate(); System.out.println("Press enter to continue..."); kbd.nextLine(); kbd.nextLine(); break; case 7: // TO DO break; case 8: // TO DO break; case 9: // TO DO break; case 10: // TO DO } // end of cases } while (choice != 10); } // end of miscellaneousProcesses method public static String detOddEven(int number){ if (number % 2 !=0) return(" The number is odd "); else return(" The number is even "); }

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

public static double getSumOfSeries(int n){ double sum=0; if(n > 1 && n%2==0){ for (int ctr = n; ctr>1; ctr-=2) sum+=(1.0/ctr); } return(sum); }// end of method public static void higherOrLower(){ Scanner keyboard = new Scanner(System.in); Random rndNoGen = new Random(); // Random class is a facility for // generating random numbers int secretNo = rndNoGen.nextInt(100) + 1; // generate a random number // that is in the range from 1 to 100. System.out.println("I have an integer from 1 to 100."); System.out.println("You have 10 chances to guess it."); int guessNo = 0; int guess; boolean gotIt = false; do { System.out.print("\nGuess #" + (guessNo+1) + ": "); guess = keyboard.nextInt(); if (guess == secretNo) { gotIt = true; break; // terminate the loop immediately } else { if (guessNo == 10) { break; // terminate the loop immediately } else { if (guess > secretNo) { System.out.println("Try something lower."); } else { System.out.println("Try something higher."); } guessNo++; } } } while (guessNo < 10); if (gotIt) { System.out.println("\nCongratulations!!!");

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

System.out.println("Got it in " + guessNo + " trial(s)!"); } else { System.out.println("\nSorry. No more guesses left."); System.out.println("The number is " + secretNo + "."); System.out.println("Better luck next time."); } System.out.println("\nThanks for playing!!!"); System.out.println("Have a nice day :)!"); } // end of higherOrLower method public static void generateFibonacciSequence(int nTerms) { int first=1, second=1; int temp; int count=nTerms; System.out.print("Terms: "); if (nTerms==1) System.out.println(first); if (nTerms==2) System.out.println(first + " , " + second); if (nTerms>2){ System.out.print(first + " , " + second); count = count - 2; // remaining terms to print. while ( count>0){ temp = first; first = second; second = temp + second; System.out.print(" , " + second); count--; } /// end of while System.out.println(); } // end of if nTerms>2 } // end of generateFibonacciSequence method public static void insectPopulationGrowthRate(){ Scanner kbd= new Scanner(System.in); int fSize, iSize; double rateOfGrowth; System.out.println("Kindly enter the following:"); System.out.print(" Initial population ... "); iSize = kbd.nextInt(); System.out.print(" Current population..... "); fSize = kbd.nextInt();

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

rateOfGrowth = (fSize - iSize)*100.0/iSize; System.out.print("\nThe rate of growth is " + rateOfGrowth + "%"); System.out.println(" because (" + fSize + " - " + iSize + ")*100/" + iSize + " is " + rateOfGrowth + "%"); } // end of insectPopulationGrowthRate method /** *Displays the elements of an array **/ public static void showElements(String[] array){ for (int x=0; x<array.length; x++) System.out.println(array[x]); } /** *Some basic algorithms *1. Linear Search(Search an item in a given list) * Search an item from a list by starting from the first element, then second, then third an so on. * * Check if the first element is the item your are searching. * If the first element is the same as the item being searched, stop and declare that the item is found. * Otherwise, check the next item... * *2. Balloon Sort (Arrange the elements of a list) * a. Determine which element should be in the first position: * Swap the first and the second elements if needed. * Swap the first and the third elements if needed. * Repeat the process until the first is compared with the last element. * By then, the first element of the list is positioned correctly. * * b. Determine which element should be in the second position: * Swap the second and the third elements if needed. * Swap the second and the fourth elements if needed. * Repeat the process until the second is compared with the last element. * By then, the second element of the list is positioned correctly. * * ...and so on * *3. Selection Sort (Arrange the elements of a list) * a. Determine the index of the element that should be placed in the first cell by checking all elements from first to last position. * Swap the first element with the element that should be in the first cell. * * b. Determine the index of the element that should be placed in the second cell by checking all elements from second to last position. * Swap the second element with the element that should be in the second cell.

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

* * ... and so on * *4. Binary Search (Search an item in a given list) * Assume that the list is sorted in ascending order, start the search at the middle cell. * If the middle element is the one you are looking for, stop and declare that the item is found. * Otherwise, drop half of the list by comparing the item being searched with the middle element. * If the middle element is greater than the item being search, this means the item being search could be at the left of the middle element. * Then, do the search in the first half of the list ( forget about the second half) * If the middle element is less than the item being search, this means the item being search could be at the right of the middle element. * Then, do the search in the second half of the list ( forget about the first half) * * * Again, start the search at the middle cell of the list that remained after dropping half of the list. Do the process repeatedly until * the item is found or until there is no more list to be halved. **/ /** *This method uses he LINEAR algorithm to determine if an item is a member of an array. *The method returns true if searchKey is in a given array of int. */ public static boolean linearSearch(int[] array, int searchKey){ boolean r=false; for (int index=0; index < array.length && r==false; index++){ if (array[index] == searchKey) r = true; } return r; }

/** *This method uses he LINEAR SEARCH algorithm to determine if an item is a member of an array. *This method returns true if searchKey is in a given array of Strings. */ public static boolean linearSearch(String[] array, String searchKey){ boolean r=false; for (int index=0; index < array.length && r==false; index++){ if (array[index].equalsIgnoreCase(searchKey)) r = true; } return r; }

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

/** *This method uses he LINEAR SEARCH algorithm to determine if an item is a member of an array. *The method returns the index of the cell that has the first occurrence * of a searchKey in a given array of int. The method returns -1 if the searchKey *is not in the array */ public static int searchList(int[] array, int searchKey){ int r=-1; for (int index=0; index < array.length && r==-1; index++){ if (array[index] == searchKey) r = index; } return r; } /** *This method returns a copy of a given array of integers. *(Something to think about: Is there a need to copy arrays? What is side-effect? */ public static int[] copyArray(int[] array1){ int[] copied= new int[array1.length]; for (int index=0; index< array1.length; index++){ copied[index] = array1[index]; } return copied; }

/** *This method implements the Balloon Sort algorithm *This method sorts a given array of int following the ascending order **/ public static void balloonSortArray(int[] given){ for (int x=0; x < given.length-1; x++){ for (int y=x+1; y<given.length; y++){ if (given[x] > given[y] ) { int temp = given[x]; given[x] = given[y]; given[y] = temp; } // end of if } // end of second for } // end of first for } // end of method

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

/** *This method implements the Balloon Sort algorithm *This method sorts a given array of String following the lexicographic order. */ public static void balloonSortArray(String[] given){ for (int x=0; x < given.length-1; x++){ for (int y=x+1; y<given.length; y++){ if (given[x].compareTo(given[y])> 0 ) { String temp = given[x]; given[x] = given[y]; given[y] = temp; } // end of if } // end of second for } // end of first for } // end of method /** *This method returns a copy of a given array of strings. *(Something to think about: Is there a need to copy arrays? What is side-effect? */ public static String[] copyArray(String[] array1){ String[] copied= new String[array1.length]; for (int index=0; index< array1.length; index++){ copied[index] = new String(array1[index]); } return copied; } /** *This method implements the Selection Sort algorithm *This method returns a sorted version of a given array of int following the ascending order.*/ public static int[] sortArray(int[] given){ int minIndex=0; int[] sorted= copyArray(given); int temp=0; for (int x=0; x < sorted.length-1; x++){ minIndex = x; for (int y=x+1; y<sorted.length; y++) if (sorted[minIndex] > sorted[y] ) minIndex = y; if (minIndex != x){ temp = sorted[x]; sorted[x] = sorted[minIndex]; sorted[minIndex] = temp; } } return sorted; }

School of Cimputing and Information Sciences (SCIS) Saint Louis University A. Bonifacio St., Baguio City, Philippines (074) 444-8246 loc 281

/** *This method implements the Selection Sort algorithm *This method returns a sorted version of a given array of Strings following lexicographic ordering*/ public static String[] sortArray(String[] given){ int minIndex=0; String[] sorted= copyArray(given); String temp=""; for (int x=0; x < sorted.length-1; x++){ minIndex = x; for (int y=x+1; y<sorted.length; y++) if (sorted[y].compareToIgnoreCase(sorted[minIndex])<0 ) minIndex = y; if (minIndex != x){ temp = sorted[x]; sorted[x] = sorted[minIndex]; sorted[minIndex] = temp; } } return sorted; } /** *This method implements the Binary Search algorithm. *Assuming that grades is a sorted array following an increasing order, this methods *returns true if key is in the array.*/ public static boolean bSearch(int[] grades, int key){ boolean r = false; int lowLimit = 0; int upLimit = grades.length-1; int mid=(lowLimit+ upLimit)/2; while (lowLimit < upLimit && !r){ mid = (lowLimit + upLimit)/2; if (grades[mid] == key ) r = true; else if (grades[mid] < key ) lowLimit = mid +1; else upLimit = mid -1; } return r; } }// end class

S-ar putea să vă placă și