Progfunhandouts 2010
Progfunhandouts 2010
Progfunhandouts 2010
What is a Computer? A computer is an electronic device capable of performing complex computations in a short time. A computer is a fast electronic calculating machine that accepts input information, processes it according to a list of internally stored instructions called a program, and produces the resultant output information. A program is a set of instructions for a computer, telling it what to do or how to behave. Programming is the craft of implementing one or more interrelated abstract algorithms using a particular programming language to produce a concrete computer program. Components of a Computer 1. Hardware 2. Software Hardware Concepts Hardware consists of devices, like the computer itself, the monitor, keyboard, printer, mouse and speakers. The hardware processes the commands it receives from the software, and performs tasks or calculations. How does the computer work? How can a computer show pictures? How can it play sounds? Data representation is the conversion of images, letters and sounds to digital electrical signals. Here, a digital electrical signal refers to a combination or sequence of on and off signals. Most computers are digital, as opposed to analog, devices. A digital device works with discrete signals such as 0 and 1. Software Concepts What is software? Software is the name given to the programs that you install on the computer to perform certain types of activities. Software Basics Computer program (or program) an organized list of instructions that, when executed, causes the computer to behave in a predetermined manner. Without programs, computers are useless. Support module an auxiliary set of instructions used in conjunction with the main software program (example: dynamic link libraries). Data module contains data (not supplied by the user) necessary for the execution of certain tasks. Data vs. Software Sometimes the term software is used too loosely and could cause confusion. Before, the term software is always associated to all non-hardware components of a computer. However, modern definitions make it clear that all documents, spreadsheets and even downloaded materials from the net are now classified as data. Code Generation In computer science, the code generation is a compilation stage that outputs machine code in the target language.
Programming Fundamentals
Code can appear in a variety of forms. The code that a programmer writes is called source code. After it has been compiled, it is called object code. Code that is ready to run is called executable code or machine code. Initially, a programmer writes a program in a particular programming language. This form of the program is called the source program, or more generically, source code. Application Software vs. System Software Software is basically categorized into two: application software and system software. Application software are computer programs that are used to accomplish specific or specialized tasks for computer users such as creating and editing documents (word processing), making graphic presentations, or listening to mp3 music. System software are programs that control the basic operations of a computer system such as saving files in a storage device like a hard disk or floppy disk, printing files, accepting input from a keyboard or mouse, execute programs, etc. Software Development Life Cycle SDLC is a methodology that is typically used to develop, maintain and replace information systems for improving the quality of the software design and development process. Phases of SDLC Planning Phase This is the initial stage in the SDLC that has to be performed. This phase includes the information about the requirements for the proposed software. Also, this phase is known as the feasibility study phase. Analysis Phase This phase requires the analyst to thoroughly study the current procedures or software used to execute tasks in an organization. The main goal in this phase is to identify the requirements for new software or simply change several aspects in the current working software. The activities performed by the analyst during this phase are: Study the current software Determine software requirements Write requirements reports Design Phase During this phase, the developer of the software translates the result of the previous phase into actual design or specifications of the software. Development of the software involves covering the input and output screens to reports, databases, and computer process. The activities performed in this phase are: Identify potential solutions Evaluate solutions and select the best Select hardware and software Develop application specifications Obtain approval to implement the new software Implement Phase After the design phase, we must put the proposed software into the test. During this phase, implementing the software will include several steps: 1. Coding creation of the actual program 2
Programming Fundamentals
2. Testing both programmer and analyst submits the software to various quality testing to discover if there are any bugs within software 3. Installation after coding and testing is done, the actual software must be installed and slowly or completely replaces the old software
Maintenance Phase With every phase being completed, perhaps the maintenance phase would be the most prevalent phase of all. There are some bugs in the software which cant be properly identified without putting the software into actual use. The maintenance phase is used to make necessary patches to remove found errors. This is where the software is systematically repaired and improved based on errors or possible new requirements found. Waterfall SDLC The waterfall SDLC suggests that prior to proceeding to the next phase; the current phase should be finished first. But applying this strategy in the real world would be unfeasible since it would be impossible to modularize system development. Modified waterfall and iterative SDLC This version of the SDLC is more flexible compared to the traditional SDLC model. Since the nature of developing software is unpredictable, using this model will allow the developer to adjust to certain situations (example: unforeseen requirements or additional features that are highly needed in the software. Programming Cycle Below are the steps in coming up with a program: 1. Problem definition specifies what we want for the computer to do. 2. Problem analysis looking at the problem itself; point of view of the computer; start with the input/output. 3. Algorithm development this is an outline that breaks problem down into segments, strategy on how to do the task. 4. Coding and debugging remove errors. Algorithm An algorithm is a finite set of well-defined instructions for accomplishing a task which, given an initial state, will result in a corresponding recognizable end-state. For example, a recipe for baking a cake is an algorithm.
Characteristics of an algorithm: Specify each step or instructor exactly There must be no ambiguity or the instructions must be clear. There must be a finite number of steps The algorithm must terminate and should have a stopping point. 3
Programming Fundamentals
There must be an output The algorithm must produce the correct result. Flowchart A flow chart is a graphical representation of a sequence of operations. The following are the elements of a flowchart: Flow lines indicated by directed lines to show the direction of data/control flow. The arrowhead is sometimes not shown when the direction of flow is clear. Flow lines are used to connect blocks by exiting from one and entering another.
Terminal block Ovals or rounded rectangles are used to indicate the start and end of a module or a program. An oval is labeled with the name of the module at the start. The end is indicated by the word end or stop for the top or Control Module. A start has no flow lines entering it and only one exiting it. On the other hand, an end or exit has one flow line entering it but none exiting it.
Initialization block The hexagon is used for declaring / initializing variables. Take note: You can only use variables that had been initialized. An initialization box has one entrance and one exit.
Process block The rectangle indicates a processing block, such things as calculations, opening and closing files, and so forth. A processing block has one entrance and one exit.
Input/Output block The parallelogram indicates general input and output operations. An I/O blocks has one entrance and only one exit.
Decision block The diamond indicates a decision. It has one entrance and exactly two exits from the block.
Connector Circles are used for in-page connectors labeled with uppercase letters while pentagons are used for off-page connectors labeled with uppercase letters and a number (typically the page number of the matching pair). The circle is used as a connection point between two sections of a flowchart that are not adjacent or closely located to each other.
Programming Fundamentals
Things to know first: Variable is a container of value, it may contain 1 value at a given time. A variable name must describe its content. Example num1 = 10 name = lynssynuj letter = L Use keywords Get, Input or Read for input block Use keywords Display or Print for the output block
Sample Flowchart Sequence 1. Create a flowchart that will display your age 5 years from now.
Start
age= 18
age=age+5
Display age
End
Programming Fundamentals
2. Create a flowchart that displays the users name, address, age, birthday, gender and phone number which will follow the sample output below. Name: Jun Rementilla Start Birthday: April 9, 1984 Age: 25 Gender: Male name, bday, age, Address: Tagaytay City addr, gen, phone Contact No.: 09166254527
Input name, bday, age, addr,gen, phone
Display Name: name Birthday: bday Age: age Gender: gen Address addr Contact No.: phone
End
Exercises: 1. 2. 3. 4. Input 2 numbers and get the sum, difference, product and quotient. Find the area of a rectangle. Find the area of a circle. Find the circumference of a circle.
Conditional Statements Conditions are statements that result in a Boolean value. A Boolean Value is either a TRUE or FALSE. Two types of operators result in Boolean Values: 1. Logical Operators these are mainly used to control program flow. They are usually part of an IF, WHILE, or some other control statements. The concept of logical operators is to allow a program to make a decision based on multiple conditions. 2. Relational operators used to compare two operands and determine the validity of a relationship.
Programming Fundamentals
The NOT truth table shows the nature of the NOT operator. A truth table is a type of mathematical table used in logic to determine whether an expression is true or valid. Such a table typically contains several rows and columns, with the top row representing the logical variables and combinations, in increasing complexity leading up to the final function. The NOT operator operates on a single value and the result is the reverse of the operand Boolean value.
Condition A F T !A T F
The AND operator is used if you want a strict condition. For AND to have true result, both conditions must be satisfied. For AND to have true result, both conditions must be satisfied. The OR operator is used when either one of the condition is true.
Condition a F F T T Condition b F T F T a AND b F F F T a OR b F T T T
Conditional Statements Relational operators compare two values and return a Boolean value depending on whether the test condition is true or false. In other programming languages, these are the symbols used for relational operators. Assume you have variable x and y. x<y test if x is less than y x>y test if x is greater than y x <= y test if x is less than OR equal to y x >= y test if x is greater than OR equal to y x==y test if x is equal to y x != y test if x is not equal to y x <> - test if x is not equal to y Note: Do not be confuse with = = (equal) and = (assignment). The first one determines if a variable has the same value as another variable, but the second makes a variable become some value. Conditional Statements: Exercises 2 Assume that you have variable X and Y. What would be the results of the conditions if we were to compare them with different values and different relational operators?
X 5 18 2 30 Y 17 4 12 31 X<Y T F F T X>Y X<=Y X>=Y X= =Y X!=Y
Conditional Statements More on Decision Box We said that the diamond box is used for decision making within your flowchart. 7
Programming Fundamentals
It should be noted that what you place inside the diamond box are conditions. Conditions that either results to TRUE or FALSE. Note: You dont place conditions that are in essay form, you must be able to represent it in a mathematical form.
Is
x< 20
Single Alternative Selection Structure A decision box may not necessarily have to do something for both the TRUE path and the FALSE path.
Dual Alternative Selection Structure The dual alternative structure allows you to perform two different tasks depending on the result of the conditions evaluation. One path is performed if the evaluation resulted in true and the other if it is false. Example: if x < y, print x, otherwise print y F T
Conditional Statements: Exercises 3 1. Draw a flowchart that will ask the user to input the values of four variables, A, B, C, and D and print TRUE if A is greater than B and C is less than D. Otherwise do nothing. 8
Programming Fundamentals
Start
A, B, C, D
Input A, B, C, D
T
A>B and C<D
2. Draw a flowchart that will ask the user to enter a character (either M or F) to indicate the users gender (Male or Female). Display Male if the user enters the value of M and Female for the value of F. (Assume all the inputs are correct.)
Start
gen
F
Outpu t FEMAL E
Input gen
T
Outpu t MALE
gen == M
End
Programming Fundamentals
Exercises: 1. Accept persons name and age then determine if he/she is old enough to vote. 2. Create a flow chart that will increase the value of the number by 5 if it is greater than 10 and display the result, otherwise do nothing. 3. Draw a flow chart for college admission office. Allow the user to input the students GWA from high school and Admission test score. Print message Accept if the student has a GWA of 80 or above and admission test of at least 60. If the student doesnt meet either of the qualification criteria, print Reject. 4. Create a flow chart that will increase the value of the number by 10 if it is less than 20 and display the result. Otherwise increase the value of the number by 20 and display the result. Multiple Decision Boxes Multiple decision boxes can oftentimes be combined into a single box. There are times, however, when you have to be very specific with the conditions that you have to put in. This is especially true in cases when different actions need to be performed depending on various conditions. Example: Create a flowchart that asks the user to enter a number from 1 3. If 1 is entered, print Hello, if 2 is entered, print Hi, and if 3 is entered, then print Bye. Otherwise, print Invalid. Start
x=0
Get x
x==1 ?
Disp Hello
x==2 ?
Disp Hi
Stop
x==3 ?
Disp Bye
Disp Invalid 10
Programming Fundamentals
Using Decision Box with Ranges Business programs often need to make selections based on a variable falling within a range of values. To perform a range check, use a sequence of decision blocks starting with either the lowest or highest value in each range of values to make your selections. Example: Create a flowchart that would print the name of the supervisor under a certain department number. Department Number 13 47 89 1st Solution Start Supervisor Mr. X Mr. Y Mr. Z
Dept-0
Get Dept
Dept <=3?
Dept <=7?
Disp Mr. Y
Stop
Disp Mr. Z
2nd Solution 11
Programming Fundamentals
Start
Dept-0
Get Dept
Dept >=8?
Dept >=4?
Stop
Exercise: Draw a flowchart that will print the students letter grade given the following specifications: 90 100 80 89 70 79 60 69 Below 60 = A = = = F
B C D
Looping Constructors
12
Programming Fundamentals
A loop is a set of program instructions that executes repeatedly until a condition is satisfied. The chart shows the basics of looping. It tells the nature of loop and how it works.
+*-/ %
Condition al
Variabl e
User Input
Stop
Fals e
Initializatio n
Example: 5 < 8 will always be true; however, using x < 8 the result will be dependent on the value of x. In programming, the value of the variable can be changed in 3 basic ways: 1. through mathematical computations (ex: Set x to x + 3 or Increment x by 3) 2. user input (enter x) 3. by initialization or passing of values (ex: x = 4, y = x) Repetition Structure Also referred to as a loop or iteration, this type of structure repeats one or more instructions until a certain condition is met. The action performed by a repetition structure must eventually cause the loop to terminate. Otherwise, an infinite loop is created.
X< Y? No
Yes
Process A
X< Y?
13
Programming Fundamentals
Yes No
Display X
This type of structure is known as a pre test repetition structure. The condition is tested BEFORE any actions are performed
X< Y?
Display X
X=X+ 1
A post-test repetition structure always performs its actions at least once. The condition is tested AFTER the actions are performed.
No
Looping Constructs: Example 1 Creating a flowchart that will display the following result: (Assume that the variable is initialized to 5.) Output: 5 4 3 2 1 Done Start
x =5 14
Programming Fundamentals
Yes
Display X
X=X-1
Create a flowchart that will print a series of numbers based on what was entered by the user. Number Entered: 4 Sample Output: 1 2 3 4 Done Start X=0 , Y Get Y
X=X+ 1
Disp X
Stop SUM, 3 Looping Constructs: Example CTR print the sum of all even numbers from 1 10. Create a flowchart that will = 0 CTR < 10? Disp SUM Stop CTR = CTR + 2 15 SUM = SUM + CTR
Programming Fundamentals
Yes no No
Exercises: 1. Create a flowchart that will print the sum of all odd numbers from 1 10. 2. Create a flowchart that will print your name 5 times. Looping Construct Multiple Loops It is possible to have a loop. In case of multiple loops, it is critical to determine what condition will terminate the whole flowchart. Multiple loops are useful if there is a need to perform repetitive tasks. Start Gen, Ctr = 1 Ctr <= 5
Stop
Get Gen
Disp Invalid
Gen == M Or One use of multiple loops is when there is a need to perform user input validations. For Gen == F except 0 or a negative number. example, suppose you will let the user enter a number
Example: Create a flowchart that asks the user to enter a gender. Determine if the user presses either Gen== M or F, if M display MALE, or if F display FEMALE. Otherwise, display Invalid M Gender and let the user reenter a gender. Repeat the whole process 5 times.
Disp Male Disp Female
16 Ctr = Ctr+1
Programming Fundamentals
Pseudocodes - Is a kind of structured English for describing algorithms. It allows the designer to focus on the logic of the algorithm without being distracted by details of language syntax. - is a short hand way of describing a computer program. Rather than use the specific syntax of a computer language, more general wording is used. Common Action Keywords Input: Read, Obtain, Get 17
Programming Fundamentals
Output: Compute: Initialize: Add one: Subtract: Print, Display, Show Computer, Calculate, Determine Set, Init Increment Decrement
The structured part of pseudocde is a notation for representing six specific structured programming constructs: A. SEQUENCE a linear progression where one task is performed sequentially after another. Sample problem 1: Create a pseudocde that will display your age 5 years from now. 1st Pseudocode Init age=18 Compute age as age plus 5 Display age 2nd Pseudocode read age Compute age as age plus 5 Display age
Sample problem 2: Create a flowchart that displays the users name, address, age, birthday, gender and phone number which will follow the sample output below. Name: Jun Rementilla Birthday: April 9, 1984 Age: 25 Gender: Male Address: Tagaytay City Contact No.: 09166254527 Pseudocode: Input name, addr, bday, age, gen, phone Display Name: name Birthday: bday Age: age Gender: gen Address: addr Contact No.: phone B. IF THEN ELSE is a decision (selection) in which a choice is made between two alternative course of action. Binary choice on a given Boolean condition is indicated by the use of four keywords: IF, THEN, ELSE and ENDI F. The general form is: IF (condition) THEN Sequence1 ELSE Sequence 2 18
Programming Fundamentals
END IF The ELSE keyword and sequence 2 are optional. If the condition is true, sequence 1 is performed, otherwise sequence 2 is performed. Sample Problem 1: Create a pseudocode that will ask the user to input the values of four variables, A, B, C, and D and print TRUE if A is greater than B and C is less than D. Otherwise do nothing. Pseudocode: Input a, b c, d If a is greater than B and C is less than D Then Display TRUE End If Sample Problem 2: Create a pseudocode that will ask the user to enter a character (either M or F) to indicate the users gender (Male or Female). Display Male if the user enters the value of M and Female for the value of F. (Assume all the inputs are correct.) Pseudocode: Input gen If gen is equal to M Then Display Male Else Display Female End If C. CASE is a multi-way branch (decision) based on the value of an expression. CASE is a generalization of IF-THEN-ELSE. A CASE construct indicates a multi-way branch based on conditions that are mutually exclusive. Four keywords, CASE, OF, OTHERS, and ENDCASE, and conditions are used to indicate various alternatives. The general form is: CASE expression OF condition 1: sequence 1 condition 2: sequence 2 condition n: sequence n OTHERS: default sequence ENDCASE The OTHERS clause is its default sequence is optional. Conditions are normally numbers or characters indicating the value of expression, but they can be English statements or some other notation that specifies the condition under which the given sequence is to be performed. A certain sequence maybe associated with more than one condition.
19
Programming Fundamentals
Sample Problem1: Create a pseudocode that asks the user to enter a number from 1 3. If 1 is entered, print Hello, if 2 is entered, print Hi, and if 3 is entered, then print Bye. Otherwise, print Invalid. Pseudocode: Enter num Case num Of 1: Print Hello 2: Print Hi 3: Print Bye Others Print Invalid number End Case Sample problem 2: Create a pseudocode that accept letter grade and display the corresponding remarks below. A = Excellent C = Satisfactory B = Good D = Poor Pseudocode: Input grade Case grade Of A: Display Excellent B: Display Good C: Display Satisfactory D: Display Poor End Case D. WHILE is a loop (repetition) with a simple conditional test at its beginning. The WHILE construct is used to specify a loop with a test at the top. The beginning and the ending of the loop are indicated by two keywords WHILE and ENDWHILE. The general form is : WHILE (condition) Sequence1 Sequence2 .. Sequence n ENDWHILE The loop is entered only if the condition is true. The sequence is performed for each iteration. At the conclusion of each iteration, the condition is evaluated and the loop continues as long as the condition is true.
Sample Problem1: Create a pseudocode that asks the user to enter 10 numbers then display the sum. Pseudocode: Set sum to 0 20
Programming Fundamentals
Set ctr to 0 While ctr <= 10 Input num Compute sum as sum plus num Increment ctr End While Display sum Sample problem 2: Create a pseudocode that asks the user to enter 10 numbers then display the average. Pseudocode: Set sum to 0 Set ctr to 0 While num <= 10 Input num Compute sum as sum plus num Increment ctr End While Compute average as sum divided by ctr Display average E. REPEAT-UNTIL is a loop with a simple conditional test at the bottom. This loop is similar to the WHILE loop except that the test is performed at the bottom of the loop instead of at the top. Two keyword, REPEAT and UNTIL are used. The general form is : REPEAT Sequence 1 Sequence 2 .. Sequence n UNTIL (condition) The sequence in this type of loop is always performed at least once, because the test is performed after the sequence is executed. At the conclusion of the loop repeats if the condition is false. The loop terminates when the condition become true Sample Problem1: Create a pseudocode that asks the user to enter 10 numbers then display the sum. Pseudocode: Set sum to 0 Set ctr to 1 Repeat Input num Compute sum as sum plus num Increment ctr Until (num > 10) 21
Programming Fundamentals
Display sum Sample problem 2: Create a pseudocode that asks the user to enter 10 numbers then display the average. Pseudocode: Set sum to 0 Set ctr to 1 Repeat Input num Compute sum as sum plus num Increment ctr Until (num >10) Compute average as sum divided by ctr Display average F. FOR is a specialized construct for iterating a specific number of times, often called a counting loop. Two keywords, FOR and ENDFOR are used. The general form is: FOR (iteration bounds) Sequence 1 Sequence 2 .. Sequence n ENDFOR Sample Problem1: Create a pseudocode that asks the user to enter 10 numbers then display the sum. Pseudocode: Set sum to 0 For (ctr starts counting from 1 to 10) Input num Compute sum as sum plus num Increment ctr End For Display sum Sample problem 2: Create a pseudocode that asks the user to enter 10 numbers then display the average. Pseudocode: Set sum to 0 For (crt starts counting from 1 to 10) Input num Compute sum as sum plus num 22
Programming Fundamentals
Increment ctr End For Compute average as sum divided by ctr Display average G. NESTED CONSTRUCTS The construct can be embedded within each other, and this is made clear by use of indenting. Nested constructs should be clearly indented from their surrounding constructs. Example SET total to zero REPEAT READ Temperature IF Temperature > Freezing THEN INCREMENT total END IF UNTIL Temperature < zero Print total In the above example, the IF construct is nested within the REPEAT construct, and therefore is indented.
Sample Problem1: Create a pseudocode that asks the user to enter 10 numbers, if the number is greater than 30 compute the sum otherwise compute the product then display the sum and product. Pseudocode: Set ctr to 1 Set sum to 0 Set product to 0 Repeat Input num If (num> 30) Compute sum is equal to sum plus num Else Compute product is equal to product times num Until(crt>10) Display The sum is: sum Display The product is: product
23
Programming Fundamentals
What is Java? A high-level programming language developed by Sun Microsystems. Java was originally called OAK, and was designed for handheld devices and set-top boxes. Java is an object-oriented language similar to C++, but simplified to eliminate language features that cause common programming errors. Java is a general purpose programming language with a number of features that make the language well suited for use on the World Wide Web. Applets and Applications There are two kinds of programs you can write with the Java language and these are: Java Applets. Java applets are small programs that the travel with HTML code and execute on the Web users computer. Java Applications. Java applications are complete stand-alone programs that do not require another application to execute.
Java Program Cycle Java source code files (files with a .java extension) are compiled into a format called bytecode (files with a .class extension), which can then be executed by a Java interpreter. Compiled Java code can run on most computers because Java interpreters and runtime environments, known as Java Virtual Machines (VMs), exist for most operating systems, including UNIX, the Macintosh OS, and Windows. Bytecode can also be converted directly into machine language instructions by a just-in-time compiler (JIT). Java Program A minimum Java program has the following format: public class <class name> { public static void main (String[]args) { <program statement> } } 24
Programming Fundamentals
In this course, we are interested in the basic programming so the students need not understand the meaning of each declaration. Just note that: 1. The items in angle brackets are placeholders. These must be replaced with whatever is appropriate for the program (without the angle brackets). a. The <class name> is an identifier for the program which should be the same as the file name. Rules for identifiers will be discussed later. b. The <program statement> is a series of Java statements to be discussed later. 2. There is the minimum of 2 pairs of curly braces one after <class name> surrounding everything else, and another surrounding the <program statements>. 3. args are available which maybe renamed according to Java rules on variables name. At this point, just use it as is. Java Conditioning Guidelines Below are the guidelines to be followed when coding in Java: 1. Java program files must Have same name as public class End with extension.java 2. Use with comments for documentation and readability 3. Whites spaces are ignored 4. Indent for readability Java Statements A statement specifies one or more actions to be performed during the execution of a program. In Java, a statement is one or more lines of code terminated by a semicolon. For example: System.out.print( Hello, World! ); Java Blocks In Java, statements can be combined to form a statement block. A block is formed by enclosing statements by curly braces. Java Comments Comments are used to add notes and documentation to source codes. Everything marked as comment is ignored by the compiler. There are three types of comments in Java block, end-of-line, and JavaDoc comments. 1. A block comments is used to provide descriptions of files, methods, data structures and algorithms. It starts with a forward slash and asterisk (/*) and ends with an asterisk and forward slash (*/). 2. A line comment starts with two forward slashes (//) and ends at the end of the line the slashes appear on. 3. A JavaDoc comment is used specifically to document classes, attributes, and methods. It starts with a forward slash and two asterisk (/**). It ends with one asterisk and a forward slash (*/). Note that the JavaDoc comment is just a special case of the block comment and can be used even if you do not intend to use JavaDoc.
25
Programming Fundamentals
Java Identifiers Identifiers are the words that are used by the programmer to properly identify or name a class, procedure, method, or variables. Java Identifier Rules and Guidelines The following are some rules and guidelines on how to name an identifier: Rules: Identifiers can use alphabetic characters, both lower and upper case (a-z and AZ), numbers (0-9), underscores (_), and dollar signs ($). Identifiers cannot start with a number. Keywords cannot be used as Identifiers (for reason keywords are sometimes called reserved words). Guidelines: Name your Identifier close its functionality. Method and variable names start in lowercase while classes start in uppercase. For multi-word identifiers, either use underscores to separate the words, capitalize the start of each words. Avoid starting the identifiers using the underscore. Java Keywords A keyword is a fixed set of symbols built into the syntax of the language. Since java is case-sensitive, changing the case of the keyword will allow its use an identifier. Sample keywords: class public void main int for while new Data Types Data types represent different set of data values and determine which standard operators can be applied. There are two kinds of data types: 1. Simple data types are the built-in or primitive Java data types. Primitive data types: Boolean( boolean) Short (short) Byte (byte) Integer (int) Long (long) Character (char) Double (double) Floating Point (float) 2. Composite or class data types are created by the programmer using simple types, arrays, classes and interfaces. Sample of Predefined Composite Data type toUpperCase( ) toLowerCase( ) String length( ) equals( )
26
Programming Fundamentals
Primitive Data Types Primitive data types are the building blocks and are in essential part of a program. 1. Boolean Data type - Javas Boolean data type is one-bit wide and takes on the values true or false. The initial value of a Boolean variable is false. 2. Character Data type- Java uses a 16-bit data type called char to represent text characters. 3. Integer Data type- The integer types are for numbers without fractional parts. Negative values are allowed. Java provides the four integer types int type is the most practical, for greater number of digits you need to resort to a long. The byte and short are mainly intended for specialized applications, such as low-level file handling. 4. Floating Point - Another type of number that can be stored is a floating-point number, which has the type float or double. Floating-point numbers are numbers with a decimal point. The name double refers to the fact that these numbers have twice the precision of the float type. Java Variables Variables are places in memory that store values that are generated in a program. Declaring and Initializing Variables In Java, variables are declared via statements of the form <data type> <name> =nitial value-; Example: int yourAge = 19; In the given example, the variable yourAge is declared and at the same given an initial value of 19. Below are the guidelines in initializing variables: 1. initialize your variables as you declare them if needed. 2. Use descriptive names for your variables. 3. Declare one variable per line of code. Displaying Variable Data In Java, we can output the value of a variable using the following commands: System.out.print( ) System.out.println( ) The given example illustrates how these two commands are used in a program. public class VarOutput { public static void main (String[] args){ int value = 10; char - x; x =A ; System.out.println(value); Syatem.out.println( the value of x = + x); 27
Programming Fundamentals
} } The program will output the following text on the screen: 10 The value of x = A Types of Variables There are two types of variables in Java and these are: 1. Primitive Data Variables these variables store data in the actual memory location of where the variable is. Example--: int i = 20 int j = 15; 2. Reference variables are variables that store the address in the memory location. A variable that does not have the value with it , but it refers to another variable for the values . Example--: int i,j; i=15; j=i; If you are using the object j in a class and accessing a file from another class then you have to take the help of the DOT(.) operator.... Here "j" is the reference variable and i is the value variable. Constants Constants are refer to those whose value does not change. The keyword final is used to modify a variable declaration to declare a constant . For Example,
public class Variables { public static void main (String[] args) { final double PI 3.14; } }
Type Casting We have data types such as int,float ,char,double. int*int gives int only. similarly float*float gives float only. But in some cases for example (in divison) 4/3 gives float .But 4 and 3 are integers. In such cases we have to change data type of ints temporarily as floats. This temporary conversions of one data type to another is called type casting. Casting means changing. Type casting gives the meaning of changing the data type. int donutCount, milkCount; double donutsPerGlass; System.out.print("Enter number of donuts: "); donutCount=Integer.parseInt(k.readLine()); System.out.print("Enter number of glasses of milk: "); 28
Programming Fundamentals
milkCount=Integer.parseInt(k.readLine()); if(milkCount< 1){ System.out.println("No Milk!"); System.out.println("Go buy some milk"); } else{ donutsPerGlass=donutCount/(double)milkCount; System.out.println(donutCount+ " donuts."); System.out.println(milkCount+" glasses of milk"); System.out.println("You have "+ donutsPerGlass+" donuts for each glass of milk."); } Java Expressions An expression produces a result and returns a value. The following are the purposes of expressions: to compute values to assign values to variables to control the flow of execution Below are common examples of mathematical expressions:
x = 5; y = x; z = x * y;
Java Operators Operators are special symbols that perform some action on its operands and return the result. Arithmetic Increment and Decrement Assignment Relational Logical
Assignment Operators The simplest assignment operator is the standard equals (=) sign operator. For example, x = y+3 evaluates the expression y+3 and assigns the result to x.
29
Programming Fundamentals
The other Java assignment operators are known as arithmetic assignment operators.
+= -= *= /= %=
Add and assign operator Subtract and assign operator Multiply and design operator Divide and assign operator Remainder and assign operator
Increment and Decrement Operators The + + operator increments its single operand, which must be a variable, by one. The behavior of this operator depends on its position relative to the operand. The - - operator decrements its single numeric operand, which must be a variable by one. The behavior of this operator depends on its position relative to the operand. Relational Operators Relational operators are used to create comparison expressions that result in a Boolean value (either true or false). Java provides the following six relational operators. = = is equal to < is less than > is greater than < = is less than or equal to > = is greater than or equal to != is not equal to
Logical Operators Expressions that result in Boolean values, such as comparison operations, can be combined to form one or more complex expressions. This is handled through logical operators, which are used for logical combinations AND, OR, XOR, and logical NOT. For AND combinations the & or && logical operators are used. For OR combinations, the | or || logical operators are used. These combined expressions return a true value if either Boolean expression is true. The XOR combination has one logical operator.^. This result in a true value only if both Boolean expressions it combines have opposite values . The NOT combination uses the ! logical operator followed by a single expression.
30
Programming Fundamentals
Operator Precedence When more than one operator used in an expression, Java has an established precedence hierarchy to determine the order in which operators are evaluated. Java Statements Statements are the tasks you wish your program to do. Statements are your commands and may be comprised of keywords, Identifiers, and /or mathematical expressions. It generally contains expressions (expressions have a value). Statements in Java can either be simple statement or compound statements. Simple statements are the basic building blocks of a program. Compound statements are used to organize simple statements into complex structures, which are called control structures since they control the order in which the statements are executed. Java Control Structures Control structures allow a programmer to change the ordering of how the statements in programs are executed. There are two types of control structures and these are: Decision control structures allows a programmer to select specific sections of code to be executed. Repetition control structures allows a programmer to execute specific sections of the code a number of times. Decision Control Structures These structures include types such as If, If-Else, and If-Else-if. If Structure The If statement specifies that a statement (or block of code) will be executed if and only if a certain Boolean statement is true. It has the format :
if OR if (expression) statement; (expressions) grammar statement or block;
If there is a need to execute several statements (compound statement).then left right { } braces can group these statements .
If (expression) { statement 1; statement 2; }
31
Programming Fundamentals
If- Else Structure The if-else statement is used when you want to execute statement/s if a condition is true and another statement if the condition is false. It has the format:
if else statement 2, or if (expression) statement 1; else statement2; (expressions) statement1;
Exercises: Let the students to perform the following exercises after discussing the If-Else Structure. 1. Test if the value of the variable count is greater than 10. If it is, print Count is greater than 10 , otherwise, print Count is less than 10 . 2. Test if the value of the variable number is an odd number . If it is, print This number is not an even number ,otherwise print This number is an odd number . 3. Test if the value of the variable age is greater than 18, and less than or equal to 40. If it is, print Youre not getting old! otherwise, print Youre not getting younger .
If- Else-If Structure The if-else if statement is used when you want to execute statement/s if a condition is true and test another condition if the previous condition is false. It has the format:
if (expressions) statement1; else if (expression) statement 2; else if (expression) statement 3; . . . else statement2;
32
Programming Fundamentals
Switch Structure Another way you can add decision-making code to your programs is with the switch statement. The switch statement enables a computer program to switch between different outcomes based on a given expressions. The general format of Switch statement is:
switch { (switch_expression) case 1: statement1; case2: statement 2; case n: statementn; default: }
switch {
(switch_expression) case 1: statement1; break; case2: statement 2; break; case n: statementn; break; default:
Everytime you encounter a switch statement, 1. Java first evaluates the switch_expressions, and jumps to the case whose selector maches 2. 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. 3. If none of the cases are satisfied, the default block is executed. However, note that the default part is optional. Take note of the following in a switch statement: 33
Programming Fundamentals
Unlike with the If statement, the multiple statements are executed in the switch statement without needing the curly braces. When the case in a switch statement has been matched, all the statements associated with that case are executed. Not only that, the statements associated with the succeeding cases are also executed. To prevent the program from executing statements in the subsequent cases, use a break statement as the last statement.
Repetition Control Structures Repetition control structures are Java statements that allow a programmer to execute the specific blocks of code a number of times. These structure include types such as WHILE, DO-WHILE and FOR.
While Structure The while loop is a statement or block of statements that is repeated as long as some condition is satisfied. Depending on the Boolean expression, the loop may not be executed at all. The general format of a while statement is :
while (boolean_expression) { statement1; statement2; }
Do-While Structure A do-while loop is similar in structure to a while-loop, except in its upside-down appearance, as the condition appears after the body. The statements inside a do-while loop are executed repeatedly as long as the condition is satisfied. The general format of a do-while statement is: do { Statement1; Statement2; 34
Programming Fundamentals
} while (boolean_expression); For Structure A for loop instructs a program to perform a block of code a specified number of times. There are many applications for a for loop, including tasks such as reading through a list of data items or initializing an array. The general format of a for statement is: for { (initialization; condition; increment)] Statement 1; Statement 2; } The for construct has three parts: the initialization section, condition section, and the increment section. The initialization section is used to initialize the loop variable. The condition section compares the loop variable to some limit value. The increment section updates the loop variable.
Arrays Programming languages provide the capability to use one variable to store a list of data of the same type, and manipulate these more efficiently. This type of variable is called an array. A data structure is a way of storing data in a computer so that it can be used efficiently. An array is a sequence of memory locations for storing data organized in such a way that any one of the individual locations can be accessed by providing its index number. In Java, the index number starts at zero. The individual items within an array are called elements. The elements are referenced by their index using the subscript operator [ ]. For example Index: 0 1 2 number : 1 2 3 Declaring Java Arrays An array variable is declared the same way that any Java variable is declared. The declaration of an array in Java simply allocates memory to contain a reference to the array. Square brackets [ ] are used to modify the variable declaration. The square brackets may also be attached to the variable to declare that the variable is an array variable, as in For example int x [ ]; 35
Programming Fundamentals
int ages [ ] ; Or Equivalent ly int [ ] x; int [ ] ages; You cant store different data types in a single array. You can have an array of integers, or an array of strings, or an array of arrays, but you cant have an array that contains, for example, both string and integers. Initializing Array Variables Once an array variable has been declared, memory must then be allocated or assigned to it before data can be stored in the array. This is done by initializing the array variable using the operator. The new operator is followed by the data type with the number of elements to allocate specified. The number of elements to be allocated is placed within the [ ]. For example name = new String [100]; age = new int [ 10] This, in effect, creates the array for data storage. Note that the array is different from the array variable . The array stores the data while the array variable identifies the array. Like other variables, an array variable can be initialized when it is declared. Element Type [ ] arrayName = new Element Type [Size Of Array]; OR Element Type arrayName[ ] = new Element Type [Size Of Array]; For example int [ ] x = new int [ 10 ] int [ ] ages = new int [ 100]; You can also create an array by directly initializing it with data. In this case, the data should be enclosed in curly braces and separated by commas. The length of the array is simplicity defined by the number of elements included within the { }. For example int [ ] arr = {1, 2, 3, 4, 5}; Or int arr [ ] = {1, 2, 3, 4, 5}; This statement declares and creates an array of integers with five elements, and initializes this with the values 1, 2, 3, 4 and 5. Once the array is created, you cannot make more space in the array The following are examples of creating arrays. 1. Creates an array of boolean variables with identifier results. This array contains 4 elements that initialized to values {true, false, true, false}. Boolean [ ] results = {true, false , true , false}; 2. Creates an array of 4 double variables initialized to the values {100, 90, 80,75.5}. 36
Programming Fundamentals
doouble [] grades = {100, 90, 80, 75.5}; 3. Creates an array of strings with identifier days and initialized. This array contains 7 elements. String [] days = {Mon, Tue, Wed, Thu, Fri, Sat, Sun}; Accessing an Array Element You can access the elements of a Java array by treating it as a one argument function, where the argument is the index or subscript.
Index number or subscript Assigned to each member of the array, to allow the program to access an individual member of the array An integer beginning at zero and progresses sequentially to the end of the end of the array Note: index is from 0 (sizeOfArray-1) For example, given the array we declared, we have //assigns 10 to the first element in the array ages [0] = 10; //print the last element in the array System.out.print (ages[99]); Once an array is declared, the stored value of each member of the array will be initialized to zero for number data. Coding Guidelines It is better to create the array right after you declare it. int [ ] arr = new int [ 100] The elements of an n-element array have indexes from 0 to 1. Note that there is no array element arr[n]! This will result in an array-index-out-of-bounds exception. You cannot resize an array. However, you can create a new array of a different size, copy the desired data into the new array, and assign the new array to the array variable. Array Length When you create an array, you specify the number of elements. Subsequently, the array keeps this information. You can access the number of elements using the constant length attached to the arrayName by a dot, as in arrayName.length. for example, if you have an array called employeeNames, the following code sets an int called nEmployees to be equal to the length of the array:
37
Programming Fundamentals
nEmployees = employeesNames.length; The arrays length is permanently fixed at creation time, so you cant modify it. The following code would cause a compilation error: employeeName.length = 5000;
Sample Program 1:
import java.io.*; public class BasicArray{ public static void main (String[]args) throws IOException{ DataInputStream k=new DataInputStream (System.in); int index; String names[]={"Jun", "Jeff", "John", "Jessie", "Jet"}; for(index=0;index<names.length;index++) System.out.println(names[index]); System.out.println(); int sum=0; int num[]={100,200,300,400,500}; for(index=0;index<num.length;index++){ System.out.println(num[index]); sum= sum+num[index]; } System.out.println(" The total of the entered numbers is " +sum); System.out.println(); String days[]={"Mon","Tue","Wed","Thu","Fri"}; for(index=0;index<days.length;index++) System.out.println(days[index]);
System.out.println();
char vowels[]={'a','e','i','o','u'}; 38
Programming Fundamentals
} }
Output: Jun Jeff John Jessie Jet 100 200 300 400 500 The total of the entered numbers is 1500 Mon Tue Wed Thu Fri Sat Sun u, o, i, e, a, Sample Program 2:
import java.io.*; public class BasicArray2{ public static void main (String[]args) throws IOException{ DataInputStream k=new DataInputStream (System.in); System.out.println("Enter Temperatures"); int index; 39
Programming Fundamentals
double temperature[] = new double[6]; the following codes show how to input elements in an array and then display the element in a specific index*/ for(index=0;index<temperature.length;index++){ temperature[index]=Double.parseDouble(k.readLine()); } System.out.println(" The element in index 2 is "+temperature[2]);
/* *
} }
Sample Program 3:
import java.io.*; public class BasicArray2{ public static void main (String[]args) throws IOException{ DataInputStream k=new DataInputStream (System.in); System.out.println("Enter Temperatures"); int index; // the following lines of codes show how to input elements in an // array double temperature[] = new double[3]; for(index=0;index<3;index++){ temperature[index]=Double.parseDouble(k.readLine()); } // the following lines of codes show how to retrieve elements from // an array for(index=0;index<3;index++){ 40
Programming Fundamentals
System.out.println(" the element in index "+index+ " is "+temperature[index]); } } }
Sample Program 4:
import java.io.*; public class BasicArray2{ public static void main (String[]args) throws IOException{ DataInputStream k=new DataInputStream (System.in); System.out.println("Enter Temperatures"); int index; // // the following codes show how to input elements in an array and then display how may arrays were entered double temperature[] = new double[6]; for(index=0;index<temperature.length;index++){ temperature[index]=Double.parseDouble(k.readLine()); } System.out.println(" Total of "+temperature.length+" elements."); } }
Programming Fundamentals
95 78 92 The total number elements is 6.
42
Programming Fundamentals
Activity: Create a program having an array of double with an identifier point. Input 4 numbers then display the sum of 1st and 2nd elements then the sum of the 3rd and 4th elements. Sample Output: Enter numbers 2.1 2 3.1 3 The sum of elements in index 0 and 1 is 4.1 The sum of elements in index 2 and 3 is 6.1
43