0% found this document useful (0 votes)
28 views35 pages

COMP1Lp1 (1)

Uploaded by

sethpaul30
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)
28 views35 pages

COMP1Lp1 (1)

Uploaded by

sethpaul30
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/ 35

1 | Computer Programming 1

UNIT 1: Introduction to Object Oriented Programming and UML

1.0 Intended Learning Outcomes

a. Explain the fundamental concept of OOP;


b. Explain the purpose of Unified Modeling Language.
c. Explain the importance of Inheritance

1.1 INTRODUCTION

OOPS is about developing an application around its data, i.e. objects which provides
the access to their properties and the possible operations in their own way. These
features include Abstraction, encapsulation, inheritance and polymorphism.

ABSTRACTION

One of the most fundamental concept of OOPs is Abstraction. Abstraction is a


process where you show only “relevant” data and “hide” unnecessary details of an
object from the user. For example, when you login to your Amazon account online,
you enter your user_id and password and press login, what happens when you
press login, how the input data sent to amazon server, how it gets verified is all
abstracted away from the you.

Another example of abstraction: A car in itself is a well-defined object, which is


composed of several other smaller objects like a gearing system, steering
mechanism, engine, which are again have their own subsystems. But for humans car
is a one single object, which can be managed by the help of its subsystems, even if
their inner details are unknown.

ENCAPSULATION

Encapsulation is a) Binding the data with the code that manipulates it. B) It keeps the
data and the code safe from external interference

Looking at the example of a power steering mechanism of a car. Power steering of a

C. M. D. Hamo-ay
1 | Computer Programming 2

car is a complex system, which internally have lots of components tightly coupled
together, they work synchronously to turn the car in the desired direction. It even
controls the power delivered by the engine to the steering wheel. But to the external
world there is only one interface is available and rest of the complexity is hidden.
Moreover, the steering unit in itself is complete and independent. It does not affect
the functioning of any other mechanism.

INHERITANCE

o Inheritance is the mechanism by which an object acquires the some/all


properties of another object.
o It supports the concept of hierarchical classification.
o For example: Car is a four wheeler vehicle so assume that we have a class
Four Wheeler and a sub class of it named Car. Here Car acquires the
properties of a class Four Wheeler. Other classifications could be a jeep,
tempo, van etc.

POLYMORPHISM

Polymorphism is one of the OOPs feature that allows us to perform a single action in
different ways. For example, let’s say we have a class Animal that has a
method sound (). Since this is a generic class so we can’t give it an implementation
like: Roar, Meow, Oink etc. We had to give a generic message. In OOP using Java we
can write it this way,

public class Animal{


...
public void sound(){
System.out.println("Animal is making a sound");
}
}

Don’t worry , we will touch this code later one at a time .

1.2 CLASSES, OBJECTS AND METHODS

C. M. D. Hamo-ay
1 | Computer Programming 3

What is Class in Java?

Class are a blueprint or a set of instructions to build a specific type of object. It is a


basic concept of Object-Oriented Programming which revolve around the real-life
entities. Class in Java determines how an object will behave and what the object will
contain.

Syntax

class <class_name>{
field;
method;
}

Ops! Don’t worry about the syntax for now, you will learn it later.

What is Object in Java?

Object is an instance of a class. An object in OOPS is nothing but a self-contained


component which consists of methods and properties to make a particular type of
data useful. For example color name, table, bag, barking. When you send a message
to an object, you are asking the object to invoke or execute one of its methods as
defined in the class.

From a programming point of view, an object in OOPS can include a data structure,
a variable, or a function. It has a memory location allocated. Java Objects are
designed as class hierarchies.

Syntax

ClassName ReferenceVariable = new ClassName();

C. M. D. Hamo-ay
1 | Computer Programming 4

What is the Difference Between Object and Class in Java?

A Class in object oriented programming is a blueprint or prototype that defines the


variables and the methods (functions) common to all Java Objects of a certain kind.

An object in OOPS is a specimen of a class. Software objects are often used to model
real-world objects you find in everyday life

Understand the concept of Java Classes and Objects

Let’s take an example of developing a pet management system, specially meant for
dogs. We need various information about the dogs like different breeds of the dogs,
the age, size, etc.

You need to model real-life beings, i.e., dogs into software entities let’s have an
illustration,

Example 1-1 how do you design software in the figure above?

