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

Module 2 Basic Program Logic

Uploaded by

adrianniel.garig
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Module 2 Basic Program Logic

Uploaded by

adrianniel.garig
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

Basic Program Logic

The most powerful tool we have for communication is language. This is true whether we are considering
communication between two humans, between a human programmer and a computer, or between a
network of computers. In computing, we use language to describe procedures and use machines to turn
descriptions of procedures into executing processes.

Language is a set of surface forms and meanings, and a mapping between the surface forms and their
associated meanings
Natural Language is a language spoken by humans which is very complex since they have evolved over
many thousand years of individual and cultural interaction. We focus on designed languages that are
created by humans for some a specific purpose such as for expressing procedures to be executed by
computers such as: string is a sequence of string zero or more characters. Each character is a symbol
drawn from a finite set known as an alphabet.

Components of Language
• primitives — the smallest units of meaning.
• means of combination — rules for building new language elements by combining simpler
 means of abstraction - allow us to give a simple name to a complex entity

A grammar is a set of rules for generating all strings in the language.

Natural languages, such as English, work adequately (most, but certainly not all, of the time) for human-
human communication, but are not well-suited for human-computer or computer-computer
communication. Why can’t we use natural languages to program computers? Next, we survey several of
the reasons for this. We use specifics from English, although all natural languages suffer from these
problems to varying degrees.

Complexity. Although English may seem simple to you now, it took many years of intense effort (most of
it subconscious) for you to learn it. Despite using it for most of their waking hours for many years, native
English speakers know a small fraction of the entire language. The Oxford English Dictionary contains
615,000 words, of which a typical native English speaker knows about 40,000.

Ambiguity. Not only do natural languages have huge numbers of words, most words have many
different meanings. Understanding the intended meaning of an utterance requires knowing the context,
and sometimes pure guesswork.

Irregularity. Because natural languages evolve over time as different cultures interact and speakers
misspeak and listeners mishear, natural languages end up a morass of irregularity. Nearly all grammar
rules have exceptions. For example, English has a rule that we can make a word plural by appending an
s. The new word means “more than one of the original word’s meaning”. This rule works for most
words: word 7→ words, language 7→ languages, person 7→ persons.
It does not work for all words, however. The plural of goose is geese (and gooses is not an English
word), the plural of deer is deer (and deers is not an English word), and the plural of beer is
controversial (and may depend on whether you speak American English or Canadian English).
These irregularities can be charming for a natural language, but they are a constant source of difficulty
for non-native speakers attempting to learn a language. There is no sure way to predict when the rule
can be applied, and it is necessary to memorize each of the irregular forms.

Uneconomic. It requires a lot of space to express a complex idea in a natural language. Many
superfluous words are needed for grammatical correctness, even though they do not contribute to the
desired meaning. Since natural languages evolved for everyday communication, they are not well suited
to describing the precise steps and decisions needed in a computer program.

Limited means of abstraction. Natural languages provide small, fixed sets of pronouns to use as means
of abstraction, and the rules for binding pronouns to meanings are often unclear. Since programming
often involves using simple names to refer to complex things, we need more powerful means of
abstraction than natural languages provide.

Programming Languages
For programming computers, we want simple, unambiguous, regular, and economical languages with
powerful means of abstraction. A programming language is a language that is designed to be read and
written by humans to create programs that can be executed by computers.
Programming languages come in many flavors. It is difficult to simultaneously satisfy all desired
properties since simplicity is often at odds with economy. Every feature that is added to a language to
increase its expressiveness incurs a cost in reducing simplicity and regularity.
Another reason there are many different programming languages is that they are at different levels of
abstraction. Some languages provide programmers with detailed control over machine resources, such
as selecting a particular location in memory where a value is stored. Other languages hide most of the
details of the machine operation from the programmer, allowing them to focus on higher level actions.
Ultimately, we want a program the computer can execute. This means at the lowest level we need
languages the computer can understand directly. At this level, the program is just a sequence of bits
encoding machine instructions. Code at this level is not easy for humans to understand or write, but it is
easy for a processor to execute quickly. The machine code encodes instructions that direct the processor
to take simple actions like moving data from one place to another, performing simple arithmetic, and
jumping around to find the next instruction to execute.

