0% found this document useful (0 votes)
211 views

My Notes

The document discusses computer programming and programming languages. It defines a computer program as a list of instructions that specifies how to solve a problem. Programmers use programming languages to communicate with computers as natural languages are too ambiguous. It then gives examples of payroll and grades programs that take in data and produce information. The document classifies programming languages from low-level machine language to high-level languages like C++ and Java that are easier for humans. It aims for future natural language programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
211 views

My Notes

The document discusses computer programming and programming languages. It defines a computer program as a list of instructions that specifies how to solve a problem. Programmers use programming languages to communicate with computers as natural languages are too ambiguous. It then gives examples of payroll and grades programs that take in data and produce information. The document classifies programming languages from low-level machine language to high-level languages like C++ and Java that are easier for humans. It aims for future natural language programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 38

Computer Programming I

What is a Computer Program?

Develop a n algorithm to compute and display the average of the score of


2 students on their CPROG1 MASTERY TEST1 AND MASTERY TEST2.

A computer program is a list of instructions arranged in some logical order,


which completely specifies how the computer is to solve a particular problem or perform a specific
task. The people who create computer program are called programmers.

Just as human beings communicate with each other through the use of
languages such as Filipino, English, or Chinese, programmers use a variety of
special languages called programming languages, to communicate with
the computer. The instructions in a program are stated using computer language
such as C, C#, Visual BASIC, JAVA and among others. Natural languages such as
English and Filipino are not suitable to use in computer programming because of
their ambiguity and lack of precision.
What you want the
computer to do
What you have What you need

INPUT PROCESS OUTPUT

DATA COMPUTER INFORMATION


PROGRAM

Example 1: Payroll Program


Data Information

Hourly Rate Basic Salary


Hourly Rate Basic Salary
Hours Worked Gross Pay
Hours Worked Gross Pay
Allowances Payroll Total Deductions
Allowances Payroll Total Deductions
Deductions Program Net Pay
Deductions Program Net Pay

Example 2: Grades Program


Data Information
 Exam Scores  Exam Average
 Attendance  Midterm Grade
 Other Scores Grading  Final Grade
Grading  Grade Report
 Grades Table Program
Program
Computer Programming I
1

Programming Languages
Writing a computer program requires the use of a programming
language that the computer can understand.

The native language of the computer is the machine language.


This language is based on the binary low (0) and high (1) signals that flow
SOFTWARE CONVERTS THE
within the computer machine’s circuits. Data and instructions in the machine PROGRAMS WRITTEN IN ASSEMBLY,
HIGH LEVEL, VERY HIGH LEVEL. OR
level are all expressed in terms of combinations of 0’s and 1’s only. NATURAL LANGUAGES

Programming the computer using the machine language as it was


actually done before could be very difficult. The use of abbreviations or
mnemonics instead of pure 0’s and 1’s in assembly language only partly CONVERSION
SOFTWARE
lessened the difficulty and it was still generally considered complicated to allow
greater productivity.

The use of English – like instructions in high – level procedural


languages greatly facilitated the programming of the computer. Programs
written in these languages are easier to understand and are no longer PROGRAMMER WRITES PROGRAMS
constrained by the kind of computer being programmed, thereby, making IN ASSEMBLY, HIGH LEVEL, VERY
HIGH LEVEL, OR NATURAL
them portable to other kinds of computers. LANGUAGES

The use of very high – level problem – oriented languages require only little
training in programming because they are designed to solve specific problems. To make
computer programming even a lot easier, programming is being developed to
approach that level of our natural languages.

COMPUTER EXECUTES THE


PROGRAMS IN MACHINE
LANGUAGE OR MACHINE CODE
FORM
Computer Programming I
1

These languages are summarized as follows:


GENERALIZATION LANGUAGE CHARACTERISTICS OF PROGRAMS WRITTEN IN LANGUAGE
 Instructions and data are expressed in 0's and 1's.
First Machine  Low - level. Difficult to program.
 Specific to a machine or to the computer being used.
 Abbreviations or mnemonics are used in place of pure 0's and 1's.
 Easier to understand than machine language but still low level and
Second Assembly
difficult to program.
 Specific to a machine or computer used.
 Designed to express the logic or procedure in English - like
instructions to solve general problems. A lot easier to write and
High - Level
Third understand. Examples are FORTRAN, COBOL, C, C#, Pascal, Visual
Procedural
BASIC, C++, and Java. Portable to other kinds of computers. Requires
special training.
 Designed to solve specific problems.
Very High-
 Examples are query languages which enable non - programmers to
Level
Fourth use easily understood commands, and pre-programmed applications
Problem-
Oriented generators.
 Requires less training.
 Designed to bring people closer to the computer through the use of
