Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 46

ajayiprogrammer@gmail.

com

SCIENTIFIC
PROGRAMMING
(using FORTRAN)

AJAYI Olusola Olajide, PhD


OND, B.SC., M.SC., PhD
MACM, MIEEE, MPSF, MCSTA, MIACSIT, MMCS
(Lecturer, CSC Dept., AAUA)
olusola.ajayi@aaua.edu.ng
ajayicomputer@gmail.com
ajayiprogrammer@gmail.com

Scientific programming (fortran) 1


ajayiprogrammer@gmail.com

COURSE OUTLINE

Chapter One: Programming Paradigms

Programming and Programming Languages

Programming Paradigms

Prerequisites to Programming: Pseudocode & Algorithm

Chapter Two: Programming in Fortran: The Basis

Variables

Data Types

Declarations and Commenting

Expressions and Statements (Arithmetic, Logical Statements etc.)

Chapter Three: The coding points

Simple I/O Statements in Fortran

Formatted I/O Statements in Fortran

Chapter Four: Control Structure

Introduction / Definitions

Types

Programming in Structured Form in Fortran

Chapter Five: Array Structure

Introduction / Definitions

Types

Array programming in Fortran

Scientific programming (fortran) 2


ajayiprogrammer@gmail.com

CHAPTER ONE

PROGRAMMING PARADIGMS

Programming Paradigms

 Programming and Programming Languages

 Programming Paradigms

 Prerequisites to Programming: Pseudocode & Algorithm

1.1 Programming & Programming Languages

1.1.1 What is Programming?

Programming can be viewed as an act of coding solution for a problem. It can also be defined as

an act of giving instruction to the computer to carry out a task.

It simply implies the ability of a programmer to communicate with the computer system in a

particular programming language.

It is a transformational act that brings about changes in the status of task – e.g. manual task to

computational one.

- Related Concepts to Programming

PROGRAM: This implies the written instruction, which the computer takes in and act upon. It

has the synonyms CODE.

PROGRAMMER: This is a person that indulges in coding for solutions. He is regarded as an

expert in writing computer codes. His major responsible is to write programs that performs a

given or specified function.

1.1.2 Programming Languages

Scientific programming (fortran) 3


ajayiprogrammer@gmail.com

These indicate the language of choice for which the programmer communicates with the

computer machine.

In other words, programming language refers to the language with which a programmer codes.

Programming Languages - Types

We have 3 types:

 Machine Language

 Low-Level Language

 High Level Language

Machine Language (ML)

This refers to the language which the computer understands. It is a language in which all

codes/instructions are represented in the form of 0s and 1s.

Low-Level Language (LLL)

This language is very much close to machine language. It needs little translator to real machine

language. It is regarded as SYMBOLIC Language. A good and common example is the

ASSEMBLY Language.

High-Level Language (HLL)

This is a language that is close to normal human English Language. It isn’t a languages the

computer understands, rather it needs the help of an interpreter or a compiler before computer

could understand it. Examples here includes QBasic (Quick – Beginners’ All Purpose Symbolic

and Instruction Code), Fortran (FORmulaTRANslator), Pascal (Delphi), Java, C, C++, C#,

Python, Ada, Eiffel, PHP (Hypertext PreProcessor), COBOL etc.

Scientific programming (fortran) 4


ajayiprogrammer@gmail.com

1.2 Programming Paradigms

Programming Paradigms imply trend & evolution of programming languages.

Early Program Development => Machine Language

1st Program Developed => Assembly Language

Real Program Developed => Fortran (1954) John Backus & IBM Team.

Subsequent Breakthru => Algol60 (1960)

Programming Paradigms can be captured under the following under-listed programming

paradigms

IMPERATIVE PROGRAMMING

This is the type of programming that deals with scientific computation i.e. It is found useful in

handling mathematical computation. In this programming language, assignment, sequence and

control statement are very important.

Examples of this programming paradigm are: FORTRAN, COBOL ,C / C++ and PASCAL

OBJECT ORIENTED PROGRAMMING (OOP)

This is a type of programming in which object interact by sending messages that change their

state. In this programming type, inheritance, polymorphism and object modeling are essential

element.

Examples of programming languages in this paradigm include: C++, JAVA, SMALLTALK,

EIFFEL, PHP & VISUAL BASIC.NET

FUNCTIONAL PROGRAMMING

This programming paradigms deals with mathematical functions in which the domain serves as

the input and the range serves as the output.

Scientific programming (fortran) 5


ajayiprogrammer@gmail.com

Example of this programming paradigm includes: LISP, SCHEME, HASKEL, MIRANDA,

MAPLE, MATHEMATICA and MATLAB.

LOGIC / DECLARATIVE PROGRAMMING

This programming paradigms deal with collection of logical declaration about what outcome a

function should accomplish.

Example of this paradigm includes: PROLOG, SEQUEL, SQL and RPG

EVENT-DRIVEN PROGRAMMING

This programming paradigms deals with design of program that respond to unpredictable events.

These event are normally generated from users’ actions e.g. mouse click, key press.

Example of this paradigm includes: VISUAL BASIC, VISUAL BASIC.NET, VISUAL C++,