Solution:

C. M. D. Hamo-ay
1 | Computer Programming 5

Step 1: List down the differences between them


.
Some of the differences you might have listed out maybe breed, age, size, color, etc.
If you think for a minute, these differences are also some common characteristics
shared by these dogs. These characteristics (breed, age, size, color) can form a data
members for your object. So, we obtain common characteristics these are,

Step 2: Next, list out the common behaviors of these dogs like sleep, sit, eat,
etc. So these will be the actions of our software objects.

C. M. D. Hamo-ay
1 | Computer Programming 6

Step 3 So far we have defined the following things:

 Class – Dogs
 Data members or objects– size, age, color, breed, etc.
 Methods– eat, sleep, sit and run.

For better understanding we can model the Dog according to the diagram below,

Step 4: Now, for different values of data members (breed size, age, and color)
in Java class, you will get different dog objects.

Step 5: You can design any program using this OOPs approach.

C. M. D. Hamo-ay
1 | Computer Programming 7

While creating a class, one must follow the following principles.

 Single Responsibility Principle (SRP)- A class should have only one reason to
change
 Open Closed Responsibility (OCP)- It should be able to extend any classes
without modifying it
 Liskov Substitution Responsibility (LSR)- Derived classes must be substitutable
for their base classes
 Dependency Inversion Principle (DIP)- Depend on abstraction and not on
concretions
 Interface Segregation Principle (ISP)- Prepare fine grained interfaces that are
client specific

Classes and Objects in Java Example Programs

Example 1-2 Let us now examine the java program of the given dog information

// Class Declaration
public class Dog {
// Instance Variables
String breed;
String size;
int age;
String color;

// method 1
public String getInfo() {
return ("Breed is: "+breed+" Size is:"+size+" Age is:"+age+" color is:
"+color);
}

public static void main(String[] args) {


Dog maltese = new Dog();
maltese.breed="Maltese";
maltese.size="Small";
maltese.age=2;
maltese.color="white";
System.out.println(maltese.getInfo());
}
}

C. M. D. Hamo-ay
1 | Computer Programming 8

Well, the code is quite complicated for now however, we follow the correct
algorithm construction of java program. Don’t worry my dear you will be
enlightened in the coming lessons.

What is the output of the program by the way?

Breed is: Maltese Size is: Small Age is:2 color is: white

Java Object and Class Example: main outside class

In previous program, we are creating main() method inside the class. Now, we
create classes and define main() method in another class. This is a better way than
previous one.

// Class Declaration
class Dog {
// Instance Variables
String breed;
String size;
int age;
String color;

// method 1
public String getInfo() {
return ("Breed is: "+breed+" Size is:"+size+" Age is:"+age+" color is: "+color);
}
}
public class Execute{
public static void main(String[] args) {
Dog maltese = new Dog();
maltese.breed="Maltese";
maltese.size="Small";
maltese.age=2;
maltese.color="white";
System.out.println(maltese.getInfo());
}
}

C. M. D. Hamo-ay
1 | Computer Programming 9

What is the output again?

Breed is: Maltese Size is:Small Age is:2 color is: white

Summary

 Java Class is an entity that determines how java objects will behave and what
objects will contain
 A Java objects is self-contained component which consists of methods and
properties to make certain type of data useful
 A class system allows the program to define a new class(derived class) in
terms of an existing class(super class) by using a technique like inheritance,
overriding and augmenting.

1.3 UNIFIED MODELLING LANGUAGE

UML or Unified Modelling Language is the symbol used to explain the purpose of
the four most common diagrams this are: Class, Object, sequence, and package
diagrams. These diagrams are used extensively when describing software designed
according to Object Oriented programming approach.

Our objective here is to draw a class diagram, object diagram, sequence diagram,
and package diagrams. We need also to understand the different class relationships,
Association, dependency Inheritance and implementation. Let’s have examples,

What is Class in UML Diagram?

A Class in UML diagram is a blueprint used to create an object or set of objects. The
Class defines what an object can do. It is a template to create various objects and
implement their behavior in the system. A Class in UML is represented by a
rectangle that includes rows with class names, attributes, and operations.

C. M. D. Hamo-ay
1 | Computer Programming 10

What is Class Diagram?

A Class Diagram in Software engineering is a static structure that gives an overview


of a software system by displaying classes, attributes, operations, and their
relationships between each other. This Diagram includes the class name, attributes,
and operation in separate designated compartments. Class Diagram helps construct
the code for the software application development.

Benefits of Class Diagram