Fifth Natural
natural languages. Still in development stage.

HIGH
HIGH –– LEVEL
LEVEL Natural
Natural Language
Language Fifth
Fifth generation
generation
(nearer
(nearer man)
man)

Problem
Problem –– Oriented
Oriented Language
Language Fourth
Fourth generation
generation

Procedural
Procedural Language
Language Third
Third generation
generation

Assembly
Assembly Language
Language Second
Second generation
generation

LOW
LOW –– LEVEL
LEVEL
(nearer
(nearer machine)
machine) Machine
Machine Language
Language First
First generation
generation

Computer
Computer Hardware
Hardware (Machine)
(Machine)
Computer Programming I
1

Steps in Developing a Computer Program

1. Program Specification also called program definition or


program analysis, this step requires us to do the following tasks

Determine the…
a. Desired output. Ask what output information you want the
computer program to generate.
b. Input data. Ask what input data are available for processing by
the computer program.
c. Processing requirements. Knowing the input data and the
desired output information, you now define what processes are to be
performed on the input data to arrive at the desired output
information.

2. Program Design. We plan and create the solution to the problem according to the
program specifications we made in step 1.

The solution to the problem may be expressed in one of the following forms:
a. Pseudocode. This is a step – by – step narrative description of the solution in short
sentences. Pseudocode is an outline form of the program.

b. Flowchart. This graphically represents the flow of instructions in a program using


standard flowcharting symbols.

3. Program Code. In this step, we write the program solution using a computer
programming language. The coding or writing of the program is according to the program
design we made in step 2.

It is necessary to code the program solution in a form of language that the computer can
understand. Examples of computer programming languages are C, C#, Visual BASIC, JAVA
Computer Programming I
1

and among others.

4. Program Test. It is necessary for us to verify or test the correctness of


our program. There are two possible kinds of errors which might be
encountered during testing, namely:

a. Syntax Errors. These are errors arising from violations of the


rules or grammar of the chosen programming language.
b. Logic or Semantics Errors. These errors arise from wrong
assumptions or inaccurate understanding of the problem to be solved. If the program is
able to execute without syntax errors but the output did not turn out as expected, a
logic error has been committed.

Finding and removing program errors is also called


debugging.

5. Program Documentation. This consists of written


descriptions and procedures about a program and how to use it. Actually, documentation
should be done not only after coding the program but throughout all the programming steps.
d.
Program documentation may include pseudocodes, flowcharts,
source listing, data formats, sample outputs, user instructions, and
technical instructions. Documentation is important for people who
may be involved with the program in the future. These people
include the program users, operators, and programmers.

6. Program Maintenance. This is a continuing process after program implementation is


conducted to correct errors discovered later, to improve the program’s
usability, to standardize, and to adjust to organizational changes.

The purpose of program maintenance is to ensure that current


programs are operating error – free, efficiently, and effectively.

Summary of Steps in Computer Programming:


Computer Programming I
1

STEP PRIMARY ACTIVITIES


 required input
 desired output
1. Program Specification Determine...  processing requirements

2. Program Design Use...  structured programming


technique

Select...  Programming language


3. Program Code
Write...  the program

 desk check
 manual check
4. Program Test Perform...
 translation attempt
 test with sample data

 Users
5. Program Documentation Write procedure for...
 Operators
 Programmers

 Errors
 inefficient or ineffective
6. Program Maintenance Adjust for... operations
 non-standard code
 changes over time

Examples: Given the problem below, identify the problem statement (Input-Process-Output)
Problem 1: Given two scores obtained by a student in two different exams, compute the
average of these scores.

Problem Statement:

Input data – two scores (score 1 and score 2)


Output information – average of the two scores
Processes – addition of the two scores, division of the sum by 2
Problem 2: Using brief sentences specify or describe a step-by-step solution to the
Computer Programming I
1

following problem. Compute the average of the two score obtained by each of the 100
students.

Problem Statement:

Input data – two scores (score 1 and score 2) of 100 students


Output information – average of the two scores of each student
Process – addition of the two scores, division of the sum by 2

This very simple example only serves to illustrate the process of problem analysis. You don’t
really need a computer program to perform the task. The real value and power of programs will
become apparent in cases where voluminous data are to be processed more quickly and more
accurately.

DATA vs. INFORMATION


Computer Programming I
1

What is Data?

DATA is defined as a set of symbols, which are used to represent objects, events,
activities, quantities, and other entities, and which can be processed or manipulated by manual or
automatic means. Today, the computer is widely used in processing data.