VISUAL C#, & JAVA

CONCURRENT PROGRAMMING

This programming paradigm deals with collection of cooperating process by sharing resources

(information) but operating asynchronously.

Example of programming languages in this group include: LINDA, CONCURRENT PASCAL

(DELPHI), HIGH PERFORMANCE FORTRAN and JAVA

1.3 Programming Language Application Domains

These include:

• Scientific Programming (SP)

• Management information system (MIS)

• Artificial Intelligence (AI)

Scientific programming (fortran) 6


ajayiprogrammer@gmail.com

• System Programming (SP)

• Web-centric Programming (WP)

Programming Language Application Domains…

SCIENTIFIC PROGRAMMING: This is programming language that is used for handling

complex computations. They are also very useful for teaching and learning. Example of this

programming language includes: FORTRAN, COBOL, PASCAL, C and BASIC

NOTE: Scientific programming falls under imperative programming paradigm

MANAGEMENT INFORMATION SYSTEM: This are program that are used for handling

organization information system e.g. payroll system, accounting system, inventory system,

online sale and marketing system. Example of this programming language includes: SQL,

COBOL and RPG.

NOTE: MIS falls under logic / declarative programming paradigm

ARTIFICIAL INTELLIGENCE: This are programming types that are used to develop

software that model after human intelligent behavior e.g. robot. Example of this programming

language includes: LISP, PROLOG, MATLAB and SCHEME.

NOTE: AI falls under programming language paradigm of functional and logic programming

language.

SYSTEM PROGRAMMING: This is a programming type which assist in the design and

development of software on which other software runs i.e. system programming deals with

developing software that act as platform on which other programs runs.

Examples are OS SOFTWARE, NETWORK SOFTWARE, INTERPRETER AND COMPILER.

A Common example of programming language use is C.

NOTE: SP falls under imperative programming language paradigm.

Scientific programming (fortran) 7


ajayiprogrammer@gmail.com

WEB-CENTRIC: This programming type involves developing programs that run on the

internet. Web-centric programming is like a two-edged sword, as it derives from both OOP and

Event-driven programming paradigm.

Programming languages used include: JAVA, VISUAL BASIC, VISUAL BASIC.NET, PHP,

HTML, JAVASCRIPT and C++ etc.

Web-Centric falls under OOP and Event-Driven Paradigms

1.4 Programming Languages and their Inventors

ADA: It was invented in 1982 by CHARLES BABBAGE but was named after a woman called

ADA

ALGOL: (Algorithmitic language) It was design by a committee in 1960.

APL: (A programming language) It was design to handle matrix calculation and the designer is

named KENNETH IVERSON in the early 1960s.

LISP: (List processing) it was invented in 1960 by JOHN McCARTHY

1.5 Pre-requisite to Programming

PSEUDOCODE

Pseudocode does the same function as Algorithm but the language of expression differs. While in

algorithm, more technical terms are used, raw English-like statements are used in Pseudocode.

While algorithm expressions are formal that of Pseudocode sounds informal.

Scientific programming (fortran) 8


ajayiprogrammer@gmail.com

PSEUDOCODE - ILLUSTRATION

1) Literally, take for instance if you are hungry and intend ‘executing’ a rice – what are the

psudocode steps/procedures for ensuring this? (varied depending on how you want to

program to flow and be implemented).

2) Design a pseudocode that solves the need to compute for the scores of ten (10) students in

CSC101, MAT101 and PHY101, computing their average scores.

SOLUTION I

i. Clean up / Prepare the utensils for the cooking

ii. Lit the stove/cooker

iii. Put water in the pot and place on the cooker

iv. Wash the rice in a basin and put unto the water-pot

v. Depending on the type of rice been cooked, put salt or any other ingredient.

vi. Cook to taste

vii. When done, Stop/End Cooking

SOLUTION II

i. Get the scores in the 3courses

ii. Carry out their calculations – their sum

iii. From there, compute their average

iv. Continue this steps until there is no more student to input for

v. Output the result

vi. Stop the process

Scientific programming (fortran) 9


ajayiprogrammer@gmail.com

ALGORITHM

Algorithms are sequence of steps taken in solving a problem. It involves highlighting intended

action(s) for executing a task.

In programming context, an algorithm can be described as a guide to logical coding that yields

the intended implementation.

PSEUDOCODE - ILLUSTRATION

Literally, take for instance if you are hungry and intend ‘executing’ a rice – what are the

algorithmic steps/procedures for ensuring this? (varied depending on how u want to program to

flow and be implemented).

Design an algorithm that solves the need to compute for the scores of ten (10) students in

CSC101, MAT101 and PHY101, computing their average scores.

SOLUTION I

Set utensils = Available

Set stove/cooker ON

Cooker = Water-Pot + Water

Water-Pot = Rice

If Rice requires Salt, Then Insert

Else Put/Insert other Ingredients

Set Cooking = Max Level/Time

If Cooking = ‘DONE’ Then STOP/END Cooking

Else CONTINUE Cooking

Scientific programming (fortran) 10


ajayiprogrammer@gmail.com