The computer’s processor is designed to execute very simple instructions like jumping, adding two small
numbers, or comparing two values. This means each instruction can be executed very quickly. A typical
modern processor can execute billions of instructions in a second.5 Until the early 1950s, all
programming was done at the level of simple instructions. The problem with instructions at this level is
that they are not easy for humans to write and understand, and you need many simple instructions
before you have a useful program.

A compiler is a computer program that generates other programs. It translates an input program written
in a high-level language that is easier for humans to create into a program in a machine-level language
that can be executed by the computer. Admiral Grace Hopper developed the first compilers in the
1950s.

An alternative to a compiler is an interpreter. An interpreter is a tool that translates between a higher-


level language and a lower-level language, but where a compiler translates an entire program at once
and produces a machine language program that can be executed directly, an interpreter interprets the
program a small piece at a time while it is running. This has the advantage that we do not have to run a
separate tool to compile a program before running it; we can simply enter our program into the
interpreter and run it right away. This makes it easy to make small changes to a program and try it again,
and to observe the state of our program as it is running. One disadvantage of using an interpreter
instead of a compiler is that because the translation is happening while the program is running, the
program executes slower than a compiled program. Another advantage of compilers over interpreters is
that since the compiler translates the entire program it can also analyze the program for consistency
and detect certain types of programming mistakes automatically instead of encountering them when
the program is running (or worse, not detecting them at all and producing unintended results). This is
especially important when writing critical programs such as flight control software — we want to detect
as many problems as possible in the flight control software before the plane is flying!

A Scheme program is composed of expressions and definitions. An expression is a syntactic element


that has a value. Expressions may be primitives. Scheme also provides means of combination for
producing complex expressions from simple expressions.

A. Primitives An expression can be replaced with a primitive:


Expression ::⇒ PrimitiveExpression
As with natural languages, primitives are the smallest units of meaning.
Scheme provides many different primitives. Three useful types of primitives are
described next: numbers, Booleans, and primitive procedures
a1. Numbers. Numbers represent numerical values. Scheme provides all the kinds of
numbers you are familiar with including whole numbers, negative numbers, decimals,
and rational numbers.
a2. Booleans. Booleans represent truth values. There are two primitives for representing true
and false
a3. Primitive Procedures. Scheme provides primitive procedures corresponding to many
common functions. Mathematically, a function is a mapping from inputs function to outputs.
For each valid input to the function, there is exactly one associated output. For example, + is
a procedure that takes zero or more inputs, each of which must be a number. Its output is
the sum of the values of the inputs.
Table 1: Selected Scheme Primitive Procedures

Most simple computer programs include steps that perform input, processing, and output. Suppose you
want to write a computer program to double any number you provide. You can write the program in a
programming language such as Visual Basic or Java, but if you were to write it using English-like
statements, it would look like this:

The number-doubling process includes three instructions:


- The instruction to input myNumber is an example of an input operation. When the computer
interprets this instruction, it knows to look to an input device to obtain a number. When the
number is retrieved from an input device, it is placed in the computer’s memory in a variable
named myNumber.
Variable is a named memory location whose value can vary— for example, the value of
myNumber might be 3 when the program is used for the first time and 45 when it is used the
next time.
- The instruction set myAnswer = myNumber * 2 is an example of a processing operation. In most
programming languages, an asterisk is used to indicate multiplication, so this instruction means
“Change the value of the memory location myAnswer to equal the value at the memory location
myNumber times two.
- In the number-doubling program, the output myAnswer instruction is an example of an output
operation. Within a particular program, this statement could cause the output to appear on the
monitor (which might be a flat-panel plasma screen or a smartphone display), or the output
could go to a printer (which could be laser or ink-jet), or the output could be written to a disk or
DVD. The logic of the output process is the same no matter what hardware device you use.
When this instruction executes, the value stored in memory at the location named myAnswer is
sent to an output device.

Pseudo code
- A term which is often used in programming and algorithm based fields. It is a methodology that
allows the programmer to represent the implementation of an algorithm.
- is a false code or a representation of code which can be understood by even a layman with some
school level programming knowledge.
- Algorithm: It’s an organized logical sequence of the actions or the approach towards a
particular problem. A programmer implements an algorithm to solve a problem. Algorithms are
expressed using natural verbal but somewhat technical annotations. Pseudo code: It’s simply an
implementation of an algorithm in the form of annotations and informative text written in plain
English. It has no syntax like any of the programming language and thus can’t be compiled or
interpreted by the computer.