Examples of DATA
Employee ID number Color Name
SSS ID Number Sex Address
Customer ID Number Product code Course
Student ID Number Unit price Amount
Tax ID Number Weight Reorder level

Processed data is often called information. Information is characterized as those that are
useful in making decisions. However, current use even in technical terms allows the interchanging of
the words data and information.

Look at this example:


In MP Corporation, having 300 employees, a certain PAYROLL PROGRAM is running to compute for the
Basic Salary, Gross Pay, Total Deductions and the Net Pay of an employee. The payroll program accepts
the following data: HOURLY RATE, HOURS WORKED, ALLOWANCES and DEDUCTIONS.

DATA INFORMATION

*Hourly Rate *Basic Salary


*Hourly Rate *Basic Salary
*Hours Worked *Gross Pay
*Hours Worked PAYROLL *Gross Pay
*Allowances PAYROLL *Total Deductions
*Allowances PROGRA *Total Deductions
*Deductions PROGRA *Net pay
*Deductions M *Net pay
M

Example 1: Enumerate all data that can be identified or inferred from the following description of a data
Computer Programming I
1

processing application.
A teacher of Asian College of Technology maintains on the computer the records of all his/her
students. These records include their complete names, course and semester level, scores in the
prelim, pre-midterm, midterm, pre-final and final exams, average of the 5 major exam scores,
midterm and final grades, their sex (male or female), and remarks on whether they passed or
not.

List of data:
Last name, first name, middle initial of student
Course, semester level
Prelim score, pre-midterm score, midterm score, pre-final score, final score
Average of 5 major exam scores
Midterm grade, final grade
Sex (male or female), remarks (passed or failed)

Example 2: Enumerate all data that you can identify or infer from the following description of a data
processing application.

ACT-HRM Restaurant is to use an information system to provide better control of all restaurant
operations and to give better service at the same time. Instead of writing down orders on a
paper pad and bringing a copy to the kitchen, the waiters would use a hand-held terminal to key
in the orders at the tables. When the order is complete, they would press a button and the order
would be transmitted into the kitchen by radio waves. At the end of the meal, the bill would be
computed and printed out automatically, including a complete listing of every item ordered. By
having these data on the computer, it would be easy to maintain sales statistics about which
items were ordered when. The sales data would also link directly to the inventory system used
for ordering food, which should help in purchasing.
List of data:
Waiter code number food code number
Waiter name food description
Order code number food sale unit
Order date food unit price
Order time food ingredient code
Order entry code food ingredient description
Order entry quantity food ingredient inventory unit
Order entry total amount food ingredient inventory level
Order total amount food ingredient reorder level
Order service time food ingredient cost
Tip amount food ingredient supplier

TYPES of DATA
Computer Programming I
1

Computer programming languages provide different types of data.

These data may be generally classified as:


a. Numeric data
b. Character or string data
c. Boolean or logical data

A numeric data has a value consisting of digits (0 – 9), positive sign (+),
negative sign (-), or decimal point (.). Currency symbols (ex. $ and ₱) and the comma
sign (as in thousand and millions) are not included in a numeric data.

A character or string data has a value consisting of alphabetic,


numeric, and other characters enclosed in quotation marks.

A Boolean or logical data has a value of either true (.T.) or false (.F.).

Data may also be classified as:


a. Constant
b. Variable

A constant is a piece of data whose value do not change during the execution of a program.

A variable is a piece of data whose value could change during the execution of a program.
Computer Programming I
1

Example 1: Study the table of data with the corresponding data type that follows.

DATA TYPE DATA TYPE


last name string pre - final score numeric
first name string final score numeric
middle initial character exam average numeric
Course string midterm grade numeric
semester level numeric final grade numeric
prelim score numeric sex (male or female) Boolean
pre - midterm score numeric remarks (passed or failed) Boolean
midterm score numeric

Example 2: Study the table of data with the corresponding data type that follows.

DATA TYPE DATA TYPE


waiter code number string food code number string
waiter name string food description string
order code number string food sale unit string
order date string food unit price numeric
order time string food ingredient code string
order entry code string food ingredient description string
order entry quantity numeric food ingredient inventory unit string
order entry total amount numeric food ingredient inventory level numeric
order total amount numeric food ingredient reorder level numeric
order service time string food ingredient cost numeric
tip amount numeric food ingredient supplier string
Computer Programming I
1

VARIABLES OR IDENTIFIERS

What are variables or identifiers?

Technically, variables are a symbolic name associated with a value and whose
associated value may be changed. Variables somewhat serve as containers, which may contain
values which are constant and which may be utilized, while the program is running or being executed.

RULES in NAMING A VARIABLE

Here are the basic rules for creating an identifier or variables:


1. A combination of alphabet characters (a – z, and A – Z),
numeric digits (0 – 9), and the underscores (_) can be used.
Identifiers or variables can be long; however, many systems
consider the first 31 characters unique.

2. The first character in the name should not be a


numeric digit.

3. No embedded space/s can be placed between the characters. This means you
cannot separate words in a name by a space. Normally you concentrate (append) second
and subsequent words onto the identifier by capitalizing the second word.

4. Being descriptive is helpful. Use meaningful names that represent the item being
described. If the identifier is used to reference a person’s age, call it age, not x. The more
descriptive your identifiers are, the easier it is for you and the others to read your code.
Computer Programming I
1

WAYS in WRITING A VARIABLE


Proper variable naming in program is important. In connection with this, programmers are
trained to use proper variable declaration and use naming conventions for better understanding of
computer programs.

Here are three ways in writing variable names:

1. Pascal Case – the first letter in the identifier and the first letter of each subsequent
concatenated word are being capitalized.
Ex. FamilyName, FirstName, MiddleInitial
2. Camel Case/Hungarian Notation – the first letter of an identifier is lowercase and
the first letter of each subsequent concatenated word is capitalized.
Ex. familyName, firstName, middleInitial
3. Uppercase – variables or identifiers use capitalization of all of its
characters
Ex. FAMILYNAME, FIRSTNAME, MIDDLEINITIAL

VALID AND INVALID VARIABLE NAMES FOR AN EMPLOYEE’S LAST NAME


Suggested variable names for
Comments
employee’s last name
employeeLastName Good
EmployeeLast Good – most people would interpret Last as meaning
Last Name
EmpLast Good—emp is short for employee
Emlstnam Legal—but cryptic
lastNameOfTheEmployeeInQuestion Legal—but awkward
last name Not legal—embedded space
employeelastname Legal—but hard to read without camel casing
Computer Programming I
1

How are values being assigned to variables or identifiers?

Assigning a value to a variable means to store that value in the


variable, hence replacing its former value. This is expressed as:

variable = value

The data type of the variable will follow the data type of the value assigned to it.

Example 1: Store the value of 18 in the variable age


age = 18

Example 2: Store the average of midterm and final in the variable average.
average = (midterm + final)/2

Example 3: Store the string value “Juan dela Cruz” in the variable name.
name = “Juan dela Cruz”

Example 4: Assign the logical value of .F. (false) to the variable done.
done = .F.
Computer Programming I
1

ALGORITHM
What is an algorithm?
Algorithms consist of steps, which describe how the
data are to be manipulated by the computer program.

PROPERTIES of an ALGORITHM
The following are properties of an algorithm:

 1Finiteness – an algorithm terminates after finite number of steps.


 Definiteness – each step is unambiguous. This means that the action specified by the step
cannot be interpreted (explain the meaning of) in multiple ways and can be performed without
any confusion.
 2Input – an algorithm accepts zero or more inputs
 3Output – it produces at least one output
 Effectiveness – it consists of basic instructions that are realizable. This means that using the
given inputs in a finite amount of time can perform the instructions.

WAYS of REPRESENTING an ALGORITHM


There are two ways to represent an algorithm.

 4Pseudocode. The steps of achieving a certain objective are being presented through text.
Sample Pseudocode:
if (AGE < 18)
DISPLAY “MINOR”
else
DISPLAY “LEGAL AGE”
Computer Programming I
1

 5Flowchart. A flowchart is a pictorial representation of the sequence of steps in an


algorithm or in a computer program.

SYMBOLS NAMES USES

Terminator Designates the start and the end of the program

Initialization Describes data to be initialized

Input Box Describes data to be inputted during program execution

Output Box Describes data to be outputted during program execution

Process box Describes how data are to be processed during program


execution

Decision Box Designates a decision to be made during program


execution

Predefined Process Designates a process whose details or steps are


Box predefined or may be defined in another flowchart

Connector Shows the connection of a flowchart segment to another


segment
Computer Programming I
1

Flow Lines Show the direction of the logic of program execution

Example: Develop an algorithm to compute and display the tuition fee of a student, given the
number of units enrolled and the tuition fee rate per unit.

Problem Statement:

Input data - number of units enrolled (UNITS), tuition rate per unit (RATE)
Output information - total tuition fee
Processes - Multiplication of number of units enrolled and tuition rate per unit

Pseudocode Flowchart

START
START

Input UNITS and RATE UNITS, RATE


UNITS, RATE

TTNFEE = UNITS * RATE


TTNFEE = UNITS * RATE
TTNFEE = UNITS * RATE

Display TTNFEE TTNFEE


TTNFEE

END
END
Computer Programming I
1