SOLUTION II

Enter/Input Value for CSC101, MAT101 and PHY101 scores

Set Sum = CSC101 + MAT101 + PHY101

Set Average = Sum/3

Loop Until Student>10

Output to the screen

Stop

Converting Pseudocode/Algorithm to Program Solution

SOLUTION II – using QBasic

5 CLS

10 REM

12 LET N = 0

15 INPUT “Enter Value for CSC101”, csc

20 INPUT “Enter Value for MAT101”, mat

25 INPUT “Enter Value for PHY101”, phy

30 LET SUM = csc+mat+phy

35 LET AVG = SUM/3

40 PRINT “The sum of the 3courses is: ” SUM

45 PRINT “The average of the 3courses is: ” AVG

46 N = N + 1

47 IF N<=10 GOTO 15

50 END

Scientific programming (fortran) 11


ajayiprogrammer@gmail.com

Under Chapter Exercise (UCE) I

Student’s Name: _________________________________________________________

Dept.: __________________________ Level: ________ M_No: IPTP2019/CSC/____

Instruction #1: Fill in the spaces left above, use the information to submit your assignment,
especially the M_No (meaning Material No)

Instruction #2: Solve in a sheet of paper and submit with the requested info in Instruction #1

Instruction #3: Submit in a week’s time

Questions

(1) Write a Pseudocode and Algorithm to solve:

x2 + y3 – (z * w/2)

(2) Write a Pseudocode and Algorithm to compute a candidate’s age given the birthyear and

specifying the current year.

(3) Write a Pseudocode and Algorithm to accepts the UTME and PUTME scores of candidates,

screen out and compute as appropriate where:

(i) UTME must be >=180

(ii) PUTME must be >=40

(4) Convert 1, 2 and 3 to programming solution using QBasic.

Scientific programming (fortran) 12


ajayiprogrammer@gmail.com

CHAPTER TWO

PROGRAMMING IN FORTRAN: THE BASIS

 Variables

 Data Types

 Declarations and Commenting

 Expressions and Statements (Arithmetic, Logical Statements etc.)

2.1 VARIABLES

Variables are regarded as named storage locations that hold values.

The type/nature of data a variable holds depends on the data type description specified for the

variable.

The acceptability of a variable depends on its conformity to the rules that pertain to forming

variables.

So as we considered VARIABLE, we’ll be looking into:

 Character Sets

 Rules for forming Variable Names

2.1.1 Character Sets

These are sets of alphanumeric strings that are acceptable for use in coding/programming.

The underlisted are acceptable in FORTRAN:

Alphanumeric: Here we have:

Numbers: 0-9

Alphabetic: a-z or A-Z (not case sensitive, so, a-z is the same as A-Z)

Underscore: _ is also allowed

For instance: aj_file, shoprog1 etc.

Scientific programming (fortran) 13


ajayiprogrammer@gmail.com

2.1.1 Character Sets…

Symbols: Here we have special xters such as:

Arithmetic symbols: =, ., (, ), +, - /, %, * etc.

Logical Symbols: >, <, ! etc

Special Symbols: $, ?, “, :, ‘, etc

2.1.2 Rules for VN Formation

The followings are rules that govern the formation of Variable Names (VN):

• VN must start with letter; it cannot start with numeric/digit or underscore e.g. 7up, _myname

are not an acceptable variable names. But, up7, my_name & myname_ are all acceptable

• VN cannot be longer than 31xters.

• VN must be distinct within the program.

2.2 DATA TYPES

Data Types described the nature of data that would be stored in a variable. Specifying a particular

data type for a particular variable indicates the type of data permissible to be captured for that

variable during data entering.

In FORTRAN, we have the following data types:

 INTEGER: For specifying ‘pure’ numeric values/data.

 REAL: For specifying decimal values/data.

 COMPLEX: For specifying complex ‘scientific’ values/data.

 CHARACTER: For specifying single ‘string’/’letter’ value/data.


Scientific programming (fortran) 14
ajayiprogrammer@gmail.com

 CHARACTER (LEN): For specifying ‘string’/ ‘alphanumeric’ data with specified number

of expected characters.

 LOGICAL: For specifying ‘Boolean’/ ‘logical’ values/data.

2.3 DECLARATION AND COMMENTING

i. INTEGER:

e.g. INTEGER :: myscore (i.e. 68)

ii. REAL:

e.g. REAL :: water_volume (i.e. 7.5 in litres)

iii. COMPLEX:

e.g. COMPLEX :: x + 2.5y

iv. CHARACTER:

e.g. CHARACTER :: sex (i.e. ‘M’ or ‘F’)

v. CHARACTER (LEN):

e.g. CHARACTER (LEN= 30) :: stud_name (i.e. ARABANIBABAENIABALABANIBABA)

vi. LOGICAL:

e.g. LOGICAL :: power_on (i.e. expecting a TRUE/FALSE response)

2.3 DECLARATION AND COMMENTING

While DECLARING however:

(i) It should be noted that, first, your PROGRAM is first declared

e.g. PROGRAM name of program

i.e. PROGRAM myfirstFORTRAN

