CHAPTER 11 - Introduction to Programming Languages
CHAPTER 11 - Introduction to Programming Languages
Chapter-
11
Introduction to Programming
Languages
236
Computer literacy Program… Introduction to Programming Languages
Introduction to Programming
What is a Program?
A computer is a tool for solving problems with data.
A program is a sequence of instructions that tell a computer how to do a task. When a computer follows the
instructions in a program, we say it executes the program.
A computer will only do what you tell it to do. This might make programming frustrating at first, but it's
relieving in a way: if you do everything right, you know exactly what the computer is going to do, because you
told it.
Computers
are machines, and at the most basic level, they are a collection of switches—where 1 represents "on" and 0
represents "off". Everything that a computer does is implemented in this most basic of all numbering
systems—binary. If you really wanted to tell a computer what to do directly, you'd have to talk to it in binary,
giving it coded sequences of 1s and 0s that tell it which instructions to execute. However, this is nearly
impossible.
237
Computer literacy Program… Introduction to Programming Languages
Programming languages are the method used to instruct a computer on how to accomplish a task.
A programming language is a collection of operators and instructions, with specific rules or syntax regarding
how the instructions are placed together. Various operations can be combined in an almost infinite number of
ways to achieve the tasks we want the computer to perform.
Some programming languages are bound to a particular set of hardware, commonly called "low level"
languages. An example of a low level language is Assembly, where the target is for a particular CPU
238
Computer literacy Program… Introduction to Programming Languages
instruction set. Other languages are more abstract from the hardware, and are known as "high level" languages.
An example of a high level language is Java.
a. Machine Language
This is the language (in the form of 0’s and 1’s, called binary numbers) understood directly by the
computer. It is machine dependent. It is difficult to learn and even more difficult to write programs.
b. Assembly Language
This is the language where the machine codes comprising of 0’s and 1’s are substituted by symbolic
codes (called mnemonics) to improve their understanding. It is the first step to improve programming
structure. Assembly language programming is simpler and less time consuming than machine level
programming, it is easier to locate and correct errors in assembly language than in machine language
programs. It is also machine dependent. Programmers must have knowledge of the machine on which the
program will run.
You know that low level language requires extensive knowledge of the hardware since it is
machine dependent. To overcome the limitation, high level language has been evolved which uses normal
English like, easy to understand statements to solve any problem. Higher level languages are computer
independent and programming becomes quite easy and simple.
FORTRAN (Formula Translation): Developed for solving mathematical and scientific problems.
One of the most popular languages among scientific community.
239
Computer literacy Program… Introduction to Programming Languages
C: Structured Programming Language used for all purpose such as scientific application,
commercial application, developing games etc.
C++: Popular object oriented programming language, used for general purpose.
Assembler
Compiler
Interpreter
Assembler
An assembler translates assembly language into machine code
Compiler
A Compiler is a computer program that translates code written in a high level language to a
lower level language, object/machine code.
Interpreter
An interpreter program executes other programs directly, running through program code and
executing it line-by-line
240
Computer literacy Program… Introduction to Programming Languages
Ensure that it is easy to understand, fix, and improve your program without a major time investment.
Common problems
These are very common mistakes programmers make:
Your program does not do a job any better than an available alternative program.
Other people, or yourself at a later time, can't understand the programming behind your program. This
means your project won't grow.
Solutions
Utility and Usability
Survey the field to look for programs similar to what you intend to develop. Determine what you like
and don't like about those programs. Figure out ways to improve those programs.
Find source code for similar programs to what you want to make if at all possible. Unfortunately,
people often write a lot of inferior code and leave it floating around the Internet. Don't be one of those
people. Only release useful, well-written programs.
Thoroughly plan what you want your program to do before you start working on it. One way to do this
is to make a flowchart of what you want your program to do.
Aim towards the maximum functionality your program can achieve while maintaining minimal
complexity. Think of the iPod, matchstick, doorknob and television. They are simple yet effective.
If possible, talk to people who might use your program to get an idea of what features they would
want or expect.
Remember the 80–20 rule: 20% of the features in most programs are used 80% of the time. If you can
successfully identify even a few of the seldom used features and leave them out, you can save yourself
some time and frustration.
Maintainability
Make it easy for someone to look at your program's source code and understand what's going on.
Use comments when you're doing somewhat complicated things in your program, or when in doubt.
241
Computer literacy Program… Introduction to Programming Languages
Always choose readability of your code over memory performance. Though in the short run this may
not always be the best choice, in the long run, the performance can be improved if the code is easy to
understand.
Use simple, easy-to-understand names for variables. The convention is that a variable should be
written variable_name or variableName.
Look at examples of source code, and especially source code intended as an example of proper
programming form. Recognize the structure they're using to make things simple.
Data Types
A "program" is a set of instructions stored in a computer's memory for it to execute. Usually in the course of
execution the program will create new information. Also, nearly every program written must store information
supplied after the program was created.
Such information may include user input, custom settings, or calculated values. Because this information can
vary, the term variable is used to describe the element of a program which stores this information. For
example, a name variable could contain "Jack" or "Jill" or any other value.
Variables
In computer science, a variable is nothing more and nothing less than a named location in memory where data
can be stored. In some languages, any kind of data can be stored in a variable while, in others, each variable is
given a well defined type by the programmer and only data of the correct type may (or at least should) be
stored in that location.
The location referred to by a variable may or may not have useful data in it, but typically it does not until it has
been initialized. The process of carving out a piece of memory and assigning it a name is
called creating, allocating or declaring a variable. In some languages, variables are automatically initialized
when they are declared (given a value when they are established as pointing to that location in memory). Most
languages allow variables to be initialized when they are declared but do not require it. The use of an
uninitialized variable is a common source of programming errors, as the data stored in memory at the location
that the variable points to is "garbage", nonsense bits that could have adverse effects on the running program.
area = pi * r * r;
It may look like a math equation, but it is more than a math equation. It is an instruction to the computer to
fetch the values from two memory locations, which do have absolute "ID numbers", but for our purposes and
the semantics of programming languages are called pi and r, multiply those values together and then store the
242
Computer literacy Program… Introduction to Programming Languages
result in the memory location called area. It is very convenient that this code can take the familiar form of an
equation but we cannot allow its appearance to fool us because it does not define a mathematical function;
rather it defines a strict set of instructions that the computer will follow when running this line of code.
X=X+1
Looking at this assignment as a mathematical equation, it makes absolutely no sense—no value is equal to
itself plus one. But we're not talking about mathematics here. While it may look like an equation, this is a
variable assignment that states "retrieve the value of X, add one, and store the result back in X." So if the value
of X is 0 before it reaches this line, it will become 1 afterward.
X = 8 // X is now 8
X += 1 // X is now 9
X –= 3 // X is now 6
X /= 2 // X is now 3
X *= 4 // X is now 12
Variable Types
Most languages have a variety of primitive types such as integers, floating point numbers, single characters
and Boolean variables. Many languages also support a variety of aggregate types (eg. arrays). The exact size
and format of available types may vary based upon operating system, hardware architecture, programming
language and/or the specific compiler used.
One of the important things to take away from the reading is the concept of static typing. Most modern
languages are statically-typed.
Despite the tremendous variety, the statically-typed languages generally follow some well-defined patterns:
Compilers are quite picky about assigning valid values to each variable.
Byte
Reading Assignment:With the possible exception of Boolean variables and user defined types, the byte
(eight bits) is the smallest unit of information used in modern programming languages. A bit is represented
by a 0 or a 1, and therefore a byte is a sequence of 8 0's and 1's, which have a total possible permutation of
28 combinations, or 256 distinct combinations.
243
Computer literacy Program… Introduction to Programming Languages
Application to Variables
System memory must be allocated to store variable values; both the compiler and the author of a program must
work together to determine how much memory should be allocated for each variable, and this memory is
allocated in a sequence of consecutive bytes in memory.
Numeric Types
Each of these have slightly different names on different platforms and in different programming languages. The
absolute size is specified in bytes, regardless of the environment. (see Data Types for more detail)
one-byte (8-bit) value: 0 to 255 (unsigned) or –128 to +127 (signed)
Character Data
A single byte is often used in many languages to store a single text character. These are often denoted by
the variable type char, which is a short-hand for character. Other languages, such as Java, use two bytes
to store a character.
Integer Variables
Integer values and variables are exact representations of numbers from the mathematical set of integers. The
range of values that can be stored is finite and is determined by the size of the memory location
used. Unsigned integers can store only positive numbers and 0. Signed integers can store both positive and
negative numbers. Signed integers are stored using a format called two's complement and have a range that is
roughly symmetrical and centered on 0.
Reading Assignment: Two's complement
Most strongly typed programming languages support a variety of integer types. Java, for example has five.
244
Computer literacy Program… Introduction to Programming Languages
char 2 0 65535
Although Java does not generally use unsigned types, it does have the char type (short for character), an
unsigned two byte integer. Many programming languages treat characters as integers. In C, for example, 'A' is
not really a capital letter A but the numeric value 65 and the numeric expression 'C'—'A' is a perfectly valid
calculation with the value 2. When reading input or writing output, the numeric value of a character variable is
converted to or from the corresponding text character.
Integer Calculations
Calculations involving integers can be as simple as 1 + 1 or as complicated as anything that the programmer
can imagine but the rules are fairly straightforward and should be moderately familiar to anyone who has had
high school algebra.
"1 + 1" is an example of an integer expression—so called because the final answer that the computer gets for
the calculation is an integer. In this example, there are two operands(integer literals in this case) and
an operator, the plus character. The process of performing the calculation is called evaluating the
expression and the answer is the result or thevalue of the expression.
Every programming language that supports integers has, at a minimum, four integer operators—one each for
addition, subtraction, multiplication and division. Some languages, such as Pascal, have an exponent operator.
Some languages, such as C++, allow a programmer to define new operators.
Of the four standard operators, the one that can cause the most trouble is division. What is 3 divided by 2? The
answer that you get will depend on the language and the operator. In some languages (Java, C, C++), if both
operands are integers, the result will be integer and so 3 / 2 will be 1. In some languages (Pascal), there are
different operators for integer division and floating point division and so 3 / 2 is 1.5 (and not an integer) but 3
div 2 is 1.
Operator Precedence
In pretty much all languages that support integer expressions, some operators are evaluated before others. In
high school algebra, everyone learns that multiplication and division are done before addition and
subtraction—unless there are parentheses involved. The rules that dictate which operations are performed first
is called precedence.
Parentheses have the highest precedence. The exact order after that depends on what operators are supported by
the language—many programming languages have a variety of operators.
245
Computer literacy Program… Introduction to Programming Languages
What about operators of equal precedence? In math, it doesn't matter what order 1 + 2 + 3 is evaluated in, but
in a computer, for some expressions, it does. Every programming language will also have rules
for associativity—the direction in which a given order associates. Addition generally associates left-to-right,
so the expression 1 + 2 + 3 would be evaluated (1 + 2) + 3.
int i = 5;
int j = 7;
int k;
k = i + (j * 3) * 4;
How many operators are in the last line? Yes, the equal sign is an operator, so there are four.
Most programming languages have an assignment operator that causes the value calculated on the right side
to be stored in the memory location identified by the variable on the left side. This process is known
as assignment.
In most programming languages where there is an assignment operator, they have a lower precedence than
addition and subtraction. Also, they associate from right to left. The expression a = b = c would associate a =
(b = c)
Boolean
Boolean variables use a single bit and thus can store only two values. They can be thought of as on and off or 1
and 0 but they are most often thought of as being true or false. Boolean variables are useful for handling
information such as, "Did the customer order cheese on her burger?"
Boolean variables and expressions are of fundamental importance in writing computer programs—you will see
why in the very next section.
Boolean Literals
Many languages do not have either Boolean variables or literals, only Boolean expressions. For those
languages that do have them, there are only two, true and false (though the case may vary).
Boolean Expressions
Within the context of computer programming, most Boolean expressions do not have any Boolean variables or
literals, but rather look something like a > 5. Where > is a Boolean operator that causes the left and right hand
operands to be evaluated and the resulting values compared. In the case of a > 5, the expression will be true if
the variable a contains a value larger than 5 and false otherwise.
246
Computer literacy Program… Introduction to Programming Languages
Relational Operators
Most programming languages have some form of the following comparison operators:
Equal == .EQ.
Please note that the type of a > 5 (or its equivalent in other languages) is Boolean. This means that 7 > a >
5 is an illegal expression in most languages because 7 > a is a boolean. Ifa had a value of 6, then this
would evaluate to:
(7 > 6) > 5
(true) > 5
Logical Operators
So how would you write the expression 7 > a > 5 in a computer program? The answer is that it is really
two sub-expressions, is 7 > a? and is a > 5? and both have to be true for the full expression to be true.
Most programming languages have Boolean operators for and, or and not.
And is a binary operator that takes two Boolean operands. The result is true if and only if both operands
are true.
Or is a binary operator that takes two Boolean operands. The result is false if and only if both operands
are false.
Not is a unary operator that takes one Boolean operand. The result is the opposite of the value of the
operand.
The logical operators usually have a lower precedence than the relation or comparison operators. So, in
Java, then, we could write the expression above as 7 > a && a > 5 where &&is the Boolean and operator.
For the sake of readability, parenthesis are recommended though, i.e. (7 > a) && (a > 5).
247
Computer literacy Program… Introduction to Programming Languages
Control structures
The If Statement
Up to this point, everything that we've covered involved simple, linear execution of every line of code. In
the seconds in a year example from above, we could have a line that declared a variable daysInYear and
initialized it to 365.
int daysInYear = 365;
What we need now, is some way to say that, in the event that the year is a leap year, assign the value 366
to the variable daysInYear. One way to do this is with an if statement.
In most programming languages, an if statement contains three parts. The first part is a keyword that tells
the computer that it's an if statement (some languages may have an equivalent structure that uses a
different key word). The second part is a boolean expression. The third part is a statement or group of
statements.
The way that the computer executes an if statement is that, first it evaluates the boolean expression. If
the expression evaluates to false, it skips the third part, the statement(s), completely as if they weren't even
there. On the other hand, if the expression evaluates to true, then the statement(s) are executed.
In a Java/C/C++ environment, where there was a boolean variable isLeapYear, you would write code that
would look something like this:
int daysInYear = 365;
if (isLeapYear)
daysInYear = 366;
It may not be the most interesting code ever written, but it is simple, direct and produces the correct result.
Variations of If Statements
An alternate way to set the number of days in a year might be:
int daysInYear;
if (isLeapYear)
248
Computer literacy Program… Introduction to Programming Languages
daysInYear = 366;
if (! isLeapYear)
daysInYear = 365;
This form seems kind of awkward and it requires the condition to be evaluated twice. Many programming
languages allow an extension of the if statement, an else clause. It would look something like this:
int daysInYear;
if (isLeapYear)
daysInYear = 366;
else
daysInYear = 365;
An if statement may be followed by exactly zero or one else statements. If the if statement evaluates as
true, then its group of statements (in this case "daysInYear = 366;") are run. If the if statement evaluates as
false the else clause's statements are executed (in this case "daysInYear = 365;").
Let us suppose that we are working on a piece of code that performs a divide in a calculator program. We
have three variables dividend, divisor and quotient. We want to divide dividend by divisor putting the
result into quotient, unless divisor is equal to 0 in which case we want to report an error message. Assume
that there is a statementReportErrorMessage that does exactly that and write some code that performs
the divide operation.
Loops
249
Computer literacy Program… Introduction to Programming Languages
A loop is a program structure that executes the same piece of code zero or more times. A loop consists of
a group of statements (called a block in many languages) to be executed and a boolean expression, called
a condition. Every time the computer executes the statements in the loop (called an iteration), the
condition is evaluated. The computer continues to iterate as long as the condition evaluates to true.
int sum = 0;
sum += counter;
print sum;
counter += 1;
This is the style of while loop used in Java, C and C++. The code of the block is delineated in this
example by a matched pair of curly braces. The condition is inside the parenthesis that follows
immediately after the keyword while. The sample while loop given above will execute nine times with
the value of the variable counter starting at one. With each iteration through the loop, the value
of counter is incremented by one. When the value of counter reaches ten, the condition will evaluate to
false and the loop will not be executed. With each iteration, the program will print out the sum of the first
N integers with N equal to counter.
In Java, C and C++, there is a structure that is called a do-while loop that is nearly identical to a while
loop, except that it uses a post-condition. Because the condition is checked at the end of the loop, post-
condition loops are guaranteed to execute at least once.
250
Computer literacy Program… Introduction to Programming Languages
int counter = 1;
int sum = 0;
do
sum += counter;
print sum;
counter += 1;
Subprograms
It is an unfortunate fact of life that things break—and computer programs are certainly no exception. One
of the things that engineers have learned is that, in general, complex things break more often than simple
things. Unfortunately, even a well built program can be tremendously complicated. Something like
Microsoft Windows XP is probably more complicated than the Space Shuttle. It isn't surprising then, that
software has bugs.
In many disciplines, including mathematics, it is a common to solve big, complicated problems by
breaking them down into a group of smaller, simpler problems. That is the basic principle
behind subprograms. Rather than write one big, complicated program that solves the entire problem, we
can write several small pieces of a program that each solve part of the problem and, then, combine them
together, in some specific way, to solve the entire problem.
Subprograms go by different names—depending on the programming language being used.
Subroutine – FORTRAN, Visual Basic, Perl
Procedure – 1Pascal
Method – A generic term used when speaking of many programming languages that refers to any
function, procedure, or subroutine.
251
Computer literacy Program… Introduction to Programming Languages
Note: the difference between a procedure (or subroutine) and a function is that functions return a result,
whereas procedures do not. In some languages, such as 1C# this distinction is implicit. In others, such
as 1Pascal, it is explicit.
Exercise-1
Part I Answer the Question
Q 1. What is Computer Programming language and how it is different from natural language.
a. Subprogram
b. Program
c. Translator
d. Operators
a. Boolean Expression
b. Compiler
c. Machine Code
d. Binary
e. Byte
252