PROGRAMMING OPERATIONS AND EXPRESSIONS

ARITHMETIC OPERATIONS and EXPRESSIONS

Arithmetic operators are used in an arithmetic


expression to tell the computer how this expression/s involving numeric
data is to be evaluated into a single value. An arithmetic expression in a
program consists of one or more numeric data and arithmetic operators.

The following table contains arithmetic operators:

ARITHMETIC OPERATORS
OPERATOR OPERATION PRIORITY
Multiplication * 1
Division / 1
Modulus % 1
Addition + 2
Subtraction - 2

The computer evaluates the operator with the highest priority (1). For the same
priority, evaluation is from left to right. Operations inside parentheses () if any are
evaluated first.

Example 1: The computer will evaluate the following arithmetic expression as


10 + 6 – 11
from left to right since addition(+) and subtraction(–) have the same priority. Therefore,

10 + 6 – 11
1 2

(1) 10 + 6 = 16
(2) 16 – 11 = 5
Computer Programming I
1

Example 2: The computer will evaluate the following arithmetic expression as


2+9/3*5
starting with / and * (left to right for same priority) and then + which has a lower
priority. Therefore,

2+9/3*5
3 1 2

(1) 9/3=3
(2) 3 * 5 = 15
(3) 2 + 15 = 17

Example 3: The computer will evaluate the following arithmetic expression as


2+4%2
The modulo operation finds the remainder of division of one number by another.
Therefore,

2+4%2
2 1

(1) 4%2=0
(2) 2+0=2
Example 4: The computer will evaluate the following arithmetic expression as
((2+2)*2)%10
equation with parenthesis, the inner equation within the parenthesis should be
performed first.
Therefore,
((2+2)*2)%10
1 2 3

(1) 2+2=4
(2) 4*2=8
(3) 8 % 10 = 8
Computer Programming I
1

PROGRAMMING STRUCTURES

The program could get so messy and difficult to understand and maintain if it will
not use the structured approach.

When writing algorithms, some or all of the following situations may arise:

1. Sequence Structure. Two or more tasks are to be carried out in sequence.

2. Selection Structure. One or two tasks are to be selected depending on a specified


condition.

3. Repetition Structure. A task is to be carried out repeatedly.

These three control structures are referred to as structured programming


constructs. Any algorithm can be written by using only these constructs.

Algorithms written with only the sequence, selection, and repetition structures are called
structured algorithms. The process of writing such algorithms is called structured
programming and the resulting programs are called structured programs.

Sequence Structure

Pseudocode Flowchart

Task 1

Task 1
Task 2
Task 2

Tasks 1 and 2 are done in sequence.


Computer Programming I
1

Selection Structure
Pseudocode Flowchart

if (condition)
Task
T F
conditio
n
Task

Task is performed if condition is true (T), do nothing if false (F).


Repetition Structure
Pseudocode Flowchart

while (condition)
F
{
Task conditi
on
} T
Task

While condition is still true (T), Task 1 is repeatedly performed. Condition is tested first before Task is
performed.
The selection structure and the repetition structure may also be viewed as tasks in a sequence
structure. Hence a program may be taken as a sequence of a mixture of sequence, selection and
repetition structures.
Note that there is always 1 entry point and 1 exit point in each structure. This gives us a
way of writing our programs in modules.
Computer Programming I
1

SEQUENCE STRUCTURE

Sequence Structure is a programming structure in which it performs an


action or event, and then performs the next action in order. A sequence can contain
any number of events, but there is no chance to branch off and skip any of the events.
Once it starts a series of events in a sequence, it must continue step-by step until the
sequence ends.

Example 1: Input two numbers, compute and display the sum, difference, product and quotient.

Problem Statement:

Input data - NUM1, NUM2


Output information - sum (SUM), difference (DIFF), product (PROD) and
Quotient (QUOT)
Processes - To get the following:
1. SUM – add NUM1 and NUM2
2. DIFF – subtract NUM1 and NUM2
3. PROD – multiply NUM1 and NUM2
4. QUOT – divide NUM1 and NUM2

Pseudocode Flowchart START


START

NUM1,
Input NUM1 and NUM2 NUM1,
NUM2
NUM2

SUM = NUM1 + NUM2


SUM = NUM1 + NUM2
DIFF = NUM1 – NUM2 SUM
DIFF = NUM1
= NUM1 + NUM2
– NUM2
DIFF = NUM1 – NUM2
PROD = NUM1 * NUM2 PROD = NUM1 * NUM2
PROD= =NUM1
NUM1/ NUM2
* NUM2
QUOT
QUOT = NUM1 / NUM2 QUOT = NUM1 / NUM2