Scientific programming (fortran) 15


ajayiprogrammer@gmail.com

(ii) Declaring VARIABLEs in FORTRAN is expected to be explicit and therefore requires that

all VARIABLEs to be used must be declared. To indicate compliance with this, the FORTRAN

Compiler expects issuance of a command called IMPLICIT and it been set to NONE.

e.g IMPLICIT NONE

After these, the variables can now be declared.

However, for VARIABLES that are not explicitly defined, FORTRAN takes over the

responsibility of deciding their DATA TYPES (to know the type of data expected to be stored in

them). This, the compiler will do using this model:

• Variable names that start with the lettering I, J, K, L, M, N are auto-ascribed INTEGER

as the DATA TYPE.

• While variable names starting with other lettering (in the letter of alphabets) are taken

as REAL

So, decide/define it yourself, else FORTRAN does it for you!

COMMENTING

The REMARK/COMMENT sign in FORTRAN is: !

The format takes the shape:

! This is the comment/remark style in FORTRAN

! Whenever you see me, know that, am not executable

! Use me to enhance readability of your program

! Never ignore me, I can be a ‘torch’ to your program

2.4 EXPRESSION AND STATEMENT

Scientific programming (fortran) 16


ajayiprogrammer@gmail.com

Expression forms Statement.

Expressions are toward the right-hand side of our equation (without the identifier). They are

operands that are usually joined with/by operators

X + Y is an expression

We have:

• Arithmetic Expression

• Logical Expression

• Relational Expression

…bringing them together

Bringing the sections discussed so far together, we can have:

PROGRAM myfirstFORTRAN

! This is my first trial in FORTRAN programming

! Let me start with simple program of W = X/Y

IMPLICIT NONE

INTEGER :: X, Y !You can have them both in one

line, separated by comma

REAL :: W

! How do I now capture values for X & Y? Be patient till the next lecture/chapter.

CHAPTER THREE

THE CODING POINTS

Scientific programming (fortran) 17


ajayiprogrammer@gmail.com

 Simple I/O Statements in Fortran

 Formatted I/O Statements in Fortran

…promised earlier made (previous lecture)!

Bringing the sections discussed so far together, we can have:

PROGRAM myfirstFORTRAN

! This is my first trial in FORTRAN programming

! Let me start with simple program of W = X/Y

IMPLICIT NONE

INTEGER :: X, Y !You can have them both in one

line, separated by comma

REAL :: W

! How do I now capture values for X & Y? Be patient till the next lecture

SIMPLE I/O STATEMENT

OUTPUT STATEMENT

 The major output statement in Fortran are:

 Print, and

 Write Statements

While PRINT is used for achieving simple output statement, WRITE is more suitable for

formatted statement.

A Fortran program to illustrate simple use of PRINT and WRITE Statements (will be

done/shown on the board)

Scientific programming (fortran) 18


ajayiprogrammer@gmail.com

INPUT STATEMENT

 The major input statement in Fortran is:

 Read Statement (for capturing data)

Others will be discussed later under related chapter/topic.

Self-Programming Exercise (…in class/at home: be faithful and do it)

1) A Fortran program to calculate the area of a triangle.

2) A Fortran program to illustrate the use of the three (3) discussed commands, viz:

Read, Write and Print.

NB: Make your inputting interactive.

FORMATTED I/O STATEMENT

At our last lecture/session, we dwelt so much on Simple I/O Statements in FORTRAN, where we

demonstrated the use of READ, WRITE & PRINT.

FORMATTED I/O STATEMENT…illustration

To illustrate, let’s consider the equation and solve using FORTRAN:

Z = (((P + Q)/2) – ((R2 / S)/3))/5

Solution

program illustration
implicit none
integer::p,q,r,s
real::z
write(*,*) "Enter value for P: "
read (*, *) p
write (*,*) "Enter value for Q: "
read (*,*) q
write (*,*) "Enter value for R: "
read (*,*) r
write (*,*) "Enter value for S: "
read (*,*) s

Scientific programming (fortran) 19


ajayiprogrammer@gmail.com

z = ((((p+q)/2)-((r**2)/(s))/3))/5
print *,"The value of z is: ", z
end program illustration

FORMATTED I/O STATEMENT…illustration (d output)

FORMATTED I/O STATEMENT…Evaluation

As you examined the last output, you will observed that the output was without ‘control’. The

decimal placement was not taken care of by us but by the compiler.

To format output, we use the format specifier ‘f’ with appropriate specification as it relates to the

data type in use.

REAL FORMAT SPECIFIER

As stated earlier, the format specifier is ‘f’ specified alongside the data type. For REAL data

type, the specification is given as: fw.d OR rfw.d

Where:

f is the formatter; w is the total no of digit expected; and d is the no of decimal to the right;

where applicable, r implies no of repeat count

To modify the earlier program illustrated with:

Scientific programming (fortran) 20


ajayiprogrammer@gmail.com

Z = (((P + Q)/2) – ((R2 / S)/3))/5

The codes should look thus:

