You are on page 1of 10

Programming NC IV

1
Procedural Programming

Procedural Programming
This module introduces the fundamental concepts and principles of
procedural programming. It focuses on strategic problem solving and
algorithmic programming, as well as the principles of data structures and
functions.
This module aims to:
1. introduce the basic concepts of procedural programming;
2. understand the different variable types in Java;
3. explore the usage of Java methods; and
4. comprehend the concepts of classes and modifiers.

Basic Concepts of Procedural Programming


Procedural programming is a programming model based on the concept of
calling procedures (also called functions, methods, routines or subroutines).
Using this model, any of the procedures created might be called at any
location during the execution of a program, including other procedures or
itself. It also focuses on the step-by-step sequence of instructions to perform
a task.
Procedural programming is used by almost all programming languages. This
kind of approach is needed because computers and applications cannot
decide on their own which sequence to use. Who says computers are more
intelligent than us?
On the other hand, non-procedural programming is done by identifying what
needs to be done rather than how it should be done. Non-procedural
programming involves instructing the system as to how to complete a task.
While non-procedural languages exist, these languages are normally limited
to small applications and are limited in the scope of tasks that they can
perform.
The most commonly used programming languages which use the procedural
approach include C, C++, Java, FORTRAN, Pascal, and BASIC. These languages
have evolved over time but they all have procedural aspects to them.

The Procedural Program


A procedural program is a series of instructions to be performed by the
computer. Each instruction tells the computer what to do.
In the procedure-oriented approach, the problem is viewed as a sequence of
things to be done, such as writing, reading, calculating and printing, for which
a number of functions are written in order to accomplish said tasks.
Course Module
Figure 1. Sample Program

Let’s revisit the example discussed in the previous module.


As you can see, the program performs each task line-per-line. So the value of
number changes every time a task is performed.
At first, number is equal to 7, then we negated it and it becomes -7, then we
assigned it with +1, so it becomes positive 1 and so forth…

Procedural programming is tricky for large applications. Large procedural


programs can become hard to manage.
There is often little opportunity for abstraction, which largely helps in
simplifying a problem. (Don’t worry, we’ll discuss abstraction in a later
module.)
The interfaces between parts of an application can also become difficult to
manage. Programmers tend to spend a lot of time learning how to program
these interfaces.
Programming NC IV
3
Procedural Programming

Top-Down Design of a Program


How do you read a document? A letter? A report?
Top to bottom, left to right. (Unless, you’re Japanese)

There is also a so-called top-down design in programming. Picture this as an


inverted triangle.

Figure 2. Top-Down Representation

This refers to a case where a program method is continuously broken down


into smaller sub-problems (to decrease the complexity of the programming
task) until each sub-problem can be solved in a few steps.
This method is also known as the Divide and Conquer Strategy.
For example, when buying a pizza, a large "economy" size pizza is not always
the best to buy. The size of the pizza is measured in diameter (in inches).
A better buy has lower price per square inch. As most people cannot easily
estimate it, the vendors are making money faster.

Program Specification
To put the Divide and Conquer Strategy into practice, let’s consider the
following problem:
We need to design a program that compares 2 pizzas and determine which is
a better buy.

Figure 3. Pizza Problem

Course Module
Input: The diameters and total prices of the pizzas to compare.

Output: Cost per square inch for each pizza and which is a better buy
including caption with your images.

Analysis:
By using the top-down design, we can form the program subtasks
below:
1. Get the input for both pizzas.
2. Compute the price per sq. in. for the first pizza.
3. Compute the price per sq. in. for second pizza.
4. Determine which is the better buy between the two.
5. Display the results.

The sub-tasks 1, 4, and 5 are straightforward. However, sub-tasks 2


and 3 are very similar because the arguments are taken and one value
is computed.
Let's create a function for the computation of the two values and call it
unitPrice.

Algorithm for unitprice function:


1. Compute the radius of the pizza.
2. Compute the area of the pizza by formula: pi r 2
3. Compute (price / area) and display.

Pseudocode:
1. Compute for radius. radius = one half diameter
2. Get the area. area = pi * radius * radius
3. Return (price / area)

What are the arguments that the unitprice function need?


price, diameter

What is value should the unitprice function return or display?


unit price per square inch
Programming NC IV
5
Procedural Programming

Coding and Testing


Start your coding by specifying what your subtasks are doing. You can
write it as a comment in Netbeans.
Code the tasks. If the program compiles and produces answers, it does
not mean it is already correct.
Get your calculator and check. If your program has produced the
correct answer once, it may still be incorrect, so ran more extensive
tests.

A test either shows an error or demonstrates that the program functions


correctly. With more successful tests, you can gain confidence but you can
never be 100% sure.

If we code the problem above:

Figure 4. Coding for the Pizza Problem

In this example program, Pizza A is better since it has cheaper unit price
(price per square inch).

Course Module
Why Practice Top-Down Design?
One of the most basic ideas in solving problems involves subdividing a
problem into sub-problems and solving each sub problem separately.
Quite often, the attempt to answer a sub-problem introduces new sub-
problems at a lower level.
The subdivision of sub-problems should continue until a sub-problem can be
easily solved. This is equivalent to the refining of an algorithm.
In large projects, sub-problems may be assigned to different programmers or
teams, who will be given accurate guidelines about how that sub-problem fits
into the overall solution.