 Class Diagram Illustrates data models for even very complex information
systems
 It provides an overview of how the application is structured before studying the
actual code. This can easily reduce the maintenance time
 It helps for better understanding of general schematics of an application.
 Allows drawing detailed charts which highlights code required to be
programmed
 Helpful for developers and other stakeholders.

Essential elements of A UML class diagram

1. Class Name
2. Attributes
3. Operations

Class Name

The name of the class is only needed in the graphical


representation of the class. It appears in the topmost
compartment. A class is the blueprint of an object which can
share the same relationships, attributes, operations, &
semantics. The class is rendered as a rectangle, including its
name, attributes, and operations in separate compartments

Following rules must be taken care of while representing a class:

1. A class name should always start with a capital letter.

C. M. D. Hamo-ay
1 | Computer Programming 11

2. A class name should always be in the center of the first compartment.


3. A class name should always be written in bold format.
4. UML abstract class name should be written in italics format.

Attributes:

An attribute is named property of a class which describes the


object being modeled. In the class diagram, this component is
placed just below the name-compartment.

A derived attribute is computed from other attributes. For example, an age of the
student can be easily computed from his/her birth date.

Attributes characteristics

 The attributes are generally written along with the visibility


factor.
 Public, private, protected and package are the four visibilities
which are denoted by +, -, #, or ~ signs respectively.
 Visibility describes the accessibility of an attribute of a class.
 Attributes must have a meaningful name that describes the
use of it in a class.

Relationships

There are mainly three kinds of relationships in UML:

1. Dependencies
2. Generalizations
3. Associations

Dependency

A dependency means the relation between two or more classes in which a change in one
may force changes in the other. However, it will always create a weaker relationship.

C. M. D. Hamo-ay
1 | Computer Programming 12

Dependency indicates that one class depends on another.

In the following UML class diagram examples, Student has a dependency on College

Generalization:

A generalization helps to connect a subclass to its


superclass. A sub-class is inherited from its superclass.
Generalization relationship can’t be used to model interface
implementation. Class diagram allows inheriting from
multiple super classes.
In this example, the class Student is generalized from
Person Class.

Association:

This kind of relationship represents static relationships between classes A and B. For
example; an employee works for an organization. Here are some rules for Association:

 Association is mostly verb or a verb phrase or noun or noun phrase.


 It should be named to indicate the role played by the class attached at the end of the
association path.
 Mandatory for reflexive associations

In this example, the relationship between student and college is shown which is studies.

C. M. D. Hamo-ay
1 | Computer Programming 13

Multiplicity

A multiplicity is a factor associated with an attribute. It specifies


how many instances of attributes are created when a class is
initialized. If a multiplicity is not specified, by default one is
considered as a default multiplicity.

Let’s say that that there are 100 students in one college. The college can have multiple
students.

Aggregation

Aggregation is a special type of association that models a whole- part relationship


between aggregate and its parts.

For example, the class college is made up of one or more student. In aggregation, the
contained classes are never totally dependent on the lifecycle of the container. Here, the
college class will remain even if the student is not available.

Composition:

The composition is a special type of aggregation which denotes strong ownership


between two classes when one class is a part of another class.

For example, if college is composed of classes student. The college could contain many
students, while each student belongs to only one college. So, if college is not functioning
all the students also removed.

C. M. D. Hamo-ay
1 | Computer Programming 14

Aggregation vs. Composition

Abstract Classes

It is a class with an operation prototype, but not the implementation. It is also possible
to have an abstract class with no operations declared inside of it. An abstract is useful
for identifying the functionalities across the classes. Let us consider an example of an
abstract class. Suppose we have an abstract class called as a motion with a method or an
operation declared inside of it. The method declared inside the abstract class is called
a move ().

This abstract class method can be used by any object such as a car, an animal, robot, etc.
for changing the current position. It is efficient to use this abstract class method with an
object because no implementation is provided for the given function. We can use it in
any way for multiple objects.

In UML, the abstract class has the same notation as that of the class. The only difference
between a class and an abstract class is that the class name is strictly written in an italic
font.

An abstract class cannot be initialized or instantiated.

In the abstract class notation, there is the only a


single abstract method which can be used by
multiple objects of classes.

C. M. D. Hamo-ay
1 | Computer Programming 15

UML Class Diagram Creating a class diagram is a straightforward process. It does not
involve many technicalities.

Example 1-3 ATM UML class diagram

ATMs system is very simple as customers need to press some buttons to receive cash.
However, there is multiple security layers that any ATM system needs to pass. This
helps to prevent fraud and provide cash or need details to banking customers.

Below given is a UML Class Diagram:

UML Class Diagram Example

C. M. D. Hamo-ay
1 | Computer Programming 16

Class Diagram in Software Development Lifecycle

Class diagrams can be used in various software development phases. It helps in


modeling class diagrams in three different perspectives.

1. Conceptual perspective: Conceptual diagrams are describing things in the real


world. You should draw a diagram that represents the concepts in the domain under
study. These concepts related to class and it is always language-independent.

2. Specification perspective: Specification perspective describes software


abstractions or components with specifications and interfaces. However, it does not
give any commitment to specific implementation.

3. Implementation perspective: This type of class diagrams is used for


implementations in a specific language or application. Implementation perspective,
use for software implementation.

Best practices of Designing of the Class Diagram

Class diagrams are the most important UML diagrams used for software application
development. There are many properties which should be considered while drawing
a Class Diagram. They represent various aspects of a software application.

Here, are some points which should be kept in mind while drawing a class diagram:

 The name given to the class diagram must be meaningful. Moreover, It should
describe the real aspect of the system.
 The relationship between each element needs to be identified in advance.
 The responsibility for every class needs to be identified.
 For every class, minimum number of properties should be specified. Therefore,
unwanted properties can easily make the diagram complicated.
 User notes should be included whenever you need to define some aspect of the
diagram. At the end of the drawing, it must be understandable for the software
development team.
 Lastly, before creating the final version, the diagram needs to be drawn on plain
paper. Moreover, It should be reworked until it is ready for final submission.

C. M. D. Hamo-ay
1 | Computer Programming 17

1. 4 References

1. https://www.guru99.com/uml-class-diagram.html
2. https://www.guru99.com/java-oops-class-objects.html
3. Simon Kendal Object oriented programming using C#, 2nd Edition, 2018,
4. Stuart Reges ,Marty Stepp. Building Java Program. 2011, Pearson Education, Inc.,
publishing as Addison-Wesley.

C. M. D. Hamo-ay
1 | Computer Programming 18

UNIT 2. INTRODUCTION TO BASIC PROGRAMMING

2.0 Intended learning outcome

a. Identify variables and use it in a program


b. Explain the basic format of a program
c. Explain loops and use it in a proram
c. Create basic program using I/O

2.1 INTRODUCTION

Programming is an art of science of reasoning .Why?, just because when you create
your program later on you are already considered a programmer isn’t it?
Programmers spent months years to develop such passionate work however, you
and them must deserve loved , recognition and above all understanding. Before we
proceed with creating a program let us be familiarize ourselves with the important
terminologies that we are going to use in our discussion.

Java Virtual Machine (JVM)

This is generally referred as JVM. Before, we discuss about JVM lets see the phases of
program execution. Phases are as follows: we write the program, then we compile
the program and at last we run the program.

1) Writing of the program is of course done by java programmer like you and me.

2) Compilation of program is done by javac compiler, javac is the primary java


compiler included in java development kit (JDK). It takes java program as input and
generates java byte code as output.

3) In third phase, JVM executes the byte code generated by compiler. This is called
program run phase.

So, now that we understood that the primary function of JVM is to execute the byte
code produced by compiler. Each operating system has different JVM; however the
output they produce after execution of byte code is same across all operating
systems. That is why we call java as platform independent language.

C. M. D. Hamo-ay
1 | Computer Programming 19

BYTECODE

As discussed above, javac compiler of JDK compiles the java source code into byte
code so that it can be executed by JVM. The byte code is saved in a .class file by
compiler.

Java Development Kit(JDK)

While explaining JVM and bytecode, I have used the term JDK. Let’s discuss about
it. As the name suggests this is complete java development kit that includes JRE
(Java Runtime Environment), compilers and various tools like JavaDoc, Java
debugger etc. In order to create, compile and run Java program you would need JDK
installed on your computer.

Java Runtime Environment(JRE)