program illustration
implicit none
integer::p,q,r,s
real::z
write(*,*) "Enter value for P: "
read (*, *) p
write (*,*) "Enter value for Q: "
read (*,*) q
write (*,*) "Enter value for R: "
read (*,*) r
write (*,*) "Enter value for S: "
read (*,*) s
z = ((((p+q)/2)-((r**2)/(s))/3))/5
! little modification using write formatted statement
write(*,'(f6.2)') "The value of Z is: ", z
end program illustration

INTEGER FORMAT SPECIFIER

For INTEGER data type, the specification is given as:

fw OR rfw

Where:

f is the formatter; w is the total no of digit expected; where applicable, r implies no of

repeat count

To modify the earlier program illustrated with:

Z = (((P + Q)/2) – ((R2 / S)/3))/5

The codes should look thus:

program illustration
implicit none
integer::p,q,r,s
real::z

Scientific programming (fortran) 21


ajayiprogrammer@gmail.com

write(*,*) "Enter value for P: "


read (*, *) p
write (*,*) "Enter value for Q: "
read (*,*) q
write (*,*) "Enter value for R: "
read (*,*) r
write (*,*) "Enter value for S: "
read (*,*) s
z = ((((p+q)/2)-((r**2)/(s))/3))/5

! The modifications are here:

write (*,*) "The data inputted are:"


write (*,*)
write (*,'(4i3)') p,q,r,s
write (*,*)
write(*,'(f6.2)') "The value of Z is: ", z
end program illustration

WAITING FOR YOUR OUTPUT…!

Under Chapter Exercise (UCE) II

Student’s Name: _________________________________________________________

Dept.: __________________________ Level: ________ M_No: IPTP2019/CSC/____

Scientific programming (fortran) 22


ajayiprogrammer@gmail.com

Instruction #1: Fill in the spaces left above, use the information to submit your assignment,
especially the M_No (meaning Material No)

Instruction #2: Solve using the system, print out and submit with the requested info in #1

Instruction #3: Submit in two weeks’ time

Questions

Q1

Given three numbers, num1, num2 & num3. Captures values for them in an interactive way and

then compute: (i) their summation (ii) their product (iii) their average

Q2

On your own, input values for two variables X and Y. Find (i) their Division value (ii) the

summation of their squares (iii) their differences

Q3

‘Bring down’ your brain, device a mathematical problem on your own/by yourself, solve using

READ, WRITE & PRINT Statements.

Q4

Modify Q1 & Q2 above using FORMATTED STYLE.

CHAPTER FOUR

CONTROL STRUCTURE

 Introduction / Definitions

Scientific programming (fortran) 23


ajayiprogrammer@gmail.com

 Types

 Programming in Structured Form in Fortran

INTRO / DEF

Control Structure can be defined as statements that caused diversion in the normal flow of

program execution. They can be seen or described as program constructs that change or obstruct

the original intended pattern of program flow.

TYPES

According to the Control Structured Theorem, we have two types:

 Selection/Branching Control Statement

 Iterative/Repetitive Control Statement

Illustrating a program without control construct (sequential program)

A fortran program to calculate the sum of squares and sum of roots of two variables X and Y.

…illustrating the codes

program loop_prog1
implicit none
real::x,y,sumsquare,sumroot
write(*,*) "Enter value for X: "
read(*,*)x
write(*,*) "Enter value for Y: "
read(*,*)y
sumsquare = (x**2)+(y**2)
sumroot = sqrt(x)+sqrt(y)
write (*,*) "The sum of square of the two variables is: ",sumsquare
write (*,*)
write (*,*) "The sum of roots of the two variables is: ", sumroot
end program loop_prog1

…the output

Scientific programming (fortran) 24


ajayiprogrammer@gmail.com

TYPES…

Selection C. S.

These are control statements that bring about changes in the normal flow of program execution

based on the truthfulness of falsity of the condition specified.

They caused branching depending on the outcome of the evaluation of the condition specified.

TYPES…Selection C. S.

We have:

i. IF – THEN Selection C. S.

ii. IF – THEN – ELSE Selection C. S.

iii. IF – THEN – ELSEIF Selection C. S.

iv. SELECT-CASE Selection C. S.

IF-THEN

Scientific programming (fortran) 25


ajayiprogrammer@gmail.com

This is a mono-directional selection control statement in which only an option is presented for

execution and it is executed iff the evaluation of the condition specified is TRUE, else no

execution is carried out.

Format:

IF-THEN format

If (condition) Then

program statement

End If

Program Illustration

IF-THEN program illustration

A fortran program to compute the value of z based on the magnitude comparison

of x and y

…d codes

PROGRAM controlprog1
implicit none
integer::x,y,z
write(*,*) "Enter 1st value: "
read (*,*)x
write(*,*) "Enter 2nd value: "
read (*,*)y
if (x .gt. y) then
z=x+y
end if
write(*,*) "The value of z is: ", z
end program controlprog1

…d output!

Scientific programming (fortran) 26


ajayiprogrammer@gmail.com

IF-THEN-ELSE

This is a bi-directional selection control statement in which two options are presented but only

one can be executed at a time based on the result of the condition specified.

Format:

IF-THEN-ELSE format