Display SUM, DIFF, PROD, SUM, DIFF, PROD,


SUM, DIFF, PROD,
QUOT
QUOT QUOT

Example 2: 1 Kilometer has 1000 meters. Given a distance in meters, compute and display the

END
END
Computer Programming I
1

distance in kilometers.

Problem Statement:

Input data – distance in meters (METERS)


Output information – distance in kilometers (DIST)
Processes – division of distance in meters and distance in kilometers

Pseudocode Flowchart

START
START

METERS
METERS
Input METERS

DIST = METERS / 1000 DIST = METERS/ 1000


DIST = METERS/ 1000

Display DIST
DIST
DIST

END
END

Programming Operations and Expressions


Computer Programming I
1

RELATIONAL OPERATIONS and EXPRESSIONS

Relational operators are used in relational


expression/s to compare the values of any two expressions. A
relational expression will evaluate to a logical value of either true
(.T.) or false (.F.). A true or false expression is also called a logical
expression or condition.

RELATIONAL OPERATORS
OPERATOR OPERATION PRIORITY
== Equal to (the same as) 1
Equality
!= Not equal to (not the same as) 1
Greater than (more, bigger, larger, higher, longer
> 1
than, exceeds, over)
Less than (smaller, fewer, lower, shorter than,
Relational < 1
below)
>= Greater than or equal to (at least) 1
<= Less than or equal to (at most) 1
The computer evaluates first the operator with the highest priority (1). For the same
priority, evaluation is from left to right. Operations inside parentheses () if any are
evaluated first.

Example: The following are examples of relational expressions and their use.

Relational Expression Used To Determine If

score > 90 score literal value is over 90


surName = “dela Cruz” surName literal value is “dela Cruz”
age <= 17 age literal value is below or equal to 17
course != ”BSIT” course literal value is not “BSIT”
sales >= 50000 sales has reached the quota of ₱50000.00
failed != .T. failed is not true(.T.)
LOGICAL OPERATIONS and LOGICAL EXPRESSIONS
Computer Programming I
1

Logical operators are used in connection with true (.T.) or false


(.F.) relational expressions that compare the values of some data.

Logical operators evaluate Boolean expressions and


return a Boolean value. A logical expression, which consists of
one or more relational expressions and logical operators, will also evaluate
to either true or false.

Logical expressions and relational expressions are the same in the sense that
they both represent true or false logical conditions.

LOGICAL OPERATORS
OPERATOR OPERATION PRIORITY
.NOT. Negation 1
.AND. Logical Multiplication 2
.OR. Logical Addition 3
The computer evaluates first the operator with the highest priority (1). For
same priority, evaluation is from left to right. Operations inside
parentheses () if any are evaluated first.

.NOT. reverses the logical value of a relational expression while .AND. and .OR. are used to
combine two or more relational expressions into a single true or false logical condition.
Please study the table that follows:

A B .NOT. A .NOT B A .AND. B A .OR. B


.F. .F. .T. .T. .F. .F.
.F. .T. .T. .F. .F. .T.
.T. .F. .F. .T. .F. .T.
.T. .T. .F. .F. .T. .T.

SELECTION STRUCTURE
One of the most significant structures in
Computer Programming I
1

programming is the selection structure. In selection structure, users are instructed to choose
from the given options.

There are several ways to represent these choices or options and these are the following:
 One – way selection structure
 Two – way selection structure
 Multiple selection structure

ONE – WAY SELECTION STRUCTURE


In one – way selection structure , a user is given a certain condition wherein he is
allowed to choose. As the user has chosen, his response will then be evaluated. If the response satisfies
the condition, then, a certain task will be done.

One – way selection structure is best illustrated in the given flowchart that follows:
Pseudocde Flowchart

if (condition) T
F
Task conditio
n
Task

As you can see in the algorithm, if a


certain condition is being satisfied a
certain task will initiate but if the
condition is not met, nothing will happen.
Example:Write an algorithm that determines if the
input number is zero or positive.

Problem Statement:

Input data – NUM


Computer Programming I
1

Output information – Message “Positive Number”


Processes – if NUM >= 0, display “Positive Number”

Pseudocode Flowchart

START
START
Input NUM

if (NUM>=0) NUM
NUM
display “Positive Number”

F
NUM
NUM>=>=
00
T

“Positive
“PositiveNumber”
Number”

END
END

TWO – WAY SELECTION STRUCTURE


In two – way selection structure , a user will be given two choices in a certain
situation wherein he is allowed to choose one, not both, from the two (2) choices.
Computer Programming I
1

Two – way selection structure is best explained by the flowchart below:

Pseudocode Flowchart

if (condition)
Task 1
else T F
conditio
Task2 n
Task 1 Task 2

As shown in the flowchart, a single condition is coupled with two tasks – one task (Task 1) is to be done
when the requirement is met; otherwise, another task, which is Task 2, will be executed.

Example: Write an algorithm that determines if the input number is NON_NEGATIVE or NEGATIVE.

Problem Statement:

Input data – NUM


Computer Programming I
1

Output information – Message “NON_NEGATIVE” or “NEGATIVE”


Processes – NUM >= 0, display “NON_NEGATIVE” otherwise display
“NEGATIVE”

Pseudocode Flowchart

START
START

Input NUM

NUM
NUM
if (NUM>=0)
display “NON_NEGATIVE”
else T F
NUM
display “NEGATIVE” NUM>=>=
00

“NON_NEGATIVE” “NEGATIVE”
“NON_NEGATIVE” “NEGATIVE”

END
END

MULTIPLE/NESTED-IF SELECTION STRUCTURE


multiple selection structure, as the word implies, this structure simply means that
In
three (3) or more selections are given in a single situation.
Nested-If Statement is another form of a conditional statement that performs an “if
within an if statement” process. Use a nested if statement when performing another set of condition
Computer Programming I
1

within a given set of condition.

Study the flowchart below which supports the multiple selection structure.

Pseudocode Flowchart

if (condition 1)
T F
Task Condition
else if (condition 2) 1

Task Task 1 T condition F


2
.
Task 2 Task 3
.
.
else
Task

Example: Write a program that examines the value of a variable called Temp. Then Display the
following messages depending on the value assigned to Temp.
Temperature Message
Less than 0 ICE
Between 0 and 100, inclusive WATER
Exceeds 100 STEAM
Computer Programming I
1

Problem Statement:

Input data – Temp


Output information – “ICE”, “WATER”, “STEAM”
Processes – Temp < 0, display “ICE” Temp > 100, display “STEAM”,
otherwise display “WATER”

Pseudocode Flowchart

START
START

Input Temp
Temp
Temp
if (Temp < 0)
display “ICE”
else if (Temp > 100) Temp < T “ICE”
Temp < “ICE”
0
display “STEAM” 0
F
else
display “WATER” T
Temp >
Temp > “STEAM”
100 “STEAM”
100
F
“WATER”
“WATER”

END
END
INCREMENTATION and DECREMENTATION
INCREMENTATION or to increment the value of a numeric variable means
to increase the value stored in that variable by a certain specified number. This is
expressed as:
variable = variable + increment
Computer Programming I
1

This means that the new value of the variable is equal to its previous value plus the increment.
Example: Increment the value of age with the value of 5.
age = age + 5

DECREMENTATION or to decrement the value of a numeric variable


means to decrease the value stored in that variable by a certain specified number.
This is expressed as:
variable = variable – decrement
This means that the new value of the variable is equal to its previous value minus the
decrement.
Example: Decrement the value of age by 3.
age = age – 3

STRUCTURED PROGRAMMING
REPETITION STRUCTURE
Repetition structure is a repeating process while condition is
still true (.T.). A very good example of it is when you try to hop 100 times
using a jumping rope. You reach the count of 100 as you are doing the same
thing and that is hopping or jumping. You may also refer to a runner. As the
athlete goes around the oval, he is doing the same thing and that is running
around the oval.
Repetition structure is best illustrated in two ways and these are:
 Pre test
 Post test
TESTING CONDITION BEFORE TASK
Pretest repetition structure is a repetition structure wherein the condition is
being evaluated first before a certain task is executed. Pretest repetition structure is illustrated
below:
Computer Programming I
1

Pseudocode Flowchart
while (condition)
{
Task
F
} conditi
on
T
Task

USING THE WHILE STATEMENT


Probably the simplest and most frequently used loop structure to write is the While
statement. The general form of the While statement is.
while (conditional expression)
{
statement(s);
}

The conditional expression, sometimes called the loop condition, is a logical condition to
be tested. It is enclosed in parentheses and is similar to the expressions you use for selection
statement. The conditional expression must be Boolean deciding true or false. An interpretation of
the While statement is “while condition is true, perform statement(s).”
The statement following the conditional expression makes up the body of the loop. The body of
the loop is performed as long as the conditional expression evaluates the true. Like the selection
construct, the statement following the conditional expression can be a single statement.

USING THE FOR LOOP STATEMENT


For Loop is a statement which allows code to be repeatedly executed. It is classified as an
iteration statement. The general form of the For Loop statement is.
for (initialization; condition; loop expression)
{
Computer Programming I
1

statement(s)
}

