0% found this document useful (0 votes)
26 views27 pages

ICS2602

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views27 pages

ICS2602

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

ICS2601-RM.

1805 him
Fortier1 : importance of

programming
Prof. Maria Lourdes L. Edang
Instructor:Asst.
PROGRAMMING
consultation Hours: TBA
-it is a tool to get solution by carefully,
pushing the repetitive tasks the
to

computer and thereby achieving automation


COURSETOPICS meanwhile still requiring input from

programmers/ software developers


IP RE IIDNI:
1) Importance of
programming
2.) Flowcharting andPseudocode
Programming is a process
Quiz 1 3 importantphases:
3.)Sequential Imperative Program

4)Data types 1) Problem identification and


5.) Strings solving phase
6)Methods
QUi2 2 2) Implementation phase
7.) Operators
8) Condition statements
Maintenance
3) phase

#DDNAD: Reasons Programming


1.) Looping constructs. Break, andcontinue
Quiz 3
is important:
2.) Arrays
3) Introduction to object Oriented programming Quiz 4 to interactwith machines and

(C + +) -
17 computer
·
To harness the power of computing
in all human endeavor
GRADING SYSTEM
·
To automate tasks
PRELIM GRADE
30%. Machine Problem ·
To create intelligentmachines
30% long quizzes
40% Prelims exam
Importantterms to remember
FINAL GRADE
1) Programming language
301. Machine Problem

30% long quizzes -use write computer


to
401 Prelims exam instructions
ICS2602 GRADE -

examples:Visual basic, C#, ct,


Java
prelim grade x. So final grade 1 so

2)Syntax
CONVERSION GRADE
OF TO 75%
-
rules governing its word usage
andpunctuation
25/40 ·

(grade 60) -

75
+

3) computer memory
passing rate is 75% -

Computer's temporary internal


storage
-

volatile

4) storage
permanent devices
- nonvolatile


understanding
Program Development
5) compiler/Interpreter cycle
-

translates program code into


machine language (binanguage)
-checks for syntax errors

4) program executes/runs
~

Inputwill be accepted i
-
some processing will occur,
andresults will be output

7) program with syntaxerrors


cannotbe executed

3) Logical Errors

Errors in programming logic


produce incorrect outputas a result
Understanding the Problem
-

mostdifficult
aspects
a) logic ofComputer program One ofthe of programming
-

Users/end users (people for whom program is written


documentation (supporting paperwork for program)
sequence ofspecific instructions
-

in specific order
Planning the logic
10) variable
-

heart
of the programming process
-mostcommon
planning tools
-Namedmemory location whose Flowchart
·

value can vary


·
pseudocode

Parough
-

X +

9
a program's logic
number
On
paper before you actually
write
the
program
variable Coding the program
addition
sign

Program Development
cycle
-understand the problem
-plan the logic
-

code the program


Use software (compiler/interpreter) to software to translate the
-using
-

a
translate the program into machine into machine
program language
language
Testt he
program SyntaxError
-

into production
Translator Program
-putthe program compiler/interpreter -
misuse a
of
language's
-
Maintain the program -changes the
programmer's grammar rules programmer
english-like high-level corrects listedsyntaxerrors
programming language into the the
mightneed to recompile
low-level machine language code several times
understanding the Evolution Programming
of

Models

-Major models or paradigms usedby programmers


procedural programming
-

the program into production


Putting -

Focuses on the procedures thatprogrammers create


-
objectoriented programming
Focuses on the objects, or "things", anddescribes their
-

features/attributes andtheir behaviors


-

Major Difference
-

Focus the programmers take the earliest planning


depends
-

process on program's purpose stages ofa


project
-may take several months

-conversion
-
entire seto factions an organization t ake
must

to switch over to using a new program or set


of

programs

Testing the Program


Logical Error
-

-Use a
syntactically
correct statementbutuse
context
current
the
wrong one for the
-

Test
-execute the program with some sample data to

see wether the resultare logically -


correct
flowcharting
pseudocode
programs should be testedwith many sets
-

data
of

ALGORITHM
setof instructions to perform a specific
-

Maintaing the Program task


-

Maintenance -

well-definedstep-by-stepsolution
-making changes after program is putinto Flowchart
production -

Graphical representation of an

algorithm
-common changes to existing programs
-

Repeatthe development cycle pseudocode


-

method of
describing algorithm
Understanding User Environments
unggembing programminganguage
-

Command line
-Location on your computer screen atwhich
communicate with
you type textentries to flowsharting symbol
operating system
the computer's

Graphical User Interface (GUI)


-Allows users interactwith
to a program in a
graphical environment
flowcharting symbol OUTPUT OPERATIONS
↳Flowchart

OUAPU Or Write
A, B.
A, B.

↳ pseudocode
OutputA;Or Write A;

STARTS END OPERATION Output B; Write;


↳ Flowchart SEQUENTIAL OPERATIONS
Start
signifies the startand ↳ sequential is very simple design
endof the flowchart
end
G itis notinvolve conditional
or iterative processing
↳ Pseudocode
StartProgram c design in type is normally
from tot right
bottom/leftto
End Program
Flowchart Pseudocode
VARIABLE DECLARATION start
Start
process I
process I
↳Flowchart
process 2 process 2
End
end

*3. 1416
EXAMPLE 1
Design Flowchart and pseudocode thatwill
↳> Pseudocode a
accept two numbers display
and the computed
sum and product
SetX to 11
SetPI to 3.1416 pseudocode Flowchart
start start

IPUT OPERATIONS SetA, B, sum, product 0


to =0, B 0
A
sum=0,
=

Product 0 =

inputA, B
FindATB an dassign to sum it
A,B
↳Flowchart product
FindAAB and assign to
Sum, product Sum A
=
+ B product-A*B
Display
end
Display sum, product

A, B.
IPUt Or
ARE End

↳ pseudocode
InputA;or Read A;
Input B; Read Bi
CONDITIONAL OPERATION Flowchart

e
-

a step where a decision be


must made
-ask
questions and choose actions basedon the
available options

EXAMPLE2

isret
a flowchartandpseudocode
to determine
Create
if the passwordis correct. The correctpassword
is 123

pseudocode

Start
Set PASSWORD to 0
Input PASSWORD
IFPASSWORD is equal to 123
EXAMPLE4
Display"PASSWORD
is correct"

end
Create a flowchartandpseudocode to

determine if number is less


a
than,
equal for
greater than 0

"itrary
Pseudocode

Start
Set NUM OO
InputNUM
NUM
IF is less than to 0
"
Display:NUM than 8
is less
in
else IF NUM IS
greater than to 0
Display "NUM IS greater than to 0
"

else

Display "NUM is equal to 0


"

End
EXAMPLE3
create a flowchartand Pseudocode to determine Flowchart
if a number is oddor even

Start
Pseudocode

Set NUM to 0
mirae
Nissant
InputNUM
NUM
IF mod (1.) 2 is equal to 0
Display "NUM is EVEn"

elsisplay "NUM is ODD"


End
signment </3

8 Develop an algorithm squares a


that given number ③ the perimeter of a square is equat to the circumference
ofa circle. Developan algorithm that computes
Flowchart: pseudocode: the area of a circle given the side of the square

start start
setn B sq to
8
Pis C0
=

4s= 2Hr +=3.14


enter a number, n
/ n 0 =
W multiply to itself Ao=? Inputs

re
andstore the
69 0 outputA
result to sq
=

AHr2
=

W end
inputn

Flowchart: pseudocode:
sq n*
n=

Start start
Set s, Airto 0 and

display sq 3.14
pi to

arein
input S
end anddivide
multiply 2 to 3

to
its 3.14 then store
the result to r
antimeter pinches
& Develop an algorithm thatadverts
multiply to itself and to 3
Flowchart: pseudocode: then store the result
toA
start
Nat in
set 3 cm to display I

En
in
convertc m to
an

e
multiply cm to 2.54
display in
end


ed
MODULE 3: SEQUENTIAL JAVA PROGRAMMING
INTRODUCTION
• Computers have greatly affected our daily lives - helping us complete many tasks

• Computer Programs (software) are design specifically for each task

• Software is created with programming languages

• Java is an example of programming language

LANGUAGE OF A COMPUTER
• Machine Language: the most basic language of a computer

• A sequence of 0s and 1s

• Every computer directly understands its own machine language

• Bit = binary digit, 0, or 1

• Byte = sequence of 8 bits

EVOLUTION OF PROGRAMMING LANGUAGE


• Early computers programmed in a machine language

• Assembly languages were developed to make programmer’s job easier

• In assembly language, an instruction is an easy-to-remember form called mnemonic

• Assembler: translates assembly language instructions into machine language

• To run a Java program

1. Java instructions need to be translated into an


intermediate language called byte-code

2. Then the bytecode is interpreted into a particular machine language

• Compiler: a program that translates a program written in a high-level language into the
equivalent machine language

In the case of Java, this machine language is the bytecode

• Java Virtual Machine (JVM): hypothetical computer developed to make Java programs
machine independent

PROGRAMMING METHODOLOGIES
• 2 Basic Approach to programming design

- Structured Design

- Object - Oriented Design


STRUCTURED DESIGN
• A problem is divided into smaller subproblems

• Each subproblem is solved

• The solutions of all subproblems are the combined to solve the problem

OBJECT - ORIENTED DESIGN (OOD)


• A program is a collection of interacting objects

• Object - consists of date and operation

• Steps in OOD

1. Identify objects

2. Form the basis of the solution

3. Determine how these object interact

THE BASICS OF A JAVA PROGRAM


• Java program: collection of classes

• There is a main method in every Java application program

• Token: smallest individual unit of a program

FEATURES OF THE JAVA PROGRAMMING LANGAUGE


• Java

- Developed by Sun Microsystems

- An object-oriented language

- General-purpose

- Advantages

- Security features

- Architecturally neutral

- Can be run on a wide variety of computers

- Does not execute instructions on the computer directly

- Runs on a hypothetical computer known as a Java Virtual Machine (JVM)

• Source code

- Programming statements written in high-level programming language


FEATURES OF THE JAVA PROGRAMMING LANGAUGE
• Development environment

- A set of tools used to write programs

• Byte code

- Statements saved in a file

- A binary program into which the Java compiler converts source code

• Java interpreter

- Checks bytecode and communicate with the operating system

- Executes bytecode instructions line by line within the Java Virtual Machine

• WORA

- Write once, run anywhere

• Console applications

- Support character output

• Windowed applications

- Menus

- Toolbars

- Dialog boxes

A JAVA PROGRAM
Public class ASimpleJavaProgram

public static void main (string [] args)

System.out.println(“My first Java Program.”);

System.out.println(“The sum of 5 and 3 = ” + 8);


?
System.out.println(“9 + 8 = ” + (9 + 8));

Sample Run:

My First Java Program.

The sum of 5 and 3 = 8

9 + 8 = 17
PROCESSING OF A JAVA PROGRAM
• Two types of Java programs: applications and applets

• Source program: written in a high-level language

• Loader: transfers the compiled code (bytecode) into main memory

• Interpreter: reads and translates each bytecode instruction into machine language
and then executes it

PROBLEM - SOLVING PROCESS


1. Analyze the problem: outline solution requirements and design an algorithm

2. Implement the algorithm in a programming language (Java) and verify that


the algorithm works

3. Maintain the program: use and modify if the problem domain changes

A JAVA PROGRAM
Public class First

public static void main (string [] args)

{ -

First
System.out.println(“First Java Application”);
Clas S
}

UNDERSTANDING THE FIRST CLASS


• Everything used within a Java program must be part of a class

• Define a Java class using any name or identifier

• Java Identifiers

- Names of things
·

- Consist of:

- Letters

- Digits

- The underscore character (_)

- The dollar sign ($)


RULES IN NAMING IDENTIFIERS
• Requirements for identifiers

1. Must begin with one of the following:

- Letter of the English alphabet

- Non-English letter (such as α or π)

- Underscore

- Dollar sign

2. Cannot begin with a digit

3. Can only contain:

- Letters

- Digits

- Underscores

- Dollar signs

4. Cannot be a Java reserved keyword

5. Cannot be true, false, or null

IDENTIFIERS
• Upper Camel casing (Pascal casing)

- Each word of an identifier begins with uppercase letter

- UnderGradStudent

- InventoryItem