If (condition) Then

program statement 1

Else

program statement 2

End If

Program Illustration

IF-THEN-ELSE program illustration

An enhancement to the program in slide 14

…d codes

Scientific programming (fortran) 27


ajayiprogrammer@gmail.com

PROGRAM controlprog2
implicit none
integer::x,y,z
write(*,*) "Enter 1st value: "
read (*,*)x
write(*,*) "Enter 2nd value: "
read (*,*)y
if (x .gt. y) then
z=x+y
else
z=x-y
end if
write(*,*) "The value of z is: ", z
end program controlprog2

…d output!

IF-THEN-ELSEIF

This is a multi-directional selection control statement in which many options are presented but

only one can be executed at a time based on the result of the condition specified.

Format:

Scientific programming (fortran) 28


ajayiprogrammer@gmail.com

IF-THEN-ELSEIF format

If (condition) Then

program statement 1

Elseif (condition) Then

program statement 2

Elseif (condition) Then

program statement 3

Else

program statement n

End If

Program Illustration

IF-THEN-ELSEIF program illustration

An enhancement to the previous program

…d codes

PROGRAM controlprog2
implicit none
integer::x,y,z
write(*,*) "Enter 1st value: "
read (*,*)x
write(*,*) "Enter 2nd value: "
read (*,*)y
if (x .gt. y) then
z=x+y
elseif (x .lt. y) then
z=x-y
else
z=x
end if
write(*,*) "The value of z is: ", z
end program controlprog2
…d output

Scientific programming (fortran) 29


ajayiprogrammer@gmail.com

SELECT CASE

This is also a multi-directional selection control statement in which many options are presented

but only one can be executed at a time based on the result of the condition specified.

SELECT CASE format

Select Case (case variable)


Case (Case no e.g. 1)
program statement 1
Case (Case no e.g. 2)
program statement 2


Case (Case no e.g. n)
program statement n
Case Default
//in case no valid no was selected/chosen, specify the action to be taken
End Select

Program Illustration

Scientific programming (fortran) 30


ajayiprogrammer@gmail.com

SELECT CASE program illustration

A fortran program to implement a computing service operation, which allows users to specify

their desired/choice operations in the list of operations.

TYPES…Selection C. S. (d codes)

PROGRAM controlprog3
implicit none
integer::x,y, opcode
real::z
write(*,*) "Enter opcode: 1 for ADD, 2 for SUB, 3 for PROD, 4 for DIV"
read (*,*)opcode
write(*,*) "Enter 1st value: "
read (*,*)x
write(*,*) "Enter 2nd value: "
read (*,*)y

…d codes…

select case (opcode)


case (1)
z = x+y
write(*,*) "The sum is: ", z
case (2)
z = x-y
write(*,*) "The difference is: ", z
case (3)
z = x*y
write(*,*) "The product is: ", z
case (4)
z = x/y
write(*,*) "The division is: ", z
case default
write(*,*) "Sorry, u selected wrong opcode, pls redo!"
end select
end program controlprog3

…d output!

Scientific programming (fortran) 31


ajayiprogrammer@gmail.com

Iterative C. S.

These are control statements that are used for repetitive execution of program statements. They

are otherwise called Repetitive Control Statement.

We have:

 Do…Counter Statement

 Do…Conditional Statement

Do…Counter Statement

As the name suggests, counter variable is used alongside the DO Statement specification.

The format is:

Do (counter variable) = initial value, final value, incremental value

….code goes here

End do

Illustration

Write a fortran program to compute the sum of the first five (5) even integers.

…d codes!

Scientific programming (fortran) 32


ajayiprogrammer@gmail.com

program do_counter_pro
implicit none
integer::count_var,sumeven=0
write (*,*) "The even numbers are: "
do count_var = 2,10,2
sumeven = sumeven + count_var
write (*,*)
write (*,*)count_var
end do
write(*,*)
write (*,*) "Their sum is: ", sumeven
end program do_counter_pro

…d output!

Do-Counter (Complementary Commands)

IF-EXIT: This is used to break/terminate a Do-Counter Loop. Execution got terminated

on reach of the If specification.

IF-CYCLE: This is used to skip/jump a Do-Counter Loop. Execution got skipped at the

true evaluation of the If specification and continues.

IF-EXIT: (format)

Scientific programming (fortran) 33


ajayiprogrammer@gmail.com

do counter = ..., ..., ...

if (condition) exit

end do

IF-CYCLE: (format)

do counter = …, …, …

if (condition) cycle

end do

IF-EXIT: (Illustration)

A fortran program to select the first five (5) students

IF-EXIT: d codes…

program if_exit_pro
implicit none
integer::matno
write (*,*) "The First Five are: "
do matno = 160404001,160404020
if(matno>160404005)exit
write (*,*)"No.", matno - 160404000, " ", matno
end do
end program if_exit_pro

IF-EXIT: d output!

IF-CYCLE: (Illustration)

Scientific programming (fortran) 34


ajayiprogrammer@gmail.com

A fortran program to expunge certain students: e.g 160404004, 160404008, 160404016,


140404020
IF-CYCLE: d codes!

program if_cycle_pro
implicit none
integer::matno
write (*,*) "The Eligible Students are: "
do matno = 160404001,160404020
if(matno==160404004 .or. matno==160404008 .or. matno==160404016 .or.
matno ==160404020)cycle
write (*,*)matno
end do
end program if_cycle_pro

IF-CYCLE: d output!

Do…Conditional Statement

As the name sounds, a condition is attached alongside the DO Statement specification.

Specifically, we make use of the WHILE Statement.

The format is:

Do while (condition)
….code goes here
End do

Do…Conditional Statement (do it as class/home exercises and be faithful to it)

Scientific programming (fortran) 35


ajayiprogrammer@gmail.com

i. Converts all the class illustration programs (using Do-Counter) to Do-Conditional

programs.

ii. Converts all the Do_Counter Supplementary Commands (if-exit and if-cycle)

program illustrations to Do-Conditional (if-exit and if-cycle) programs.

Note: In using If-exit and if-cycle under Do-Conditional, the while statement will not be used.

e.g.

do
program statement
if(condition) if-exit or if-cycle
end do

Under Chapter Exercise (UCE) III

Scientific programming (fortran) 36


ajayiprogrammer@gmail.com

Student’s Name: _________________________________________________________

Dept.: __________________________ Level: ________ M_No: IPTP2019/CSC/____

Instruction #1: Fill in the spaces left above, use the information to submit your assignment,
especially the M_No (meaning Material No)

Instruction #2: Solve using the system, print out and submit with the requested info in #1

Instruction #3: Submit in three weeks’ time

Questions

Q1

Write a fortran program to compute the sum of the first ten (10) odd integers.

Q2

Write a fortran program to compute the sum of the first ten (10) integers.

Q3

Modify the program in page 35 such that it outputs only the expunge students and title the

heading as appropriate.

Q4

Given the table below, code in Fortran to output candidates based on company policies

that absorbed Male and Female that are less than 30years and of High Experience.

CHAPTER FIVE

Scientific programming (fortran) 37


ajayiprogrammer@gmail.com

ARRAY STRUCTURE

 Introduction / Definitions

 Types

 Array Programming in Fortran

DEFINITIONS

An array is a collection of data element, captured with the same name (storage location name)

and having the same data type.

The nature of data stored in an array depicts the type of array been created (i.e. numeric array,

string array etc.)

PICTORIAL REPRESENTATION

TYPES

We have two divisions of array:

One Dimensional Array OR Linear Array

Multidimensional Array OR Matrix

LINEAR ARRAY

An array that consist of a one-columnar set of data.

DECLARING AN ARRAY

Declaration with Initialization

data type, DIMENSION (size of the array)::array_name=(/values/)

e.g.

integer, dimension (4):: mydata = (/6, 9, 4, 13/)

Declaration with Initialization…Element Specification/Accessing

Scientific programming (fortran) 38


ajayiprogrammer@gmail.com

Array_name(m:n) – means from element m to element n

Array_name(m:n:2) – means from element m to element n step2

Array_name(:) – means all elements

Array_name(::3) – means all elements step3

ILLUSTRATION I

PROGRAM array_pro2
implicit none
INTEGER, DIMENSION (6):: my_elements=(/4,6,2,8,9,34/)
write (*,*) "The whole elements are (all elements): ", my_elements(:)
write (*,*) "Sub-section of the array (from d 2nd to d 5th step1): ", my_elements(2:5:1)
write (*,*) "Sub-section of the array (from d 1st element to d last step2): ", my_elements(::2)
end program array_pro2

…output

Declaration without Initialization

data type, DIMENSION (size of the array)::array_name


e.g.
integer, dimension (4):: mydata
NB: Unlike in most other programming languages, To capture data into array, ARRAY INDEX

starts from 1 and not 0.

Declaration without Initialization … Illustrating (Codes)

Scientific programming (fortran) 39


ajayiprogrammer@gmail.com

…d codes…

PROGRAM array_pro3
implicit none
INTEGER, DIMENSION (5):: my_array
INTEGER :: i
write(*,*) "Capturing Data into the Array"
write(*,*)
do i = 1,5
write (*,*) "Element ", i, " : "
read (*,*)my_array(i)
end do
end program array_pro3

..d output…

SPECIFIC ARRAY OPERATIONS

Some of the array operations that can be performed on ARRAY include but not limited to:

MAXVAL: Highest element in the array

MINVAL: opposite of MAXVAL

SUMVAL: Sum total of the elements of the array

SPECIFIC ARRAY OPERATIONS…code illustration I

Scientific programming (fortran) 40


ajayiprogrammer@gmail.com

PROGRAM array_pro1

implicit none
INTEGER, DIMENSION (5):: my_array
INTEGER :: i
write(*,*) "Capturing Data into the Array"
write(*,*)
SPECIFIC ARRAY OPERATIONS…code illustration
do i = 1,5
write (*,*) "Element ", i, " : "
read (*,*)my_array(i)
end do
write (*,*) "The highest element in the array is: ", MAXVAL(my_array)
write (*,*) "The lowest element in the array is: ", MINVAL (my_array)
write (*,*) "The sum of the elements in the array is: ", SUMVAL(my_array)
write (*,*) "The whole array elements are: ", my_array
end program array_pro1

NB: Run the program and show the output to the next person close to you!

ARITHEMETIC AND LOGICAL OPERATIONS ON ARRAY

Some of the arithmetic operations that can be performed on ARRAY include but not limited to:

 Summation
 Multiplication
 Comparison

ARITHEMETIC AND LOGICAL OPERATIONS ON ARRAY…code illustration II

program array_pro4
implicit none
integer, dimension(4)::mydata,yourdata, sum_all_data, product_both_data
integer::i
do i = 1,4
write (*,*) "Enter value for array mydata element ", i, " : "
read (*,*) mydata(i)
write (*,*) "Enter value for array yourdata element ", i, " : "
read (*,*) yourdata(i)
sum_all_data(i)= mydata(i) + yourdata(i)
product_both_data(i) = mydata(i) * yourdata(i)
end do
end program array_pro4

…output!
Scientific programming (fortran) 41
ajayiprogrammer@gmail.com

MULTI-DIMENSIONAL ARRAY

An array that consist of rows and columns of data. It is also called MATRIX.

MULTI-DIMENSIONAL ARRAY - DECLARATION


data type, dimension(row_size, column_size)::matrix_name
e.g.

3 5 6 7
6 3 2 1
9 18 10 5

integer, dimension(2,4)::my_matrix
integer, dimension(2,5)::my_matrix1, my_matrix2
integer, dimension(2,3)::my_matrix1
integer, dimension(2,7)::my_matrix2

MULTI-DIMENSIONAL ARRAY – code illustration I

Scientific programming (fortran) 42


ajayiprogrammer@gmail.com

program matrix_pro
implicit none
integer, dimension(2,3)::mytable
integer i,j
write (*,*) "Capturing data into matrix"
do i=1,2
do j=1,3
write (*,*) "Enter data for Row ", i, " Column ", j
read (*,*) mytable(i,j)
write(*,*)
end do
end do
end program matrix_pro
MULTI-DIMENSIONAL ARRAY – output

MULTI-DIMENSIONAL ARRAY – code illustration I


program matrix_pro2
implicit none
integer, dimension(2,3)::mytable1
integer, dimension (3,5)::mytable2
Integer:: i,j
write (*,*) "Capturing data into matrix MYTABLE 1"
do i=1,2
do j=1,3
write (*,*) "Enter data for Row ", i, " Column ", j
read (*,*) mytable1(i,j)
write(*,*)
end do
end do
MULTI-DIMENSIONAL ARRAY – code illustration

Scientific programming (fortran) 43


ajayiprogrammer@gmail.com

write (*,*) "Capturing data into matrix MYTABLE 2"


do i=1,3
do j=1,5
write (*,*) "Enter data for Row ", i, " Column ", j
read (*,*) mytable2(i,j)
write(*,*)
end do
end do
end program matrix_pro2

MULTI-DIMENSIONAL ARRAY – output

Under Chapter Exercise (UCE) IV

Scientific programming (fortran) 44


ajayiprogrammer@gmail.com

Student’s Name: _________________________________________________________

Dept.: __________________________ Level: ________ M_No: IPTP2019/CSC/____

Instruction #1: Fill in the spaces left above, use the information to submit your assignment,
especially the M_No (meaning Material No)

Instruction #2: Solve using the system, print out and submit with the requested info in #1

Instruction #3: Submit before the exam

Questions

Q1

Modify the program in page 43 (Code Illustration I) such that:

 It computes the sum of the matrix mytable1


 It computes the average value of the matrix mytable2
 It computes the row-sum of the matrix mytable1
 It computes the column-sum of the matrix mytable2
 It transposes the elements of the two matrices mytable1 & mytable2
Q2

Assuming with me is N54,890. out of this, my intention is to have 2/3 of it to take care of my

domestic expenses, 35% for academic expenses, 65.7% for religious commitment, 2.3% for

electrical & utility bills, and 18.4% for miscellaneous expenses. Help FORTRAN-code my left-

over or deficit as the case may be. Your code must be such that logically detect if the expenses

resulted into left-over of deficit before executing the computation.

Q3

Quadratic equation is not a mathematical problem strange to you. Using FORTRAN, fully code

its implementation assuming values for the various variables it presents.

Q4

Scientific programming (fortran) 45


ajayiprogrammer@gmail.com

Coding/programming/developing software most times also require the need to search and acquire

generic or a particular domain knowledge before a particular task can be successfully

implemented. Weather forecasting is such a domain where u may need to do some searching to

know how the prediction is done. So, while preparing to code, pause a little, browse how weather

are been forecasted. From your search, code in FORTRAN to implement a generic weather

forecasting program.

Q5

Modify the program in page 41 (Code Illustration II) to output the values of sum_all_data and

product_both_data.

Extend the program such that it outputs:

 All elements in the mydata array

 All elements in the yourdata array

 The biggest element in the sum_all_data

 The smallest element in the product_both_data

Scientific programming (fortran) 46

You might also like