Advantages of Pseudocode
- Improves the readability of any approach. It’s one of the best approaches to start
implementation of an algorithm.
- Acts as a bridge between the program and the algorithm or flowchart. Also works as a rough
documentation, so the program of one developer can be understood easily when a pseudo code
is written out. In industries, the approach of documentation is essential. And that’s where a
pseudo-code proves vital.
- The main goal of a pseudo code is to explain what exactly each line of a program should do,
hence making the code construction phase easier for the programmer.

How to write a Pseudo-code


- Arrange the sequence of tasks and write the pseudocode accordingly.
- Start with the statement of a pseudo code which establishes the main goal or the aim. Example:
- This program will allow the user to check the number whether it's even or odd.
- The way the if-else, for, while loops are indented in a program, indent the statements likewise,
as it helps to comprehend the decision control and execution mechanism. They also improve the
readability to a great extent.
- Use appropriate naming conventions. The human tendency follows the approach to follow what
we see. If a programmer goes through a pseudo code, his approach will be the same as per it, so
the naming must be simple and distinct.
- Use appropriate sentence casings, such as CamelCase for methods, upper case for constants and
lower case for variables.
- Elaborate everything which is going to happen in the actual code. Don’t make the pseudo code
abstract.
- Use standard programming structures such as ‘if-then’, ‘for’, ‘while’, ‘cases’ the way we use it in
programming.
- Check whether all the sections of a pseudo code is complete, finite and clear to understand and
comprehend.
- Don’t write the pseudo code in a complete programmatic manner. It is necessary to be simple to
understand even for a layman or client, hence don’t incorporate too many technical terms.

Understanding Unnamed, Literal Constants and their Data Types

All programming languages support two broad data types;


i. numeric - is one that can hold digits and have mathematical operations performed on it. It describes data
that consists of numbers
ii. string- can hold text, such as letters of the alphabet, and other special characters, such as punctuation
marks. It describes data that is nonnumeric.

Most programming languages support several additional data types, including multiple types for numeric values
that are very large or very small and for those that do and do not have fractional decimal digits. Languages such as
C++, C#, Visual Basic, and Java distinguish between integer (whole number) numeric variables and floating-point
(fractional) numeric variables that contain a decimal point. (Floating-point numbers are also called real numbers.)
When you use a specific numeric value, such as 43, within a program, you write it using the digits and no quotation
marks. A specific numeric value is often called a numeric constant (or literal numeric constant) because it does not
change—a 43 always has the value 43. When you store a numeric value in computer memory, additional characters
such as dollar signs and commas are not input or stored. Those characters can be added to output for readability,
but they are not part of the number.
A specific text value, or string of characters, such as “Amanda”, is a string constant (or literal string constant).
String constants, unlike numeric constants, appear within quotation marks in computer programs. String values are
also called alphanumeric values because they can contain alphabetic characters as well as numbers and other
characters.

For example,
“$3,215.99 U.S.”, including the dollar sign, comma, periods, letters, and numbers, is a string.
Although strings can contain numbers, numeric values cannot contain alphabetic characters.
The numeric constant 43 and the string constant “Amanda” are examples of unnamed constants—they do
not have identifiers like variables do.

Variables are named memory locations whose contents can vary or differ over time. At any moment in time, a
variable holds just one value. The ability of variables to change in value is what makes computers and
programming worthwhile. Because one memory location can be used repeatedly with different values, you can
write program instructions once and then use them for thousands of separate calculations.
In most programming languages, before you can use any variable, you must include a declaration for it. A
declaration is a statement that provides a data type and an identifier for a variable. An identifier is a program
component’s name. A data item’s data type is a classification that describes the following:
 What values can be held by the item
 How the item is stored in computer memory
 What operations can be performed on the item

When you declare a variable, you provide both a data type and an identifier. Optionally, you can declare a starting
value for any variable. Declaring a starting value is known as initializing the variable. In many programming
languages, if you declare a variable and do not initialize it, the variable contains an unknown value until it is
assigned a value. A variable’s unknown value commonly is called garbage.

Naming Variables
As a programmer, you choose reasonable and descriptive names for your variables. The language translator
(interpreter or compiler) then associates the names you choose with specific memory addresses. Every computer
programming language has its own set of rules for creating identifiers. Most languages allow letters and digits
within identifiers. Some languages allow hyphens in variable names, such as hourly-wage, and some allow
underscores, as in hourlywage. Some languages allow dollar signs or other special characters in variable names (for
example, hourly$); others allow foreign-alphabet characters, such as π or Ω. Each programming language has a few
(perhaps 100 to 200) reserved keywords that are not allowed as variable names because they are part of the
language’s syntax.
For example, the data type names in a language, such as num and string, would not be allowed as variable names.
When you learn a programming language, you will learn its list of keywords. Different languages put different
limits on the length of variable names, although in general, the length of identifiers in newer languages is virtually
unlimited. In the oldest computer languages, all variable names were written using all uppercase letters because
the keypunch machines used at that time created only uppercase letters. In most modern languages, identifiers are
case sensitive, so HoUrLyWaGe, hourlywage, and hourlyWage are three separate variable names. Programmers
use multiple conventions for naming variables, often depending on the programming language or standards
adopted by their employers. Quick Reference 2-1 describes commonly used variable naming conventions.

The variable names used generally follows 0nly three rules:


1. Variable names must be one word. The name can contain letters, digits, hyphens, or underscores. No
language allows embedded spaces in variable names, and most do not allow punctuation such as periods,
commas, or colons. This book uses only alphabetic letters, digits, and underscores in variable names.
Therefore, r is a legal variable name, as are rate and interestRate. The variable name interest rate is not
allowed because of the space.
2. Variable names must start with a letter. Some programming languages allow variable names to start with
a nonalphabetic character such as an underscore. Almost all programming languages prohibit variable
names that start with a digit. This book follows the most common convention of starting variable names
with a letter.
3. Variable names should have some appropriate meaning. This is not a formal rule of any programming
language. When computing an interest rate in a program, the computer does not care if you call the
variable g, u84, or fred. As long as the correct numeric result is placed in the variable, its actual name
doesn’t matter. However, it’s much easier to follow the logic of a statement like set interestEarned =
initialInvestment * interestRate than a statement like set f = i * r or set someBanana = j89 *
myFriendLinda. When a program requires changes, which could be months or years after you write the
original version, you and your fellow programmers will appreciate clear, descriptive variable names in
place of cryptic identifiers.
Assigning Values to Variables
When you create a flowchart or pseudocode for a program that doubles numbers, you can include a
statement such as the following:
set myAnswer = myNumber * 2
Such a statement is an assignment statement. This statement incorporates two actions. First, the computer
calculates the arithmetic value of myNumber * 2. Second, the computed value is stored in the myAnswer
memory location. The equal sign is the assignment operator. The assignment operator is an example of a
binary operator, meaning it requires two operands—one on each side. (An operand is simply a value used by
an operator.) The assignment operator always operates from right to left, which means that it has right-
associativity or right-to-left associativity. This means that the value of the expression to the right of the
assignment operator is evaluated first, and then the result is assigned to the operand on the left. The operand
to the right of an assignment operator must be a value—for example, a named or unnamed constant or an
arithmetic expression. The operand to the left of an assignment operator must be a name that represents a
memory address—the name of the location where the result will be stored.

In each case, the expression to the right of the assignment operator is evaluated and stored at the location
referenced on the left side. The result to the left of an assignment operator is called an Lvalue. The L is for left.
Lvalues are always memory address identifiers. Type-safety is the feature of some programming languages
that prevents assigning values of an incorrect data type. You can assign data to a variable only if it is the
correct type.

The following are invalid because the type of data being assigned does not match the variable type:

Declaring Named Constants


Besides variables, most programming languages allow you to create named constants. A named constant is similar
to a variable, except it can be assigned a value only once. You use a named constant when you want to assign a
useful name for a value that will never be changed during a program’s execution. Using named constants makes
your programs easier to understand by eliminating magic numbers. A magic number is an unnamed constant, like
0.06, whose purpose is not immediately apparent.

For example, if a program uses a sales tax rate of 6 percent, you might want to declare a named constant as
follows:
num SALES_TAX_RATE = 0.06
After SALES_TAX_RATE is declared, the following statements have identical meaning:
taxAmount = price * 0.06
taxAmount = price * SALES_TAX_RATE

The way in which named constants are declared differs among programming languages. It follows the convention
of using all uppercase letters in constant identifiers, and using underscores to separate words for readability. Using
these conventions makes named constants easier to recognize. In many languages a constant must be assigned its
value when it is declared, but in some languages a constant can be assigned its value later. In both cases, however,
a constant’s value cannot be changed after the first assignment.

Performing Arithmetic Operations


Most programming languages use the following standard arithmetic operators:
+ (plus sign)—addition
– (minus sign)—subtraction
* (asterisk)—multiplication
/ (slash)—division
Many languages also support additional operators that calculate the remainder after division, raise a number to a
power, manipulate individual bits stored within a value, and perform other operations. Each of the standard
arithmetic operators is a binary operator; that is, each requires an expression on both sides.
In programming languages, you can combine arithmetic statements. When you do, every operator follows rules of
precedence (also called the order of operations) that dictate the order in which operations in the same statement
are carried out. The rules of precedence for the basic arithmetic statements are as follows:
 Expressions within parentheses are evaluated first. If there are multiple sets of parentheses, the
expression within the innermost parentheses is evaluated first.
 Multiplication and division are evaluated next, from left to right.
 Addition and subtraction are evaluated next, from left to right.
The assignment operator has a very low precedence. Therefore, in a statement such as d=e*f+g, the operations on
the right of the assignment operator are always performed before the final assignment to the variable on the left.

For example, consider the following two arithmetic statements:


firstAnswer = 2 + 3 * 4
= (2 + 3) * 4
After these statements execute, the value of firstAnswer is 14. According to the rules of precedence,
multiplication is carried out before addition, so 3 is multiplied by 4, giving 12, and then 2 and 12 are added, and 14
is assigned to firstAnswer. The value of secondAnswer, however, is 20, because the parentheses force the
contained addition operation to be performed first. The 2 and 3 are added, producing 5, and then 5 is multiplied by
4, producing 20.
Forgetting about the rules of arithmetic precedence, or forgetting to add parentheses when you need
them, can cause logical errors that are difficult to find in programs. For example, the following statement might
appear to average two test scores:
average = score1 + score2 / 2

However, it does not. Because division has a higher precedence than addition, the preceding statement
takes half of score2, adds it to score1, and stores the result in average. The correct statement is:
average = (score1 + score2) / 2

All the arithmetic operators have left-to-right associativity. This means that operations with the same precedence
take place from left to right.

Understanding the Advantages of Modularization


Programmers seldom write programs as one long series of steps. Instead, they break down their
programming problems into smaller units and tackle one cohesive task at a time. These smaller units are modules.
Programmers also refer to them as subroutines, procedures, functions, or methods; the name usually reflects the
programming language being used. A main program executes a module by calling it. To call a module is to use its
name to invoke the module, causing it to execute.

The process of breaking down a large program into modules is modularization; computer scientists also
call it functional decomposition. You are never required to modularize a large program to make it run on a
computer, but there are at least three reasons for doing so:
 Modularization provides abstraction.
Programmer to see the “big picture.” Abstraction is the process of paying attention to important properties
while ignoring nonessential details. Abstraction is selective ignorance. Life would be tedious without
abstraction.
Likewise, some level of abstraction occurs in every computer program. Fifty years ago, a programmer had to
understand the low-level circuitry instructions the computer used. But now, newer high-level programming
languages allow you to use English-like vocabulary in which one broad statement corresponds to dozens of
machine instructions. No matter which high-level programming language you use, if you display a message
on the monitor, you are never required to understand how a monitor works to create each pixel on the
screen.
 Modularization helps multiple programmers to work on a problem.
When you divide any large task into modules, you gain the ability to more easily divide the task among various
people. Rarely does a single programmer write a commercial program that you buy. Consider any word-
processing, spreadsheet, or database program you have used. Each program has so many options, and
responds to user selections in so many possible ways, that it would take years for a single programmer to
write all the instructions.
 Modularization allows you to reuse work more easily.
If a module is useful and well written, you may want to use it more than once within a program or in other
programs. Reliability is the feature of programs that assures you a module has been proven to function
correctly. Reliable software saves time and money.

You might also like