Unit 1: Introduction To Programming Language Concepts

Download as pdf or txt
Download as pdf or txt
You are on page 1of 20

UNIT 1: INTRODUCTION TO PROGRAMMING

LANGUAGE CONCEPTS
*

Structure
1.0 Inuoduction
1.I
Objectives
1.2 What is an Algorithm?
1.3 Flowcharting
1.4 Problem and It5 Algorithm
1.5 Concepts of a Programming Language
1.6 Categorics of Language

1.6.1
1.6.2
1 6.3
1.6.4

1.7

Machine Language
Assembly Language
H ~ g hLevel Language
Fourch Generation Language

Elements of Programming Language


1.7.1

1.7.2
1.7.3
1.7.4

Variables. Constants. Data Types. A m y and Expressions


Inpt and Output Statement
Conditional and Looping Statement
Subroutine and Functicm

1.8
1.9

Summary
Model Answers
1.10 Further Readings

1.0

INTRODUCTION

A computer contains two basic parts: (i) Hardware and (ii) software. In the first course we
touched upon hardware issues in quite detail. In this unit and also in the rest of the units of
this block we will discuss topics related to software. Without software a computer will
remain just a metal. With software, a computer can store, retrieve, solve different types of
problems, create friendly environment for software development etc.

i. l

I
I

The process of software development is called programming. To do programming one


should have a knowledge of (i) a particular programming language (ii) set of procedures (algonthm) to solve a problcm or develop software.
The development of an algorithm is basic to computer programming and is an important part
of computer science studies. Developing a computer program is a detailed process which requires serious thought, careful planning and accuracy. It is a challenging and exacting task
drawing on the creativity of the programmer.
Oncc an algorithm is obtained, the next step for a solution using a computer would be to program the algorithm using mathematical and data processing techniques. Programming languages constitute the vehicle for this stage of problem solving. The development of
Programming Languages is one of the finest intellectual achievements in Computer Science.
It has been said that "to understand a computer, it is necessary to understand a programming language. Understanding them does not really mean only being able to use them.
A lot of people can use them without really fully understanding them".

After completion of this unit, you should be able to


define an algorithm and its features
describe problem solving stages (steps)

Programming Concepts a.nd


Softwarc Tools

explain the conaept of a language &a the generations

'

differentiate several concepts of programming languages such as variable, constant,


data type, arrays, expression etc.
describe looping
differentiate between subroutine and function

1.2

WHAT IS AN ALGORITHM?

An algorithm consists of a set of explicit and unambiguous finite steps which, when camed
out for a given set of initial conditions, produce the corresponding output and terminate h a
fured amount of time. By unarnabiguity it is meant that each step should be defined precisely i.e. it should have only one meaning. This definition is further classified with some more
features.
According to D.E. Knuth, a pioneer in the computer science discipline, an algorithm has five
important features.
i)

Finiteness:

An algorithm terminates after a fued number of steps.

ii) Definiteness:

Each step of the algorithm is precisely defined, i.e. the actions to be


carried out should be specified unambiguously..

iii) Effectiveness:

All the operations used in the algorithm are basic (division,


multiplication, comparison, etc.) and can be performed exactly in a
'fixed duration of time.

iv) Input:

An algorithm has certain precise inputs, i.e, quantities which are


specified to it initially, before the execution of the.algorithm begins. -

v) Output:

An algorithm has one or more outputs, that is, the results of opemtions
which have a specified relation to the inputs.
Let us take one example to illustrate all the features of an algorithm.

Example: Suppose, we have to develop an algorithm to convert an Gteger numerical score (0


to 100) scored by a student in a particular test into lener grades (A,B,C,D@ using the following procedure.
Numerical Score

Letter grade

Less than 40

More than 85

Algorithm is defined as follows:


Step 1 INPUT the score of a student
Step 2 If the score is less than 40 then print " E :END
Step 3 If the score is greater than or equal to 40 and less than 55, then print "D":END
of a program
Step 4

If the score is greater than or equal

55 and less rhq 70-print "C":END

Step 5 If the score is greater than or equal to 70 and less than or equal to 85 print "B"

:END

, -3tepP6

If the score is gmim than 85 print "A"

Step 7 End of a program

I
*

The algorithm terminates after 7 steps. This explains the feature of finiteness. Action of
each step is precisely defined. In our example. each step requiressimple comparison and printing
operation. This explains the feature of definiteness and effectiveness. Input of our algorithm is
marks scored by a student and output is the grade awarded according to the range.

1.3

FLOWCHARTING

The most difficultand important task within programming is the systematic and careful
analysis of a whole problem. Therefore,before going to actua! programming. a programmer
should always go through the following steps in a sequential order.
i) Design an algorithm representing the process of solution of problem
ii) Represent this algorithm through flowchartfor better understanding of the algorithm
iii) Code the flowchart i.e. write instruction in a ptograrnming language that a specific
computer will accept.
iv) Run/Execute the program on the computer for the given data (Input) and get the
output.

Steps (1) (3) and (4) will be discussed in the next section. In this section we will discuss
only the flowcharting symbols step (Step 2)

Flowcharting: Flowchart is a graphical representation of an algorithm. It makes use of the


basic operations in programming. All symbols are connected among themselves to indicate
the flow of information and processing. Figure 1 shows the list of flowchart symbols. We
will use these symbols in the next section to represent an algorithm.
i) Terminal

The oval represents any terminal point in a program and generally contains-such
words as BEGIN,START, END or STOP

ii) Input/Output

The parallelogram represents the Input/Outputfunction i.e. making data available


for processing (input) or recording of the processed information (output). This step
implies obtaining a number from an Input device (say, the keyboard and storing
- it
in the ~tn-o~.
lncation named 'A').
Flow Direaim

=I1

Decitioa Making

a
A~t~outim

-----..--.

Predefined Process

Pnuxer

Fig.1 : Flowchart Symbols

Rogrnmmlng Concepts and

iii) 'Process

Sdtware Tool.-

The rectangle represents the processing operation. A process changes or moves


data. An assignment is normally represented by this symbol.
iv) Flow direction
Lines or arrows represent the flow direction function - the flow of control. Normal
flow direction is from left to right or from top to bottom.
A broken line and bracket represent the annotation function - the addition of
descriptive comments or explanatory notes for clarification of some statements.

vi) Decision making symbol


The diamond represents a decision or switching type of operations that determines
which of the alternative paths is to be followed.
vii) Connector
The circle represents a function in a flow line
viii) Pre-defined process
The double sided rectangle represents a named process that consists of one or more
operations or programming steps that are specified elsewhere, such as a module or
subroutine. We will use these flowcharting symbols for representing algorithm.

1.4

PROBLEM AND ITS ALGORITHM

We have already discussed the basic concept of an algorithm and certain aspects of problem
solving. Now our goal will be to select some useful protkm and discuss appropriate algorithm using different mathematical techniques to solve them on a computer. To solve any
type of problem on a computer, be it simple or complex, we just require a very small number
of instructions which are us& for storing information and for arithmetic operations.
Problems can be solved through several standard mathematical technique. We will illustrate
here only one technique called iterative technique.

Iterative Technique
This technique is applied to solve problems containing repetitive operation(s) or processes:
Suppose we have to add numbers 1 to 15 (that is 1+2+3+4+....+15). This could be done by
simply adding successive numbers to an accumulating sum. That is:

Successive Numbers

Accumulating Sum

1+2

3+?

We just noticed that accumulative sum 3,6,10 are added with successive numbers 3,4,5 ....etc.
There are a large numbers of problems similar to the above which are solved by repeating the
same process (addition in our example) over and over again. Problems of this type (of repetitive nature) are solved by the iterative technique.
The important issue to be considered while discussing the iterative technique is that iterative
process cannot go on forever and must be terminated at a certain stage.
Now, let us discuss, a very interesting problem called$,- Fibonacci series which requires an '
iterative technique for developing the series.

Problem: Generate and print the first n terms of the Fibonacci series where n is greater than
orequal to 1.

The frrst few numbers in the series are:

As you can see in this series from the third number onwards, each number beyond the first
two is derived from the sum of its two nearest predecessors. The famous series wai
originated in 1202 by Leonard0 Pisano (Leonard0of Pisa) who is also known as Leonardo
Fibonacci. His book contains the following exercise: "How many pairs of rabbits can be
produced from a single pair in a year's time?" To solve this problem, we are told to assume
that each pair produces a new pair of offspring every month but each new pair becomes fertile only after one month and furthermore these rabbits never die! After two months there
will be two pairs of rabbits, and after three months, there will be three. The following month
the original pair 1 and the pair born during the first month will both usher in a new pair and
there will be five in all and so on.
Definition of an Algorithm: In the Fibonacci series only the first two numbers (0 and 1) are
defined. After that, each number is the sum of the last two numbers. This is illustrated by
the following table presurr.ing 0 and 1 are the fmt two numbers in the series.
Next number
1
2

3
5
8

=
=
=

=
=

Sum of last two numbers


1 + 0 (0 and 1 are last two numbers)
1 + 1 (1 and 1 are last two numbers)
2 + 1 (2 and 1 a~ last two numbers)
3 + 2 (3 and 2 are last two numbers)
5 + 3 (5 and 3 are last two numbers)

Let us now develop an algorithm which can generate the series,


Let us define 3 variables: SUM, X and Y.
SUM is used to store the next numbef
X is used to store the number before the last number

Y to store the last number.


Thus, in any solution, in the series, SUM, X and Y will be placed as X,Y,SUM. With this
premise, the series can be depicted as:

You will notice, that in the process of generating the numbers the values of X and Y keep on
changing.
If you observe more carefully, you will fmd that the next value of Y is the previous value of
SUM and the next value of X is the previous value of Y. For example, when SUM is 5 then X
and Y are 2 and 3 respectively. And in the next number i.e. when SUM is 8, then X becomes
3 (previous value of Y) and Y becomes 5 (the previous value of SUM). This process of exchanging the values of SUM. X and Y and addition of X and Y continues depending upon
how many numbers have to be produced. Since the process of exchange and addition are
repetitive, we can apply iterative techniques. Let us presume that we are required to generate
5 successive numbers starting from the 3rd number in the series; the first two numbers being
X ( 4 ) and Y (= 1).
Description of the Algorithm
Step 1 INPUT N the number of series to be generated.
Step 2 Assign the initial value to X and Y.
Step 3 Initialise the counter.

step 4

Calculate the next number by adding X and Y

Step 5 Print its value

Step 8 Increment counter by 1


Step 9 Compare whtrher the series has been generated or not
Step 10 If yes (in om case N 15) then, terminate the program a else go to Step 4. Now let us
conceptualhe the definition of algorithm through this example, Step 1 and Step 5
define Input and Output part. Each step is unambiguous.

These steps are also explained through a flowchart (Figure 2). ' h e same algorithm developed
as a BASIC pogram is shown in figm 3.

Step 1

Value of N

'

.
I
SUM = 0

sw2

Step 6

Step 7

SUM = Y

I
1 ~ 1 + 1

J?igurt 2 :Flowchart for Fibonacci Series

10 M , N

Read the n u m h of Fibonacci spies to be generated

20 LETX=O

Assign the first Fibonacci number

30 LETY-1
40

FOR I = 3 TO N :

Assign the second Fibonacci number


Initialise the counter I. Initial value of I is 3 because first two
Fibonacci numbers are a l p d y given.

50 SUM = X+Y

Generate next Fibonacci number

60 PRINTSUM

PRINTSUM

80 LETX=Y

Exchange the values

90 NEXT1

Update the value of I

100 END

Terminate the program

70 LETY = SUM

Figure 3 :BASIC Program for Fibonacci Series


From the program, it is evident that the iterative process is developing the series of numbers can be broken down into a series of steps after establishing a relationship between
successive numbers. A pattem in the relationship will be established after analysis. This
pattem is used to formulate the algorithm. There are many other techniques which will
be discussed in Course 4 (Data Structure).

Quccticrn 1 : Wntc fio*;v.ci~~t


and slcps for solving the following problems
(i) to cfilcuiate ii~earm of a ~ c m g l e

(ii) print four n ~ n l h x spri~it


,
heir sun) and heir yroduct

(iii) find the su~riof

squats

of inugcls from M to N whcre M and N are input by the

LIT-cr
(iv) frnd the avtiage of

the s q u a ~of
~ sLhc fit st W psilive intcgers whcreN is input by

lhc: user.

Qucstion 2 : Dcfinc input, output and main~lwcssingparts of (i), (ii) and (iii).

1.5

CONCEPT OF A PROGRAMMING LANGUAGE

In order to communicate with each other, we use natural languages like Hindi, English,
Bengali, Tamil, Marathi, Gujarati etc. In the same way programming languages of one
type or another are used in order to communicate instructions and commands to a computer for solving problems. Learning a programming language requires learning the symbols, words and rules of the language.
Program and Programming: A computer can neither think nor make any judgement'qn
its own. Also it is impossible f a any computer to independently analyse a given data
and follow its own method of solution. It needs a program to tell it what to do. A program is a set of instructions that are arranged in a sequence that guides the computer to
solve a problem.
The process of writing a program is called Programming. Programming is a critieal
step in data processing. If the system b not correctly programmed, it delivers information results that cannot be used. There are two ways in which we can acquire a program. One is to pumhase an existing program, which is normally referred to as
packaged s o h a r e and the other is to prepare a new p g m m from scratch in which
case it is called customised software.

Rogrnmmlng Concepb and


SoftwareTds

Today. there are m p y languages available for developing programs. These languages
are designed kceping in mind some specific areas of applications. Thus, some of thelanguages may be good for wriling system programlsoftware while some other for application software. Since a computcr can be used for writing variaus types of
application/system softwares, thcre are different programming languages.
9

i)

System Programming Languages :System programs are designed to make the computer easier to use. An example of system software is an operating system. whichconsists of many other programs for contralling inputloutput dcvices, memory. processor
etc. To write an operating system. the programmer needs inslruction to control the
computer's circuitry (hardware part). For example, insuuctions.that move data from one
location of storage to a register of the processor. Today C-language is widely used to
develop system software.

ii) Application Programming Language: Application programs are &signed for specific
computer applications, such as payroll processing, inventory cotluol etc. To write
programs for payroll processing or other applications, the programmer does not need to
conuol the basic circuitry of a computer. Instead the programmer n& instructions that
make it easy to input data, produce output. do calculations and store and retrieve data.
Programming languages hat are suitable for such application programs support these insuuctions but not necessarily the types of instructions needed for development of system
programs.
There are two main categories of application programs: business programs and scientific application proglams. Most programming languages are dcsigned to be good for one category
of applications but not necessarily for the other, although there are some general purpose languages that support both types. Business applications are characterised by processing of large
inputs and large outputs, high volume data storage and retrieval but call for simple calculations. Languages which are suitable for business program development must support high
volume input, output and storage but do not need to support complex calculations. On the
other hand. programming languages that are designed for writing scientific programs contain
very powerful insuuctions for calculations but rather poor instructions for input, output etc.
Amongst traditionally used programming languages, COBOL (Commercial Business
Oriented Programming Language) is more suitable for business applications whereas
FORTRAN (Formula Translation Language) is more suitable for scientific applications.