The For Loop executes a statement or a block of statements repeatedly until a specified
expression evaluates to false. The For Loop is useful for iterating over arrays and for sequential
processing. Unlike many other kinds of loops, such as the While Loop, the For Loop is often
distinguished by an explicit loop counter or loop variable. This allows the body of the For Loop (the
code that is being repeatedly executed) to know about the sequencing of each iteration. For Loops
are also typically used when the number of iterations is known before entering the loop. For Loops
are the shorthand way to make loops when the number of iterations is known.

Example: Write an algorithm that generates the given sequence numbers. (Pretest)
Sequence numbers
1 2 3 4 5
Pseudocode Flowchart
START
START

CTR = 1
CTR = 1
CTR = 1
while (CTR <= 5)
F
{ CTR <=
CTR <=
5
display CTR 5
T
CTR = CTR + 1 CTR
CTR
}

CTR = CTR + 1
CTR = CTR + 1

END
TESTING CONDITION AFTER TASK END

Post – test repetition structure is a repetition structure wherein the task is being
executed first before the condition is evaluated. Post – test repetition structure is illustrated in the
flowchart that follows:

Pseudocode Flowchart

Task

T
conditio
n
F
Computer Programming I
1

do
{
Task
}
while (condition)

Example: Write an algorithm that generates the given sequence numbers. (Post-test)
Sequence numbers
1 2 3 4 5

START
START

CTR
CTR==00

CTR
Pseudocode CTR==CTR
CTR+Flowchart
+11

CTR = 0
do CTR
CTR
{

T
CTR
CTR<=4
<=4

END
END
Computer Programming I
1

CTR = CTR + 1
display CTR
}
while (CTR <= 4)

DEFINITE NUMBER OF REPETITIONS


In every repetition structure, there is an initial value and a final value which will define
certain number of loops or repetition.

Counter/Sentinel/State Controlled Loop

COUNTER-CONTROLLED LOOP
This is when the loop may be executed a specified number of times.
With a counter-controlled loop, a variable simulating a counter is used as the
loop control variable to keep track of the number of iterations.
Many programs you develop require that you write one or more
Computer Programming I
1

statements that must be performed more than once. When you know the number of times the
statements must be executed, you can create a counter-controlled loop.
Example:

Pseudocode Flowchart
ctr = 1
ctr = 1
if (ctr <= 5)
{ F
ctr <= 5
ctr = ctr + 1
} T
ctr = ctr + 1

ctr

In this example, the initial value of ctr is literally 1. After initialization, a condition box follows
which sets the value as to how many repetitions are to be executed.

SENTINEL-CONTROLLED LOOP

SENTINEL-CONTROLLED LOOP is a type of loop that is


terminated by entering or encountering a sentinel value. Sentinel-controlled
loops are often used for inputting data when you do not know the exact
number of values to be entered. If your program inputs multiple homework
scores, for example, you might display a message telling the users to enter a
negative value to indicate they are finished entering scores. You would never
have a negative score; thus, this would be an appropriate sentinel value.
Sentinel-controlled loops are also referred to as indefinite loops, because the number of
repetitions is not known before the loop’s execution. To design an indefinite loop, select a sentinel
value to use in the expression. A sentinel value is an extreme value, a dummy value. It is a value that
should not be processed—like a negative value when only positive scores are to be processed.
The sentinel value is used as the operand in the conditional expression for an indefinite
loop. A sentinel-controlled loop gives you the advantage of not needing to know how many times the
loop will be performed. When all the data has been processed, the sentinel value can be entered
Computer Programming I
1

indicating the loop should terminate normally.

NESTED LOOP(Pre final boundary)


A nested loop is a logical structure used in computer programming where two repeating
statements are placed in a "nested" form, i.e., one loop is situated within the body of the other. In a
nested loop, the first iteration of the outer loop causes the inner loop to execute. The inner loop then
repeats for as many times as is specified. When the inner loop completes, the outer loop is executed
for its second iteration, triggering the inner loop again, and so on until the requirements for the outer
loop are complete.

Example: Write an algorithm that print the multiplication table

Pseudocode

ROW = 1
PRODUCT = 0
while (ROW <= 10)
{
COL = 1
while (COL <= 10)
{
PRODUCT = ROW * COL
Display PRODUCT
COL = COL + 1
` }
ROW = ROW + 1

Flowchart

START
START

ROW
ROW==11
PRODUCT
PRODUCT==00

ROW
ROW<=<=
10
10
T END
END
COL
COL<= 110
COL
PRODUCT
COL ===<=
PRODUCT
COL COL
ROW110++*1*1COL
=COL
PRODUCT
PRODUCT
COL ROW COL ROW
T F ROW==ROW
ROW++11

You might also like