• Access specifier
`
- Defines how a class can be accessed

JAVA RESERVED WORDS


VARIABLES
• Variable (name, value, data type, size)

- Content may change during program execution

- Must be declared before it can be used

- May not be automatically initialized

- If new value is assigned, old one is destroyed

- Value can only be changed by an assignment statement or an input (read) statement

• Example

double amountDue;

int counter;

char ch;

int num1, num2;


CONSTANT DECLARATION
• Named constant

- Cannot be changed during program execution

- Declared by using the reserved word final

- Initialized when it is declared

• Example

final double CENTIMETERS_PER_INCH = 2.54;

final int NO_OF_STUDENTS = 20;

final char BLANK = ' ';

final double PAY_RATE = 15.75;

CREATING A JAVA PROGRAM


• Syntax of a class

public class Classname

ClassMembers

• Syntax of the main-method

public static void main (String [] args)

Statement 1

Statement n

}
PARTS OF TYPICAL CLASS

THE main () METHOD


• Static

- reserved keyword

- Means the method is accessible and usable even though no objects of the class exist

• Void

- Use in the main() method header

- Does not indicate the main() method is empty

- Indicates the main() method does not return a value when called

- Does not mean that main() doesn’t produce output


INDENT STYLE
• Use whitespace to organize code and improve readability

• For every opening curly brace ( { ) in a Java program, there must be a corresponding closing
curly brace
(} )

• Placement of the opening and closing curly braces is not important to the compiler

• Allman style used in text

USING THE Scanner CLASS TO ACCEPT KEYBOARD INPUT


• Standard input stream object: System.in

• System.in object

• Standard input device

• Normally the keyboard

• AccessusingtheScannerclass

• Scannerobject

• Breaks input into units called tokens

• To read data:

1. Create an input stream object of the class Scanner

2. Use the methods such as next, nextLine, nextInt, and nextDouble

static Scanner console = new Scanner(System.in);

• Example

static Scanner console = new Scanner(System.in);

int feet;

int inches;

Suppose the input is

23 7

feet = console.nextInt(); //Line 1

inches = console.nextInt(); //Line 2


OUTPUT
Standard output subject : System.out

Methods :

print

println

Syntax:

System.out.print(StringExp);

System.out.println(StringExp);

System.out.print();

System.out.println(“Hello World”);

System.out.print(“Hello World”);

int x = 100;

System.out.println(“x”);

System.out.println (x);

System.out.println (“x = “ + x);

System.out.println (“5” + “10”);

System.out.println (5 + 10);

System.out.println (5 + 10 + “abc”);

System.out.println (“abc” + 5 + 10);

System.out.println (“abc” + (5 + 10));


ESCAPE SEQUENCE
• Begins with a backslash followed by a character

• Represents a single nonprinting character

char aNewLine = ‘\n’;

• To produce console output on multiple lines in the command window, use one of these
options:

- Use the newline escape sequence

- Use the println() method multiple times

Import STATEMENT
• Used to import the components of a package into a program

• Reserved word

• import java.io.*

• imports the components of the package java.io into the program

• Primitive data types and the class string

- Part of the Java Language

- Don’t need to be imported

THE ASSIGNMENT STATEMENT


Syntax: Variable = expression;

Example:

num1 = 13;

num2 = 5 * 5 - 11;

sale = 0.05 * 1000;

first = ‘A’;

Str = “It is a rany day.”;


ADDING COMMENTS
• Program comments

- Nonexecuting statements added to a program for documentation

- Use to leave notes for yourself or others

- Include the author, date, and class’s name or function

• Comment out a statement

- Turn it into a comment

- The compiler does not translate, and the JVM does not execute its command

TYPES OF COMMENTS
• Line comments

- Start with two forward slashes (//)

- Continue to the end of the current line

- Do not require an ending symbol

• Block comments

- Start with a forward slash and an asterisk (/*)

- End with an asterisk and a forward slash (*/)

• Javadoc comments

- A special case of block comments

- Begin with a slash and two asterisks (/**)

- End with an asterisk and a forward slash (*/)

- Use to generate documentation


Example

INDENT STYLE
• Use whitespace to organize code and improve readability

• For every opening curly brace ( { ) in a Java program, there must be a corresponding closing
curly brace (} )

• Placement of the opening and closing curly braces is not important to the compiler

• Allman style used in text

SAVING A JAVA APPLICATION


• Save the class in a file with exactly the same name and .java extension

• For public classes, class name and filename must match exactly

COMPILING A JAVA APPLICATION


• Compile the source code into bytecode

• Translate the bytecode into executable statements

• Using a Java interpreter

• Type javac First.java

• Compilation outcomes

• Javac is an unrecognized command

• Program language error messages

• No messages indicating successful completion

ERRORS IN JAVA PROGRAM


• Reasons for error messages

- Misspelled the command javac

- A misspelled filename

- Not within the correct subfolder or subdirectory on the command line

- Improper installation of Java


CORRECTING SYNTAX ERRORS
• The first line of the error message displays:

- The name of the file where the error was found

- The line number

-The nature of the error

• Next lines identify:

- The symbol

- The location

• Compile-time error

- The compiler detects a violation of language rules

- Refuses to translate the class to machine code

• Parsing

- Compiler divides source code into meaningful portions

OTHER LOGICAL ERRORS


• Logic error

- The syntax is correct but incorrect results were produced when executed

• Run-time error

- Not detected until execution

- Often difficult to find and resolve


RUNNING A JAVA APLLICATION
• Run the application from the command line

- Type javaFirst

• Shows the application’s output in the command window

• The class is stored in a folder named Java on the C drive

SAMPLE RUN

FINDING HELP
• Java API

- Also called the Java class library

- Provides prewritten information about Java classes

• FAQs on the Java Web site

• Java Development Kit (JDK)

- A software development kit (SDK) of programming tools

- Free to download

DON’T DO IT
• Don’t forget the file’s name must match the class name

• Don’t confuse these terms:

- Parentheses, braces, brackets, curly braces, square brackets, and angle brackets

• Don’t forget to end a block comment

• Don’t forget that Java is case sensitive

- Don’t forget to end every statement with a semicolon • Do not end class or method
headers with a semicolon

• Don’t forgot to recompile when making changes

• Don’t panic when you see a lot of compiler error messages

• Don’t assume your program is perfect when all compiler errors are eliminated.
MODULE 4:DATA TYPES
DATA TYPES
• set of values together with a set of operations

• A type of data that can be stored

• How much memory an item occupies

• What types of operations can be performed on data

JAVA DATA TYPES


• Primitive data types

- A simple data type

• Reference data types ( to be discussed next term )

- Also known as Non-Primitive Data Type

- More complex data types

PRIMITIVE DATA TYPES


• Integral

- byte, short, int, long

• Floating

- float, double

• Textual

- char

• Logical

- boolean
INTEGRAL

Examples:

byte myNum = 200;

System.out.println(myNum);

short myNum = 5000;

System.out.println(myNum);

int myNum = 100000;

System.out.println(myNum);

long myNum = 15000000000L;

System.out.println(myNum);

FLOATING POINT
float myNum = 5.75f;

System.out.println(myNum);

double myNum = 19.99d;

System.out.println(myNum);

float f1 = 35e3f;

double d1 = 12E4d;

System.out.println(f1);

System.out.println(d1);

TEXTUAL TYPE
• Can be represented in three ways:
TEXTUAL
Examples:

char myGrade = 'B’;

System.out.println(myGrade);

• You can use ASCII values to display certain characters

char a = 65, b = 66, c = 67;

System.out.println(a);

System.out.println(b);

System.out.println(c);

BOOLEAN
Example:

boolean isJavaFun = true;

boolean isFishSalty = false;

System.out.println(isJavaFun); // Outputs true

System.out.println(isFishTasty); // Outputs false

STRING
• used to store a sequence of characters (text).

• String values must be surrounded by double quotes

Example:

String greeting = “Mabuhay!";

System.out.println(greeting);

CONCATENATION
• A numeric variable is concatenated to a String using the plus sign ( + )

• The entire expression becomes a String

• The println() method can accept a number or String


PRIMITIVE AND NON-PRIMITIVE DATA TYPES
The main difference between primitive and non-primitive data types are:

• Primitive types are predefined (already defined) in Java. Non-primitive types are created by
the programmer and is not defined by Java (except for String).

• Non-primitive types can be used to call methods to perform certain operations, while
primitive types cannot.

• A primitive type has always a value, while non-primitive types can be null.

• A primitive type starts with a lowercase letter, while non-primitive types starts with an
uppercase letter.

• The size of a primitive type depends on the data type, while non-primitive types have all the
same size.

TYPE OF CONVERSION (CASTING)


• Type casting is when you assign a value of one primitive data type to another type.

• In Java, there are two types of casting:

• Widening Casting (automatically)

- converting a smaller type to a larger type size

byte -> short -> char -> int -> long -> float -> double

• Narrowing Casting (manually)

- converting a larger type to a smaller size type

double -> float -> long -> int -> char -> short -> byte

WIDENING CASTING
• done automatically when passing a smaller size type to a larger size type

public class MyClass {

public static void main(String[] args) {

int myInt = 13;

double myDouble = myInt; // Automatic casting:

int to double System.out.println(myInt); // Outputs 13 System.out.println(myDouble); //


Outputs 13.0
}}
NARROWING CASTING
• must be done manually by placing the type in parentheses in front of the value

public class MyClass {

public static void main(String[] args) {

double myDouble = 9.78;

int myInt = (int) myDouble; // Manual casting:

// double to int

System.out.println(myDouble); // Outputs 9.78

System.out.println(myInt); // Outputs 9
}
}

TYPE OF CONVERSION (CASTING)


• Used to avoid implicit type coercion

• Syntax

(dataTypeName) expression

• Expression evaluated first, then type converted to dataTypeName

• Examples

(int)(7.9 + 6.7) = 14

(int)(7.9) + (int)(6.7) = 13

• Convert String to int or double

- Use methods from the built-in Java classes Integer and Double

- Type-wrapper classes

- Each primitive type has a corresponding class contained in the java.lang package

- Include methods to process primitive type values

Integer.parseInt()

Double.parseDouble()

You might also like