JRE is a part of JDK which means that JDK includes JRE. When you have JRE
installed on your system, you can run a java program however you won’t be able to
compile it. JRE includes JVM, browser plugins and applets support. When you only
need to run a java program on your computer, you would only need JRE.

Java Virtual Machine (JVM), Difference JDK, JRE & JVM – Core Java

Java is a high level programming language. A program written in high level


language cannot be run on any machine directly. First, it needs to be translated into
that particular machine language. The javac compiler does this thing, it takes java
program (.java file containing source code) and translates it into machine code
(referred as byte code or .class file).

Java Virtual Machine (JVM) is a virtual machine that resides in the real machine
(your computer) and the machine language for JVM is byte code. This makes it
easier for compiler as it has to generate byte code for JVM rather than different
machine code for each type of machine. JVM executes the byte code generated by
compiler and produce output. JVM is the one that makes java platform independent.

So, now we understood that the primary function of JVM is to execute the byte code
produced by compiler. Each operating system has different JVM, however the
output they produce after execution of byte code is same across all operating
systems. Which means that the byte code generated on Windows can be run on Mac
OS and vice versa. That is why we call java as platform independent language. The
same thing can be seen in the diagram 1.1.

C. M. D. Hamo-ay
1 | Computer Programming 20

Figure 1.1 Java source code compiled into different platform

So to summarise everything: The Java Virtual machine (JVM) is the virtual machine
that runs on actual machine (your computer) and executes Java byte code. The JVM
doesn’t understand Java source code, that’s why we need to have javac compiler that
compiles *.java files to obtain *.class files that contain the byte codes understood by
the JVM. JVM makes java portable (write once, run anywhere). Each operating
system has different JVM, however the output they produce after execution of byte
code is same across all operating systems.

JVM Architecture

C. M. D. Hamo-ay
1 | Computer Programming 21

Functions:

Class Loader: The class loader reads the .class file and save the byte code in
the method area.

Method Area: There is only one method area in a JVM which is shared among all the
classes. This holds the class level information of each .class file.

Heap: Heap is a part of JVM memory where objects are allocated. JVM creates a
Class object for each .class file.

Stack: Stack is a also a part of JVM memory but unlike Heap, it is used for storing
temporary variables.

PC Registers: This keeps the track of which instruction has been executed and which
one is going to be executed. Since instructions are executed by threads, each thread
has a separate PC register.

Native Method stack: A native method can access the runtime data areas of the
virtual machine.

Native Method interface: It enables java code to call or be called by native


applications. Native applications are programs that are specific to the hardware and
OS of a system.

JVM Vs JRE Vs JDK

JRE: JRE is the environment within which the java virtual machine runs. JRE
contains Java virtual Machine (JVM), class libraries, and other files excluding
development tools such as compiler and debugger.

Which means you can run the code in JRE but you can’t develop and compile the
code in JRE.

JVM: As we discussed above, JVM runs the program by using class, libraries and
files provided by JRE.

C. M. D. Hamo-ay
1 | Computer Programming 22

JDK: JDK is a superset of JRE, it contains everything that JRE has along with
development tools such as compiler, debugger etc

2.2 HOW TO RUN AND COMPILE YOUR FIRST JAVA PROGRAM

Example 2.1 Create a java program that will produce an output “This is my
first program in java”

Solution:

public class FirstJavaProgram {


public static void main(String[] args){
System.out.println("This is my first program in java");
}//End of main
}//End of FirstJavaProgram Class

C. M. D. Hamo-ay
1 | Computer Programming 23

Note: This program is quite complicated as of now. However, we can have better
understanding in the next discussion. Don’t worry be happy.

How to compile and run the above program

Prerequisite: You need to have java installed on your system. You can get the java
from here.

Step 1: Open a text editor, like Notepad on windows and TextEdit on Mac. Copy the
above program and paste it in the text editor.

Step 2: Save the file as FirstJavaProgram.java. You may be wondering why we have
named the file as FirstJavaProgram, the thing is that we should always name the file
same as the public class name. In our program, the public class name
is FirstJavaProgram, that’s why our file name should be FirstJavaProgram.java.

Step 3: In this step, we will compile the program. For this, open command prompt
(cmd) on Windows, if you are Mac OS then open Terminal.
To compile the program, type the following command and hit enter