CATEGORIES OF LANGUAGES
We can choose any language for writing a program according to the need. But a computer executes programs only after they are represented internally in binary form (sequences of 1s and 0's). Programs written in any other language must be translated to the
binary representation of the instructions before they can be executed by the computer.
Programs written for a computer may be in one of the following categories of languages.

1.6.1

Machine Language

This is a sequence of insuuctions written in the form of binary numbers consisting of


1's. 0's to which the computer responds directly. The machine language was initially
referred to as code. although now the term code is used more broadly to refer to any program text.
An jnsbuction prepared in any machine language will have at least two parts. The f i t
part is the Command or Operation, which tells the computer what functions is to be performed. All computers have an operation code for each of its functions. The second
part of the instruction is the operand or it tells the computer where to find or store the
data that has to be manipulated.
Just as hardware is classified into generations based on technology, computer languages
also have a generation classification based on the level of interaction with the machine.
Machine language is considered to be the first generation language.

introduction to Programming
Language Concepts

Advantage of Machine Language


It is fastcr in execution since the computer directly starts executing it.

Disadvantage of Machine Language


It is difficult to undersmd and develop a program using machine language. Anybody
going through this program for checking will have a dificult task understanding what
will be achieved when this program is executed. Nevenheless, the computer hardware
recognises only Lhis type of instruction code.

The following program is an example of a machine language program for adding two
numbers.
Load A register with
value 7
Load B register with 10
At A + B
Store the result
into the memory location
whose address is 100 (decimal)
Halt processing
1.6.2

Assembly Language

Whcn wc cmploy symbols (letter, digits or special characters) for the operation part, the
address part and other parts of the instruction code, this representation is called an asscmbly language program. This is considered to be Lhe second generatjon language.
Machine and Asscmbly languages are referred to as low level languages since the coding
for a problem is at the individual instruction level.
Each machine has got its own assembly language which is dependent upon the internal
architecture of Lhe processor.
An assembler is a translator which takes its input in the form of an assembly language
program and produces machine language code as its output.
The following program is an example of an asscmbly language program for adding two
numbers X and Y and storing the result in some memory location.
LD A, 7

Load register A with 7

LD B, 10

Load register B with 10

ADD A, B

A t A+B

LD (100). A

HALT

Save the result in the location 100


Halt process

From this program, il is clear that usage of mnemonics (in our example LD. ADD,
HALT arc thc mnemonics) has improved the readability of our program significantly.
An assenibly language program cannot be executcd by a machine directly as it is not in
a binary form. An assembler is needed in order to translate an assembly language program into Lhc object code executable by the machine. This is illustrated in the figure 4.
Assembly
language
program

Assembler

Fig.4 : Assembler

) Object Code

Rogrmmlng ConceptE and

S d t w u c Tools

Advantage of Assembly Language


Writing a program in assembiy language is more convenient than in machine language.
Instead of binary sequence, as in machine language, it is written in the foam of symbolic
instructions. Therefore, it gives a little more readability.
Disadvantages of Assembly Language
Assembly language (program) is specific to a particular machine architecture. Assembly
languages are designed for specific make and model of a microprocessor. It means that
assembly language programs written for one processor will not work on a different
processor if it is architecturally different. That is why the assembly language program is
not portable.
Assembly language program is not as fast as machine language. It has to be first translated into machine (binary) language code.
1.63

High-level Language

We have talked about programming languages as COBOL, FORTRAN and BASIC.


They are called high level programming languages. The program shown below is written
in BASIC to obtain the sum of two numbers.
10
20

30
40
50

LET
LET
LET
PRINT
END

X
Y

SUM
SUM

10
X+Y

The time and cost of creating machine and assembly languages was quite high. And
this was the prime motivation for the development of high level languages.
Since a high level source program must be transbed first into a form the machine can
understand, this is done by a sofcware called Compiler which takes the some code as
input and produces as output the machine language code of the machine on which it is
to be executed. This is illustrated in figure 5,

Source Program
in High level
Language

Compiler

> object Code

Fig.5 : Compiler

During the process of translation; the Compiler reads the source programs statement-wise
and checks the syntactical emrs. If there is any error, the computer generates a print-out
of the emrs it has detected. This action is known as diagnostics.
There is another type of software which also does the translation. This is called an Interpreter. The Compiler and Interpreter have different approaches to aanslation. The following table lists the differencesbetween a Compiler and an Interpreter.
Compiler
1) Scans the entire program

first and then translates


it into machine code.
2) Converts the entire program
to machine code; when all
the syntax errors are
removed execution takes
place.

Interpreter
Translates the program line by
line.
Each time the program is
executed, every line is checked
for syntax error and then
converted to equivalent machine
code.

3) Slow for debugging

Good for fast debugging.

4) Execution time is less

Execution time is more.

Advantages of High-level Programming Language: There ate four main advantages of


high-level programming languages. These are:

i)

Readability: Programs written in these languages are more readable than assembly and
machine language.

ii) Portability: Programs could be run on different machines with little or no change. We
can. therefore, exchange software leading to creation of program libaria.
iii) Easy debugging: Errors could easily be removed (debugged).
iv) Easy Software development: Software could easily be developed. Commands of
programming language are similar to natural languages (ENGLISH).
High level languages are also called Third generation languages.
1.6.4

Fourth Generation Language

The fourth generation of programming languages is not as clearly defined as are the
other earlier generations. Most people feel that a fourth generation language, commonly
referred to as 4GL is a high level language that requires signifcantly fewer instructions
to accomplish a particular task than a third generation language does. Thus a programmer should be able to write a program faster in 4GL than in third generation language.
Most third generation Iat~guagesare procedural languages. This means that the programmer must specify the steps, that is the procedure, the computer has to fdlow in a program. By contrast, most fourth generation languages are non-procedural languages. The
programmer does not have to give the details of procedure in the program, but instead,
specifies what is wanted. For example, assume that a programmer needs to display some
data on a screen, such as the address of a particular employee (SANTOSH) from the personal file. In a procedural language, the programmet would have to write a series of instructions in the following steps:
Step'l

: Get a record from the personal file

Step 2

Step 3 :

If this is the record for SANTOSH, display the address


If this is not the record for SANTOSH, go to Step 1.

In a non-procedural language (4GL), however, the programmer would write a single instruction that says:
Get the address of Santosh from personal file.
Major fourth generation languages are used to get information from files and data bases,
as in the previous example and to display or print the information. These fourth generation languages contain a query language which is used to answer queries or questions
with data from a database. For example the following figure shows a query in a common query language SQL,
SELECT ADDRESS FROM PERSONNEL
WHERE NAME = "SANTOSH"
Some fourth generation languages are used to produce complex printed reports. These
languages contain certain types of a program called generators. With a report generator
available, the programmer specifies the headings, detailed data and totals needed in a
report. Thus, the report generator produces the required report using data from a file.
Other fourth generation languages are used to design screens to be used for data input
and output and for menus. These languages contain certain types of programs called
screen painters. The programmer designs how h e screen is to look and, therefore, we

Programming Conecpts and


Software Tools

can say that the programmer paints the screen,. using the screen painter program. Fourth
generation languages are mostly machine independent. Usually they can be used on
more than one type of computer. They are mostly used for office automation or business applications, but not for scientific programs. Some fourth generations languages are
designed to be easily learnt and used by end users.

1.7

ELEMENTS OF A PROGRAMMING LANGUAGE

Learning a programming language requires understanding of concepts such as representation of different types of data in the computer, the various methods of expressing
mathematical and logical relationship among data elements and the mechanics for conriolling the sequence in which operation can be executed for inputting, processing and outputting of data.
1.7.1

Variables, Constants, Data type, Array and Expressions

These are the smallest components of a programming language.


Variable: The first thing we must learn is how to use the internal memory of a computer in
writing a program. Memory may be pictured as a series of separate memory cells as shown in
figure 6.
cornput& memory is divided into several locations. Each location has got its own address.
Cell 1
Cell 2

....,.....
Cell N
Figure 6 :Memory Organisat ion
Each storage location holds a piece of information. In order to store or retrieve information
from a memory location, we must give that particular location a name. Now study the follow.
ing definition.
Variabie is a character or gmup of characters assigned by the programmer to a single
memory location and used in the program as the name of that memory location in order to ac
cess the value stored in it.
For example in expression A = 5 , A is a name of memory location i.e. a variable where 5 is
stored.
Constant: It has fixed value in the sense that two cannot be equal to four. String constant is simply a sequence of characters such as "computer" which is a suing of 8 characters. The numeric constant can be integer representing whole quantities or a number
with a decimal point to represent numbers with fractional part. Constant would be
probably the most familiar concept to us since we have used it in doing everything that
has to do with numbers. Numeric constants can be added, subtracted, multiplied,
divided, and also compared to say whether two of them are equal, less than or greater
than each other.
As suing constants are a sequence of characters. a related string constant may be o b
tained from a given one, by chopping off some characters from beginning or end or both
or by appending another string constant at the beginning or end. For example, from
'Gone with the wind', we can get 'one with'. 'Gone with wind', and so on. String constants can also be compared in a lexicographic (dictionary) sense to say whether two of
them are equal, not equal, less than or greater than each other.
Data type: In computer programming, the term data refers to anything and everything

