Chapter-2: Elements of Computer Programming-I
Chapter-2: Elements of Computer Programming-I
Key Words: flow charts, algorithms, computer programs, do loops,if statements, compilation,
execution, input, output, programming errors.
2.1 Introduction.
In this chapter we will outline the basic principles of computer programming for numerical computations
A program (or software) is a sequenceof instructions or operationswhich are so organized that they
are executed or carried out on a computer. Consider the example of finding the largest of 3 numbers.
Here, we need to read the three numbers, compare them with one another and write the largest number of
the computer screen or a computer file. Take another example of program for calculating product of two
6x6 matrices. In this program, we have to input the values of elements of the two matrices to the program.
The program has the code or the steps or the statements (program lines) to find the elements of the
product matrix and write out the results either on the computer screen or in a file on the computer. On the
other hand, there could be very complex programora commercial ‘package’ such as the one that handles
the Indian railway reservations. The program runs on some “large” computer referred to as a server. The
program has the complete information on the availability of the seats on all the trains. A person wanting
1
to reserve a seat or a berth logs into the system through the internet (using which he/she has already
created an account on the reservation system’s program), gives the information required for reservation. If
areservation is available as required, he gets an output on the screen, which is the ticket which can be
printed out. Of course, he/she has to pay the required amount through internet banking. Such a program
has tremendous advantages over the laborious book keeping methods that were used in the past.
We can conclude from above that some of the ingredients in a program are input, output, repeated
operations (such as computing each element of a matrix one by one), comparisons (is the seat available or
not available), information storage, doing mathematical operations such as additions, multiplications and
other functions such as those found on a calculator. Using these features, it is possible to design or write
programs for assisting highly complex functions such as automatic landing on the moon or running
There are several programming languages such as FORTRAN (formula translation), C++, and
java. Some languages, such as basic or Pascal are becoming obsolete. New languages may emerge. Our
emphasis here will be on programming logic. While we will use mostly FORTRAN, we will also try to
illustrate with otherlanguages too.We will prefer to use the Linux operating system as it is available freely
in public domain. The compilers (for FORTRAN, C++, and java) which convert the program code into a
form/file that can be executed on the computer (such a file is called an executable file) are freely available
and so are the software such as Scilab, Xmgrace and Avogadro, whose use we will illustrate in Chapters 8
and 9.
2.2 Algorithms
In the earlier days of programming, it was a common practice to prepare the flow chart for a task you
want to carry out. The important preparation before writing program is to know the algorithm for solving
2
the problem at hand. An algorithm is a set of well-defined steps that need to be carried out for solving a
problem.The program expresses the algorithm in a suitable programming language. Of course, the steps
a) If the value of a real number x is negative i.e. if x<0, then its absolute value is –x
In the above statements, statement ‘a’ is unambiguous and statement b is vague, because if the object
‘w’ is a word, we cannot take its square root. If the object ‘w’ is a negative number, again the square
root is a problem, unless we are dealing with complex numbers. Consider two examples of
algorithms.
Example 2: Finding the Fibonacci series with F(1) = 1, F(2) = 2 and F(n) = F(n-1) + F(n-2) for n = 3,4,5
….
Step 1: Initialise the first two members of the Fibonacci series as F(1) = 1, F(2).
Step 2: Ascertain the total number of members of the series that you want to calculate, let us say 100.
Step 3: n = 3
3
Step 6: If n is less than 101, go to step 4.
y= x + z / c + a * b
r = d ** f
t = sqrt (23.0)
a=a+b
In line 1, adding, dividing (/), multiplying (*) and equating (= implies replace the lhs [left hand side]
variable by the value calculated on the rhs [right hand side]) are the operations that are being carried out.
In mathematics a = a + b is wrong but it is perfectly fine in a computer program because the meaning of a
= a + b is replace the value of ‘a’ by the value of a + b. The second line indicates the sin and log functions
and the names of variables are theta and conc. In FORTRAN, variables beginning with i, j, k, l, m and n
as the first letters are integer variables. Another vital feature is that you begin typing from the
seventhcolumn and not the first. Each programming language comes with its own peculiarities! With the
passage of time, the peculiarities have decreased and there are searches for more “universal” languages.
4
The third line uses the exponentiation function. The forth line is the FORTRAN expression for
raising d to the power fof df. The fifth line has the square root function.
To run a program that does the above operations, we need to do a few more things.
1) Firstly the program has to know the values of variables x, z, a, b, etc. This can be done either by
assigning values to these variables at the beginning of the program or read their values from the
3) The program should have an end statement. And most important, we need to convert the
A program written in fortran also needs to have an extension .f , e.g. the file name should be prog.f. On a
Linux system you can use the Pico or the vi editor to create a file as follows.
program test
read(*,*)x,z,c,a,b,theta,conc,energy,
1boltz,temp,d,f
y=x+z/c+a*b
r=d**f
t = sqrt (23.0)
5
a=a+b
write(*,*)y,p,q,r,t,a
stop
end
[In newer versions of Fortran, the stop statement (the statement before the end statement) may be left out]
On some linux systems, f77 may not be available, but the compiler gfortran may be available. In some
cases, you may need to install these files. In the case of gfortrran compiler, the compilation statement will
be
gfortran prog.f
The ls command lists all the files in the present working directory.
After this, you need to input the values of x, z and the other variables on the screen.
If these values are 2.0, 3.0, 5.0, 6.0, 9.0, 30.0, 0.2, 10.0, 8.314, 298.0, 2.0and 3.0 (a total of 12 quantities),
see what will be the values of the output on the screen.
Note:
1) The read statement in the program extends beyond one line. To continue the statement on the
second line, type character such as 1 at the sixth column of the next line and continue typing.
2) Whenever quantities with units are used, ensure that proper care is taken. In the data, energy was
in J/ mol and hence the value of boltz is 8.314 J/ (mol. K) and temperature is in K.
3) a.out is an executable file and the execution of the program is done by typing ./a.out
6
When using the computer screen for input or output, it is convenient to print out sentences or
questions which will prompt you (i.e, the programmer)to give the correct input and indicate the nature
Read (*, *) n
In the above lines the string of characters between the single quotation marks ‘….’ are printed
The power of computing comes from the ability to perform repeated operations quickly and the
designs in the programs for conditional flow of control in the program. These two aspects will be
illustrated with examples below. The meaning of (*,*) will be elaborated later. It means that the
reading or the writing of the variables is done from the computer screen.The data entry is of course
2.5 Do loops
Suppose we want to calculate the value of sin (x) for values of x ranging from 0 to 2π.The values
of ‘x’ are to be given in radians. The default unit (i.e, the natural unit when nothing else is specified) of
the angle in the trigonometric functions is radians.If there are only a few values of x, we can calculate sin
(x) for each of those values and print them. However, if there are 100 or more values of x, we cannot
write a 200 line program just for these repeated identical calculations. These are done by what are called
7
c calculate the value of sin (x) at 101equispaced points between 0 and 2pi (including the end points).
c there are higher precisions and are used occasionally when more accurate results are needed
do 10 i =1, 101
y = sin (x)
write (*, *) ‘step number and the values of x and sin (x) are =’, i, x, y
10 continue
end
The meaning of the do 10 i =1, 101 is: repeat the operations till theline which is labeled 10 (the
line numbers are placed in columns 1 to 5) starting with the value of i=1 and ending with the value 101.
When the flow of the control in the program reaches 10 continue, the flow goes back to the do statement
and increments the value of the do loop variable i by 1. When i is 102, the flow does not go back to the do
statement, but to the statement following (or next to) the do statement. In place of the 10 continue, we
do 10 i=1, 101,1
y= sin (x)
real(i) is not required, we could just use ‘i’. It is however a god practice to convert real to integer and
integer to real whenever the programming steps necessitate it and obtained the same result. In the above
8
program line numbered 10 is an executable statement and the continue statement is not needed. We have
used real (i) which is a function that gives the real value of i i.e. 1.0 in place of 1 which is an integer. We
need to carefully distinguish between real, integer and other types of variables. Another feature was in
theline do 10i =1, 100, 1 here, the last part ‘1’ indicates that i is incremented by 1 every time. If we want
do 10 i=1, 100, 2
There are other alternatives to the do statement such as the one given below.
sum=0.0
do i=1, 100
end do
What does this program do? It adds the cubes of the first hundred integers (using the arithmetic of real
numbers).
Here, there are no line numbers. There are ‘do’ and ‘enddo’ statements which do the same work
9
The‘if’ statement allows the branching of the flow of control in the program. Ordinarily the flow is top to
bottom, i.e. from one line to the next line below it. Consider the following function of x, a function
f (x) = x if x ≥ 10
16
14
12
10
f (x) 8
6
4
2
0 x
-15 -10 -5 0 5 10 15 20
We need to write a program which gives the value of f(x) as per the above formula. This is given below.
read (*, *) x
if (x.lt.0.0) then
funct = 0.0
funct = 10.0
else
funct = x
endif
end
Please note the indentation conventions used above. These conventions enable one to easily
The symbols .lt., .eq. , .gt. , .ge. and .and. are relational statements(actually, operators). The
group of statements between ‘if ’ … and ‘endif ’is called an ‘ if block ’and it and executes the branching
or the distribution (or redirection) of the flow of control as per the conditions satisfied.
11
program quadratic
read (*, *) a, b, c
x = -c/b
twoa=2.0*a
go to 100
go to 100
endif
ww = b * b - 4.0 * a * c
go to 50
else
go to 100
endif
50 continue
12
c the roots are complex b**2 - 4 * a * c is -ve
ww = 4.0 * a * c - b * b
realpt = -b / twoa
impt2 = -impt
100 continue
end
separately at the beginning. Next, real roots are calculated when 𝑏𝑏2 − 4𝑎𝑎𝑎𝑎 > 0.
Once the calculation is completed, go to statement is used to send the flow of control to line
labeled 100 or 50 as the case may be. In modern programming, line numbers are avoided as it is
harder to debug a program where there is repeated branching. It is better to divide the program
into several modules called functions or subroutines (subprograms or procedures) and access
2.8 Summary
13
Perhaps a day will soon come when you can ask a computer to do the desired tasks by
speaking into the computer. But until such time, the instructions have to be given to a computer
computer are storage of a large amount of data and doing repeated operations until the user’s
criteria are satisfied. For example, you may want to do an SCF (self consistent field) calculation
until the calculated energies are accurate to better than 1 part in a billion. Or, you may want to
calculate the molecular dynamics (MD) trajectory of a liquid system for a time span of a
nanosecond. The main ingredients of a program are 1) an instruction to carry out a mathematical
calculation until a condition is satisfied, 3) allocation of storage space for calculated quantities
such as the integrals evaluated in an SCF calculation or the coordinates and velocities in an MD
trajectory, 4) reading inputs from files and writing the output to files as well as the computer
screen, 5) terminating the program either on completion or giving messages if something has
gone wrong with the execution of the program. For getting a program in an executable mode, the
program written in a programming language has to be converted into an executable file. Suitable
compilers are available for performing this task. A compiler converts a program in a high level
language (such as Fortrtan, C, Java, etc) into a machine level code. This machine level code can
not be edited as we edit a fortran program. If there is a programming error (you will see these in
abundance), the program has to be corrected and recompiled. The machine level code is referred
to as an executable file and you will see it as an a.out filelisted in your directory. It will be nice
tofamiliarise yourself with the common unix/linux commands as mkdir, ls –l, rm, mv, cp. Also,
14
distinguish between the insert mode and the edit mode of the vi editor.It will also be very good if
2.9 Problems
1. For standard mathematical operations, a programming language will have symbols to
carry out the operation. The following list will illustrate the operations with examples
y = a x 2 + e- x + z + 6
w - z / log ( x)
The log and ln functions are different.Notice that the expression has several algebraic
operations. In FORTRAN language, this will be expressed as
Rising to a power is done using the symbols **. Exponentiation is done using exp, square
root through the symbol sqrt and logarithm through alog. One has to ensure that one does
not take the square root of a negative number and not take the logarithm of zero.
2. Calculate the value of the hydrogen 1s and 2s orbitals for values of r ranging from zero to
10 angstroms at the interval of 0.1 angstrom.Take theformulaeof the orbitals along with
the normalization constants from any physical chemistry book. The exponential part has
the term r/a 0 , where r is in Angstroms and a 0 is theBohr radius equal to 0.529 Angstroms.
4. Write a program to convert Joules into eV, kcal/mol, hartree(a.u), and cm-1.
5. Write a program to read the radius of a circle and compute its area and circumference.
15
7. A cylindrical tub of diameter d has water filled up to a height of 0.2m. If a tap is opened
to fill it and water flows at the rate of 2 liters/min, find the height to which it will be filled
after 5 minutes. [ f * t = π r2 h]
f = volume of water flowing per minute, t = time in minutes, h = height of water level.
α
a. cos (ω t + φ )
α 2 +ω2
x
b. log c
yz
1 − e −α x
c. −x
1 + xe
11. Write a program to find the sum of the individual digits of a 5 digit number.
a. log10 x + cos 32 o + x 2 + y 2 + 2 xy
1 2σ ( x −m )2
b. e
a 2π
13. Write a program to find the polar coordinates θ and r of a given point whose Cartesian
r= x2 + y2 , θ = tan −1 ( y x)
14. Given a point (x, y), write a program to find out if it lies on the x- axis, y- axis or at the origin.
16
15. Extend the above program to check if a given point (x, y) lies in the 1st, 2nd, 3rd or 4th quadrant.
17