Classes and Modifiers


In practicing procedural programming, you will encounter classes, modifiers,
variables and methods.

Classes
A class is a blueprint from which individual objects are created. The class can
have any number of methods to access the value of various kinds of methods.
It can be seen by all classes from all packages in a project.
Example:

public class MyFirstClass{


public static void main(String[] args){
// body
}
}

The public class has to have the same name as the JAVA file.
A single Java file can contain more than one nonpublic class but can have
only one public class.

Modifiers
Modifiers are keywords that you add to those definitions to change their
meanings.
There are two types of modifiers in Java: (1) Access Modifiers and (2) Non-
Access Modifiers.
Access Modifiers - Java provides a number of access modifiers to set access
levels for classes, variables, methods and constructors. The four access levels
are:
1. private - visible to the class only
2. public - visible to the world
Programming NC IV
7
Procedural Programming

3. protected - visible to the package and all subclasses.


4. The default (No modifier) - visible to the package

Non-Access Modifiers - Java provides a number of non-access modifiers to


achieve many other functionalities:
1. The static modifier for creating class methods and variables;
2. The final modifier for finalizing the implementations of classes,
methods, and variables;
3. The abstract modifier for creating abstract classes and methods;
and
4. The synchronized and volatile modifiers, which are used for
threads.

Java Variables
Programs work by manipulating data placed in the computer memory. The
data can be numbers, text, objects, etc. The data is given a name, so that it can
be re-used whenever it is needed. The name and its corresponding value, is
known as a Variable.
A variable is a named storage that programs can manipulate. It can also be
defined as the name of the reserved area allocated in the memory. With the
combination of the words "vary" and "able", it simply means that the value of
a variable can be changed.

Variable Types
There are three kinds of variables in Java:
1. Local variables - These variables are declared within the body of a
method and can be only used inside the method. Unlike instance and
class variables, local variables are fussy about where you position the
declaration for it.
You must place the declaration before the first statement that actually
uses the variable.
Example:

public class LocalVariableTest{


public static void main(String[] args){
String message;
message = "Hello, World!";
System.out.println(message);
}
}

Course Module
The variable message is our local variable because it was declared
inside the main method.
Methods cannot use variables that are locally declared from other
methods.

2. Instance variables – These are variables that are declared in a class, but
outside a method. They hold values that might be referenced by more
than one method or block.
Instance variables can be accessed directly by calling the variable. They
should be called using the fully qualified name as
ObjectReference.VariableName.
Example:

import java.io.*;
public class InstanceVariableTest{
public String message;
public static void main(String[] args){
message = "Hello, World!";
System.out.println(message);
}
}

In the example above, the variable message is our instance variable


because it was declared outside the main method and was also given
a public access modifier.

3. Class/Static Variables - These variables are declared with the static


keyword in a class, but outside a method or a block. Defining its
visibility or access level is similar to instance variables.
Usually, static variables are declared publicly in order for them to be
available for users of the class.
Static variables can also include the final keyword. This means that
those variables are storing constant values.
Example:

import java.io.*;
public class StaticVariableTest{
public static String message;
public static final String PERSON = “Me”;
public static void main(String[] args){
message = "Hello, World!";
System.out.println(PERSON + message);
}
}
Programming NC IV
9
Procedural Programming

The variables message and PERSON are our static variables because
they were declared outside the main method along with a static
keyword. The variable PERSON has a final keyword that makes it
hold a constant value.

When a variable is declared with the keyword “static”, it is called a


class variable or static variable.
Without the static keyword, it is called an instance variable.

Java Methods
A Java method is a collection of commands that are grouped together to
perform an operation that can be used over again.
Sometimes, the terms “function” and “method” are used interchangeably. The
correct terminology for Java is “method”.
A simple Java method includes the following:
1. Modifier – It defines the access type or the visibility of the method. It is
optional to use.
Examples: public, private, protected
2. Return Type – This refers to the data type of the value to be returned by
the method.
Examples: void, int, double, boolean
3. Method Name – This is whatever you want to call your method depending
on its purpose. Just remember about the naming convention for Java
methods.
Examples: getName, getTotalAmount, setAge, displayName
4. Parameter List - It is the type, order, and number of parameters of a
method. Using parameters lists is optional, since a method may contain
zero parameters.
Examples: getName(String firstName, String lastName)
5. Method Body – This is where the actions of the method takes place. It
contains all valid Java instructions that the method should do.

Course Module
Example:

public int getNumber(int a, int b){


int answer = a % b;
return answer;
}

Where:
public − modifier
int − return type
getNumber − name of the method
x, y − formal parameters
int x, int y − list of parameters

References
Java Point. Variable in Java. India. Retrieved from:
http://www.javatpoint.com/variable-datatype
Tutorials Point. Available at: https://www.tutorialspoint.com
ZDU Student Manual. (1998). Java Programming: Part 1. Retrieved from:
https://7chan.org/pr/src/JAVA_-_Student_Manual_-_Tutorial_-
_Exercises.pdf

You might also like