processed by the computer. There are different types of data processed by the computer;
numbers are one type of data'and words axe of another type. In addition, the operations
that are performed on data differ from one type of data to another type. For example
multiplication applies to numbers and not words or sentences.
Data type defines a set of related values/integers, number with fraction, characters and a
set of specific operations that can be performed on those values.
In BASIC a statement LET A = 15 denotes that A is a numeric data type because it contains numbers but in a statement LET A$ = "BOmAY" , A$ a variable of character
data type. Data type also defines in terms of contiguous calls should be allocated for a
particular 'variable.
Array: In programming we deal with large amount of related data. To represent each
data element we have to consider them as separate variables. For example if we have to
analyze for the sales performance of a particular company for the last 10 years, we can
take ten different variables (names) each one representing sales of a particular year. If
we analyse sales information for more than 10 years, then accordingly number of variables will further increase. It is a very difficult to manage with large number of variables in a program. To deal with such situation an array is used.
An array is a collection of same type of data (either string or numeric), all of which
are referenced by the same name.

Normally two types of array are used:


(i) One dimensional array Am)
(ii) Two dimensional array A(X,Y)
One Dimensional Array: It is a list of related data of same type referred to by the
same variable name. For example 5 years sales information of a company in a one
dimensional array is represented is as follows:

A (1) specifies Sales information of a first year


A (2) specifies Sales information of a second year
A (5) specifies Sales information of a fifth year
+

Two Dimensional Array: In a single dimensional array the data of an array is dependent upon a single factor such as in the sales example it is the year of sales. Sales of
First year, sales of - --second
year -.

In some instances, we find arrays whose elements are determined by two factors, such
as sales figure in each of 5 years by certain cities where sales are made. In this case, we
use two dimensional arrays which are represented in a tabular form (in rows and
columns) shown at figure 7. Rows represent cities whereas columns represent years (first
year, second year and so on). The content of each cell contains amount (in rupees) sold
out in a city in a particular year.
1st year

2nd year

3rd year

4th year

5th year

MADRAS

10.000
A (1.1)

20,000
A (1.2)

30,000
A(1.3)

40,000
A (1.4)

50.000
A (1.5)

CALCUTI-A

20,000
A(2.1)

5,000
A (2.2)

16,000
A (2.3)

18,000
A (2.4)

30,000
A (2.5)

DELHI

25,000
A (3.1)

30,000
A (3.2)

35,000
A (3; 3)

40,000
A (3.4)

50,000
A (3.5)

Figure 7: Tho Dimensional Array

Introduction to Programm~ng
Language Concepts

ProgrammingConcepts and
Softwarc Tools

A(1.1) speciks the fmt row and first column of two dimensional array A.
Expression : We h o w lhat we can express intended arithmetic operations using exsions such as X+Y, X+Y*Z and so on. Several simple expressions can even be nested
together using parentheses to form complex expressions. Every computer fanguage
specify as in which various arithmetic operators are evaluated in a given expression. An
expression may contain operators such as
Parentheses

(1

exponentlation

negation
multiplication, division

*, /

Addition, substractlon

+. -

The operators are evaluated in the order given above. For &ample. the expression

Can be considered to be evaluated as follows:


2+8*(44/3)

Sub expression (4-613) taken up first

2+8*(4-2)

division 6/3 within (4-6/3)hashigherpriority than 4-6

2+8*2

Subtraction (4-2) is performed next


(4-6'3) is now cornpiere.

2+8*2

8*2 will be executed first then its


result will be added with 2 that is
16+2 = 18.

It is useful to remember the order of priority of various operators. But it is safer to


simplify expressions and enclose them in parentheses to avoid unpleasant surprises. So
far we have focused on arithmetic expressions. But expression is a very general concept.
We mentioned earlier that apart from arithmetic operation we can compare numbers a
strings. We do it by using relational operators in expressions.
The following is a list of relational operators.

equalto

< > not equal to


<

lessthan

>

greater than

<= less than or equal to

>= greater than or equal to


These operations have the same level of priority among themselves but a lower priority
than arithmetic operators mentioned earlier. The relational expressions result in one of
the truth values. either TRUE or FALSE. Some computer languages such as PASCAL,
FORTRAN explicitly provides logical constants. TRUE.. .FALSE.. andlor. YES...NO as
u s 4 to represent these n t h values. Other languages use integer constants to implicitly
represent the n t h values arrr for instance, FALSE is usually represented by number 0 and
1 is considered to represent TRUE. When a relational expression such as (3 > 5) is
evaluated to be FALSE by such languages, a value 0 {s assigned, whereas (5 < 7) will
he evaluated to be TRUE. and value 1 will be assigned.
Now thal relational expressions are capable of comparing only two values separated by
appropriate relational operator. If we want to an express idea such as whether number 7

happens to be within two other numbers 4 and 10. we may be tempted to write relational expression 4 <= 7 <= 10. Such reasonable expectation from us may be a bit too complex for a computer language. In such cases, we need to explain our idea in terms of
simple relational expressions such as (4 c= 7) AND (7 c= 10) which means that 7 is between 4 and 10. To combine several relation expressions for expressing complex condi- '
tions, we use logical operators such as AND or OR operators. Among other logical
operators NOT simply negates a truth value in the sense that NOT TRUE is FALSE, and
NOT FALSE is TRUE. The logical operaprs have lower priority-than relational
operators. Among themselves they have the following order of priority during evaluation
of logical expressions.:
Operator

Meaning

NOT

Simply negates a truth value. NOT (2 > 5)is TRUE

AND

TRUE if both adpming expressionsare 'TRUE otherwise it is FALSE.


For example (4 c 7) and (7 c 10) is TRUE whereas (4 > 7) and (7 c 10)
is FALSE

OR

FALSE if both adjoining expressions are FALSE otherwise it is TRUE


For example (4 c 2) OR (7 > 2) is False whereas (4 > 2) OR (7 > 2)
is TRUE

XOR

TRUE only if one of the adjoining expressions is TRUE and other is


FALSE. The XOR has same priority as OR.(4 c 7) XOR (7 c 10)
is FALSE,

Of the four logical operators NOT, AND and OR are sufficient to express any logical
condition.
Expressions would be our basic programming unit. Our programs would be full of them,
and while executing the program, computer would be preoccupied most of the time
evaluating them. But the computer would also be doing other things such as taking some
values as input from an input device, assigning a value or result of an expression to a
variable, send a value for display to a display unit, pondering to be or not to be on
some conditional expression, repeating some tasks until we are satisfied, and calling
some slave-programs to peflorm specific tasks. In the following discussion we shall
elaborate on these actions.
1.7.2

Input and Output Statement

Syntax :

input list of variables

Input statements are normally used for supplying values to a list of variables through an
input device such as a keyboard. On execution, a question mark? (in BASIC) would be
displayed on the meen. in response to which we are expected to supply a sequence of
desired values matching appropriately the type (i.e. integer, floating-point or string type )
and the number of variables in the list. For example in BASIC, INPUT A, B, C is an
input statement with list of 3 variables A.B.C.
Assignment statement

Syntax : variable = expression


This is the most obvious statement used for assigning value to an identifier ( i.e, variable). In BASIC languages this is also known as LET statement though the key word
LET is optional in most of them. Note the use of = as assignment operator. You would
recall that it was also used as relational operator. Some purists justifiably object to ambiguous use of =. In Pascal, := is used for assignment instead of just = which is used as
relational operator. In language C '=' is used for assignment but ' == ' for relational
operator! Few examples of assignment statemant in BASIC are given below:
LET SUM = X+Y
LETX
=5
SUM and X are called variables whereas A+B is called in expression.

Rqlrrmming Concepts and


Sdtware Tools

Print statement
Syntax

print

list of variables

This is again an obvious way to display values of specified list of variables on display
screen. We shall make use of print to represent generic output statement independent of
any particular output device such as display screen, printer and so on. Computer languages normally provide very iich facilities for making the display as athactive as possible.
An Example of print statement in BASIC is PRINT A$$, which will display values of
A,BC on display screen.
1.73

Conditional and Looping Statement

Conditional Statement
If-then-else- structure :
Syntax : if (condition)
Then
statement(s)for lbsk A
else
statement(s) for Task A

-I

This is one of the most important program -structures that enables a modem programmer
to develop well structu~dprograms. Note that we are calling it as structure rather than
a statement. As structure it accommodates statements corresponding to alternate tasks to
be performed depending upon truth value of the condition, The structure has three canponents: a conditional expression the truth value of which determines the action, a
then-clause denoting task to be performed if the condition is TRUE (Task A), and an op
tional else-clause with task to be performed if the condition is FALSE.
Looping Statement

Obviously, the purpose of a' loop suucture is to repeat certain tasks until no-more ~ p e t i tion is desired. We shall be presenting several variations of loop structure appropriate to
handle different situations
While- end while:

(While Condition)

Syntax :WHILE

statement(s) for task being repeated

end while
A loop structure is characterised by the body of statements to be repeated, and the condition for termination of loop. In while-end while version the condition is tested before
every execution of the body. The body is executed if the condition is found to be
TRUE. 'lhe loop is active as long as the condition evaluates to be TRUE and terminates
when the condition is evaluated to be FALSE. In case the condition is found to be
FALSE for the first time, the body will be skipped.

for endfor s~ucture

Syntax: for var = Start to finish step incr do


Body of statements

This loop structure is distinctly different from the while condition end while we have
discussed so far. Unlike it, the for - endfor suucture counts the number of times the
body is to be executed on the basis of the number of times a control variable is incremented from start to finish in specified steps. Managing the control variable is the
responsibility of the for - endfor structure, so we need not and should not worry about
assigning any value lo it in the body of statements. Any attempt to do so may land us in
trouble.
Fibonacci series program is written using FOR-END FOR statement (Refer section 1A).
This loop structure is so famous that it is available in all languages, sauctured or not
As usual, key words provided may be diffetent. The Microsoft BASIC calls it for
next, and optionally provides for specification of control variable after next Many other
languages insist on mention of the control variable after next

We have discussed program structures quite elaborately. Let us turn our attention to dam
smctures that hold w values. So far we have been dealing with simple variables that
hold only one value of a &sired type. So we have integer variable, floating-point variable, and string variable holding only one value on the corresponding type at any moment. Can we have data structures that are capable of holding mote than one value?
Programming languages do oget complex data structures required for advanced programming. Array and record are two of them. We have discussed about an array at 1.7.1 at
some extent. A detailed discussion on these topics is beyond this unit

1.7.4

Subroutine and Functions

When writing a program sometimes. it is necessary to repeat a statement or group of


statements at several points. For example, it may be necessary to perform the same computation several times. Repeating the same statement in a propam each time makes a
program lengthy and also gives poor readability. These problems could be sorted out if
the necessary statements could be ,written (coded)once and then referred to each time
they are needed.
This is the purpose of subroutine and function. Subroutine and function consist of one a
more basic statements that can be referred to at diffaent points in a program. Each time
that a subroutine and function is referenced. we say it is called.
A subroutine is a group of statements that can be executed from different points in a program.Syntax for defining subroutine varies from one language to another language.

-.

Functions: The word function in programming means essentially what it does in mathe
matics. Function is a rule or series of rules that assign one and only one value Y to give
value X. Thus, X and Y are called variables. Value of Y is dependent upon value of X.
This X is also called the argument of the function. The notation used for function should
already be quite familiar to you.

In this notation '%' is the name of the function. . Consider a specific example:

If we let X equal 3, then this rule or function directs us to compute 12 for Y. If we assign the value of X= -3, then Y is -6. Using function notation, F(3) = 12 and
f(-3) = -6.
Each language has different rules to define a function. In Course 4, in Block 1 and 2 we
will discuss syntaxes of C and Pascal as two high level languages in detail.
Library functions: These are functions supplied with your language. The code for a
library function does not appear in the program. It is inserted by the computer when the
program is translated into machine language.

Introductbnt o P r q r m I q
~lyurpCorcapb

I'rugrarnmlng Conccpts and


Sortxarc l'ools

Some built-in functions in C programming language arc Printfo, Scanfo.


Check Your Progress 2
Question 1.
Qucstlon 2:

What 1s the d~llerenccbctwccn dilrd gcncrmorr a ~ fuu~li:


~ d k c ! ? i ! ~ t i U i r lullguagc.
(I)

What is the purpose of a looping sbiemerlu irr a progirilriii;ii:g s r i g ~ a k e '

( I I ~L)cflnc 4

problems whlch you thlnic rt arl 1 ~ wluicl


:
statemcnh.

Questlon 3:

ii) What
iii)

Qucst~on4:

1.8

IS ihc

advanugc of usnnp m array

;i:

.I

Irtiudt:-

;:rrigi-dnnlin:

,~:rl,rr.b

- l ; i . ~-i - > :+~

'

Write lour exprcssionh usir!g an Xi&..

What is the diffwncc bctwccn subroii~irit-

iuncaun'

SUMMARY

Developing a software for any application (problem) requires defining an algorithm and
coding it in a suitable programming language.
The key concepls discussed in the unit are:
High level languages offer many advantages over low level languages and there are
many issues to be considered when choosing a high level language for a particular
application.
High lcvel programming languages consists of several basic componenls and learning a programming language requires learning these components.
To dcvclop skill is a particular programming language. one has to do lots of problem solving
exercises and practicals on a machine.

MODEL ANSWERS

1.9

Check Your Progress 1


1.

(i)

Step1

Ilrr'PUT the value of BASE

Step 2

INPUT thc value of HEIGHT

Step 3

Calculate AREA = BASE * HEIGHT

S::p 4

P E N T the value of

Siep 5

END

Height

0
ESD

Introduction to Pmgrammlng
Language Concepts

(ii) NOmodel answei.


(iii)
Step 1

INPUT the value of M and N

Step 2

Initialize variable SUM to zero

Step 3

Check whether M is less than and equal to N if M is less


than N then execute next step otherwise GOTO Step 9

Step 4

Multiply M with itself and assign the result to SQR

Step 5

Take sum of SQR

Step 6

Increment M by 1

Step7

GOT0 Step 4 i.e. continue multiplication and addition till M is less and
equal to N

Step 8

PRINT SUM

Step 9

END

Flowchart

'5

Input MJ

I
SUM = SUM

+ SQR

R q n m m i n g Concepts and
Software Tools

(iv)
2.

No model answer.
(i) Step 1 and Step 2 are Input parts.
Step 4 is Output part.
Step 3 is Processing part.
(ii) No model answer.
(iii) No model answer.

Check Your Progress 2

1. (i) Looping statementsare provided in a programming language to support execution of


statement(s) repeatedly.
2. No model answer.

3. (i

Array provides a very simple and efficient way of refemng to and performing
computation on collection of data that have got some common attributes.

(ii) A(3)
A(l)
A(2)
A(I)
4.

= A(2) + A( 1)
=5
= 5 * A(1)
= A(1) + 6

Nomodelanswer.

1.10

FURTHER READINGS

1. T.W.Pratt - Programming Languages, Design and Implementation PHI.

2. R. G. Dromey - How to solve by computer - PHI


a

You might also like