Module 2 Basic Program Logic
Module 2 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
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.
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:
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.
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.
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:
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.
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.
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.