javac FirstJavaProgram.java

If you get some error then you first need to set the path before compilation.

Set Path in Windows:

Open command prompt (cmd), go to the place where you have installed java on
your system and locate the bin directory, copy the complete path and write it in the
command like this.

set path=C:\Program Files\Java\jdk1.8.0_121\bin

Note: Your jdk version may be different. Since I have java version 1.8.0_121 installed
on my system, I mentioned the same while setting up the path.

Step 4: After compilation the .java file gets translated into the .class file(byte code).
Now we can run the program. To run the program, type the following command

C. M. D. Hamo-ay
1 | Computer Programming 24

and hit enter

java FirstJavaProgram

Closer look to the First Java Program

Now that we have understood how to run a java program, let have a closer look at
the program we have written above.

public class FirstJavaProgram {

This is the first line of our java program. Every java application must have at least
one class definition that consists of class keyword followed by class name. When I
say keyword, it means that it should not be changed, we should use it as it is.
However the class name can be anything

public static void main(String[] args) {

This is our next line in the program, lets break it down to understand it:
public: This makes the main method public that means that we can call the method
from outside the class.

static: We do not need to create object for static methods to run. They can run itself.

void: It does not return anything.

main: It is the method name. This is the entry point method from which the JVM can
run your program.

(String[] args): Used for command line arguments that are passed as strings. We will
cover that in a separate post.

C. M. D. Hamo-ay
1 | Computer Programming 25

System.out.println("This is my first program in java");

This method prints the contents inside the double quotes into the console and inserts
a newline after.

SAQ 2-1 Create a program that will produce the following output

Hello ECE 1!
Is these the first time here in SSU?
How is your first class in Programming 1?

2.3 VARIABLES AND VARIABLE DEFINITION

In programming, we use variables just as we use it in mathematics , however


naming variables does not start with numeric values instead it could be a single
variable such as : x , y, and combination of alphanumeric character such as sum,
difference, area, length, etc. are correct variable definition. So that we will be
enlighten with naming correct variables let as have an example

Example 2.2 Compute the sum of two integers given that x = 1 and y = 5

Solution:

Step 1 : Identify the variables in the problem this are: x , and y, its so happen
that the value assigned on the variable x and y is given as 1, and 5
respectively that becomes a constant.
Step 2 : Upon knowing the given, what are you going to do with these
values? Yes! We are going to find the sum. So we can name another
variable who will hold the result when adding these two values, let us
use variable sum,

C. M. D. Hamo-ay
1 | Computer Programming 26

Step 3 : Create now the program algorithm using the java format mentioned
in our previous example we have,

public class AddTwoNumbers {

public static void main(String[] args) {

int x = 5, y = 15, sum;


sum = x + y;

System.out.println("Sum of these numbers: "+sum);


}
}

Output? Sum of these numbers: 20

Example 2.3 Modify example 2.2, these time you input two values of x and y instead
of constant.

Solution:

Remember in this problem we need Scanner so that our input will be recognize

Step 1 : Identify the variables, we can use the same variables: x,y,sum
Step 2 : Input the first integer assign the variable x
Input the second integer assign the variable y
Compute the sum of x + y
Display the result
Step 3 : Code the program

The Scanner allows us to capture the user input so that we can get the values of both
the numbers from user. The program then calculates the sum and displays it.

C. M. D. Hamo-ay
1 | Computer Programming 27

import java.util.Scanner;
public class AddTwoNumbers2 {

public static void main(String[] args) {

int x, y, sum;
Scanner sc = new Scanner(System.in);
System.out.println("Enter First Number: ");
x = sc.nextInt();

System.out.println("Enter Second Number: ");


y = sc.nextInt();

sc.close();
sum = x + y;
System.out.println("Sum of these numbers: "+sum);
}
}

Output? Enter First Number: 5


Enter Second Number: 13
Sum of these numbers: 18

2. 4 CONDITIONAL STATEMENT IN PROGRAMMING

One of the most common statement in programming is with the use of if..else
statement . These is a conditional statements that would allow to execute the
correctness of the statements in mathematics we use the symbol: >greater than, <less
than, = equal to, != not equal to , ║ or , && and ≥greater than or equal to, less than or
equal two≤, in these symbol we can check the validity of the given condition where
it is true or false. Le’s have a simple example.

Format of if else statement

C. M. D. Hamo-ay
1 | Computer Programming 28

If (x>y) If ((x>y) && (x!=0))


If { (condition)
{ {
Statement… Statement Statement
} …… ……………….
} }
Else Else Else
{ { {
Statement… Statement Statement
……………. …………………..
} } }

Example 2.4 Input two integers display the largest among the two

Solution:

Step 1 : we have three variables again, x,y, and large, large variable will hold
the result after comparison.
Step2 : Create the algorithm
: Input the first integer and assign x to hold the value
: Input second integer and assign y to hold the value
: Compare the two integers and select which is the largest
: Display the result
Step3: : Code the program

C. M. D. Hamo-ay
1 | Computer Programming 29

/* Java Program Example - Find Largest of Two Numbers */

import java.util.Scanner;

public class JavaProgram


{
public static void main(String args[])
{
int x,y , large;
Scanner scan = new Scanner(System.in);

System.out.print("Enter Two Number : ");


x = scan.nextInt();
y = scan.nextInt();

if(x>y)
{
large= x;
}
else
{
large = y;
}

System.out.print("Largest of Two Number is " +large);


}
}

2.5 LOOPS

The for loop helps to avoid such redundancy by repeatedly executing a sequence of
statements over a particular range of values.

Syntax of for loop:

C. M. D. Hamo-ay
1 | Computer Programming 30

for(initialization; condition ; increment/decrement)


{
statement(s);
}

Flow of Execution of the for Loop

As a program executes, the interpreter always keeps track of which statement is


about to be executed. We call this the control flow, or the flow of execution of the
program.

Example 2.4 Suppose you want to write out the squares of the first five integers.
You could write a program like this:

1 public class WriteSquares {


2 public static void main(String[] args) {
3 System.out.println(1 + " squared = " + (1 * 1));
4 System.out.println(2 + " squared = " + (2 * 2));
5 System.out.println(3 + " squared = " + (3 * 3));
6 System.out.println(4 + " squared = " + (4 * 4));
7 System.out.println(5 + " squared = " + (5 * 5));
8}
9}

C. M. D. Hamo-ay
1 | Computer Programming 31

To avoid these repetitive task manually instead, we use “ for” loop so we can write
in these way,

1 public class WriteSquares2 { Line 3: Initialization; condition; increment


2 public static void main(String[] args) { Initialization : int i =1;

Condition: i<=5;
3 for (int i = 1; i <= 5; i++) {
Increment: i++
4 System.out.println(i + " squared = " + (i * i));
5}
6}
7}

The output could be,

Note: there are three loops in programming these are: do..while, while..do, and for.

1.2 DATA COMMUNICATIONS AND NETWORKING FOR TODAY’S ENTERPRISE

C. M. D. Hamo-ay
1 | Computer Programming 32

Assignment No. 1

Name: _____________________________ Course, Year & Section: ________


Subject: COMP 1 Instructor: Francisco Dequito,Jr.

Directions: Solve the following comprehensively based on your own


understanding. Write your answers on a short bond paper.

1. a) Discuss problems and issues regarding the following subject of concern and
b) Find each concrete solutions to the problems you have identified.

 Abstraction
 INCAPSULATION
 INHERITANCE
 POLYMORPHISM

2. A man deposited his money in the bank for a period of n years. How much
money does he have in the bank if he withdraws the amount after how many
years assuming the money initially invested has interest compounded
annually(assume 5% or less). Use variables in the problem just for the purpose
of exercises and use for loop in the solution.

Output like these:

Initial amount deposited in pesos:


Interest rate per annum:
Year deposited:
Year withdrawn:
Amount in bank:

2. Create a java program. Your program will produce an output:

C. M. D. Hamo-ay
1 | Computer Programming 33

2.6 References

1. https://beginnersbook.com/java-tutorial-for-beginners-with-examples/
2. Simon Kendal. Object oriented programming using C#, 2nd Edition, 2018,
4. Stuart Reges ,Marty Stepp. Building Java Program. 2011, Pearson Education, Inc.,
publishing as Addison-Wesley.

2.7 Acknowledgment

Further revealed that the images, tables, figures and information contained in this
module were taken from the references cited above.

C. M. D. Hamo-ay
1 | Computer Programming 34

C. M. D. Hamo-ay
1 | Computer Programming 35

C. M. D. Hamo-ay

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy